View.java revision 1454afce8255079ec4fc42220cd0dac2a86da2b6
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 java.lang.Math.max; 20 21import android.animation.AnimatorInflater; 22import android.animation.StateListAnimator; 23import android.annotation.CallSuper; 24import android.annotation.ColorInt; 25import android.annotation.DrawableRes; 26import android.annotation.FloatRange; 27import android.annotation.IdRes; 28import android.annotation.IntDef; 29import android.annotation.IntRange; 30import android.annotation.LayoutRes; 31import android.annotation.NonNull; 32import android.annotation.Nullable; 33import android.annotation.Size; 34import android.annotation.TestApi; 35import android.annotation.UiThread; 36import android.content.ClipData; 37import android.content.Context; 38import android.content.ContextWrapper; 39import android.content.Intent; 40import android.content.res.ColorStateList; 41import android.content.res.Configuration; 42import android.content.res.Resources; 43import android.content.res.TypedArray; 44import android.graphics.Bitmap; 45import android.graphics.Canvas; 46import android.graphics.Color; 47import android.graphics.Insets; 48import android.graphics.Interpolator; 49import android.graphics.LinearGradient; 50import android.graphics.Matrix; 51import android.graphics.Outline; 52import android.graphics.Paint; 53import android.graphics.PixelFormat; 54import android.graphics.Point; 55import android.graphics.PorterDuff; 56import android.graphics.PorterDuffXfermode; 57import android.graphics.Rect; 58import android.graphics.RectF; 59import android.graphics.Region; 60import android.graphics.Shader; 61import android.graphics.drawable.ColorDrawable; 62import android.graphics.drawable.Drawable; 63import android.hardware.display.DisplayManagerGlobal; 64import android.net.Uri; 65import android.os.Build; 66import android.os.Bundle; 67import android.os.Handler; 68import android.os.IBinder; 69import android.os.Message; 70import android.os.Parcel; 71import android.os.Parcelable; 72import android.os.RemoteException; 73import android.os.SystemClock; 74import android.os.SystemProperties; 75import android.os.Trace; 76import android.text.TextUtils; 77import android.util.AttributeSet; 78import android.util.FloatProperty; 79import android.util.LayoutDirection; 80import android.util.Log; 81import android.util.LongSparseLongArray; 82import android.util.Pools.SynchronizedPool; 83import android.util.Property; 84import android.util.SparseArray; 85import android.util.StateSet; 86import android.util.SuperNotCalledException; 87import android.util.TypedValue; 88import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 89import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 90import android.view.AccessibilityIterators.TextSegmentIterator; 91import android.view.AccessibilityIterators.WordTextSegmentIterator; 92import android.view.ContextMenu.ContextMenuInfo; 93import android.view.accessibility.AccessibilityEvent; 94import android.view.accessibility.AccessibilityEventSource; 95import android.view.accessibility.AccessibilityManager; 96import android.view.accessibility.AccessibilityNodeInfo; 97import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 98import android.view.accessibility.AccessibilityNodeProvider; 99import android.view.accessibility.AccessibilityWindowInfo; 100import android.view.animation.Animation; 101import android.view.animation.AnimationUtils; 102import android.view.animation.Transformation; 103import android.view.autofill.AutofillId; 104import android.view.autofill.AutofillManager; 105import android.view.autofill.AutofillValue; 106import android.view.inputmethod.EditorInfo; 107import android.view.inputmethod.InputConnection; 108import android.view.inputmethod.InputMethodManager; 109import android.widget.Checkable; 110import android.widget.FrameLayout; 111import android.widget.ScrollBarDrawable; 112 113import com.android.internal.R; 114import com.android.internal.view.TooltipPopup; 115import com.android.internal.view.menu.MenuBuilder; 116import com.android.internal.widget.ScrollBarUtils; 117 118import com.google.android.collect.Lists; 119import com.google.android.collect.Maps; 120 121import java.lang.annotation.Retention; 122import java.lang.annotation.RetentionPolicy; 123import java.lang.ref.WeakReference; 124import java.lang.reflect.Field; 125import java.lang.reflect.InvocationTargetException; 126import java.lang.reflect.Method; 127import java.lang.reflect.Modifier; 128import java.util.ArrayList; 129import java.util.Arrays; 130import java.util.Collection; 131import java.util.Collections; 132import java.util.HashMap; 133import java.util.List; 134import java.util.Locale; 135import java.util.Map; 136import java.util.concurrent.CopyOnWriteArrayList; 137import java.util.concurrent.atomic.AtomicInteger; 138import java.util.function.Predicate; 139 140/** 141 * <p> 142 * This class represents the basic building block for user interface components. A View 143 * occupies a rectangular area on the screen and is responsible for drawing and 144 * event handling. View is the base class for <em>widgets</em>, which are 145 * used to create interactive UI components (buttons, text fields, etc.). The 146 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 147 * are invisible containers that hold other Views (or other ViewGroups) and define 148 * their layout properties. 149 * </p> 150 * 151 * <div class="special reference"> 152 * <h3>Developer Guides</h3> 153 * <p>For information about using this class to develop your application's user interface, 154 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 155 * </div> 156 * 157 * <a name="Using"></a> 158 * <h3>Using Views</h3> 159 * <p> 160 * All of the views in a window are arranged in a single tree. You can add views 161 * either from code or by specifying a tree of views in one or more XML layout 162 * files. There are many specialized subclasses of views that act as controls or 163 * are capable of displaying text, images, or other content. 164 * </p> 165 * <p> 166 * Once you have created a tree of views, there are typically a few types of 167 * common operations you may wish to perform: 168 * <ul> 169 * <li><strong>Set properties:</strong> for example setting the text of a 170 * {@link android.widget.TextView}. The available properties and the methods 171 * that set them will vary among the different subclasses of views. Note that 172 * properties that are known at build time can be set in the XML layout 173 * files.</li> 174 * <li><strong>Set focus:</strong> The framework will handle moving focus in 175 * response to user input. To force focus to a specific view, call 176 * {@link #requestFocus}.</li> 177 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 178 * that will be notified when something interesting happens to the view. For 179 * example, all views will let you set a listener to be notified when the view 180 * gains or loses focus. You can register such a listener using 181 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 182 * Other view subclasses offer more specialized listeners. For example, a Button 183 * exposes a listener to notify clients when the button is clicked.</li> 184 * <li><strong>Set visibility:</strong> You can hide or show views using 185 * {@link #setVisibility(int)}.</li> 186 * </ul> 187 * </p> 188 * <p><em> 189 * Note: The Android framework is responsible for measuring, laying out and 190 * drawing views. You should not call methods that perform these actions on 191 * views yourself unless you are actually implementing a 192 * {@link android.view.ViewGroup}. 193 * </em></p> 194 * 195 * <a name="Lifecycle"></a> 196 * <h3>Implementing a Custom View</h3> 197 * 198 * <p> 199 * To implement a custom view, you will usually begin by providing overrides for 200 * some of the standard methods that the framework calls on all views. You do 201 * not need to override all of these methods. In fact, you can start by just 202 * overriding {@link #onDraw(android.graphics.Canvas)}. 203 * <table border="2" width="85%" align="center" cellpadding="5"> 204 * <thead> 205 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 206 * </thead> 207 * 208 * <tbody> 209 * <tr> 210 * <td rowspan="2">Creation</td> 211 * <td>Constructors</td> 212 * <td>There is a form of the constructor that are called when the view 213 * is created from code and a form that is called when the view is 214 * inflated from a layout file. The second form should parse and apply 215 * any attributes defined in the layout file. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onFinishInflate()}</code></td> 220 * <td>Called after a view and all of its children has been inflated 221 * from XML.</td> 222 * </tr> 223 * 224 * <tr> 225 * <td rowspan="3">Layout</td> 226 * <td><code>{@link #onMeasure(int, int)}</code></td> 227 * <td>Called to determine the size requirements for this view and all 228 * of its children. 229 * </td> 230 * </tr> 231 * <tr> 232 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 233 * <td>Called when this view should assign a size and position to all 234 * of its children. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 239 * <td>Called when the size of this view has changed. 240 * </td> 241 * </tr> 242 * 243 * <tr> 244 * <td>Drawing</td> 245 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 246 * <td>Called when the view should render its content. 247 * </td> 248 * </tr> 249 * 250 * <tr> 251 * <td rowspan="4">Event processing</td> 252 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 253 * <td>Called when a new hardware key event occurs. 254 * </td> 255 * </tr> 256 * <tr> 257 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 258 * <td>Called when a hardware key up event occurs. 259 * </td> 260 * </tr> 261 * <tr> 262 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 263 * <td>Called when a trackball motion event occurs. 264 * </td> 265 * </tr> 266 * <tr> 267 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 268 * <td>Called when a touch screen motion event occurs. 269 * </td> 270 * </tr> 271 * 272 * <tr> 273 * <td rowspan="2">Focus</td> 274 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 275 * <td>Called when the view gains or loses focus. 276 * </td> 277 * </tr> 278 * 279 * <tr> 280 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 281 * <td>Called when the window containing the view gains or loses focus. 282 * </td> 283 * </tr> 284 * 285 * <tr> 286 * <td rowspan="3">Attaching</td> 287 * <td><code>{@link #onAttachedToWindow()}</code></td> 288 * <td>Called when the view is attached to a window. 289 * </td> 290 * </tr> 291 * 292 * <tr> 293 * <td><code>{@link #onDetachedFromWindow}</code></td> 294 * <td>Called when the view is detached from its window. 295 * </td> 296 * </tr> 297 * 298 * <tr> 299 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 300 * <td>Called when the visibility of the window containing the view 301 * has changed. 302 * </td> 303 * </tr> 304 * </tbody> 305 * 306 * </table> 307 * </p> 308 * 309 * <a name="IDs"></a> 310 * <h3>IDs</h3> 311 * Views may have an integer id associated with them. These ids are typically 312 * assigned in the layout XML files, and are used to find specific views within 313 * the view tree. A common pattern is to: 314 * <ul> 315 * <li>Define a Button in the layout file and assign it a unique ID. 316 * <pre> 317 * <Button 318 * android:id="@+id/my_button" 319 * android:layout_width="wrap_content" 320 * android:layout_height="wrap_content" 321 * android:text="@string/my_button_text"/> 322 * </pre></li> 323 * <li>From the onCreate method of an Activity, find the Button 324 * <pre class="prettyprint"> 325 * Button myButton = findViewById(R.id.my_button); 326 * </pre></li> 327 * </ul> 328 * <p> 329 * View IDs need not be unique throughout the tree, but it is good practice to 330 * ensure that they are at least unique within the part of the tree you are 331 * searching. 332 * </p> 333 * 334 * <a name="Position"></a> 335 * <h3>Position</h3> 336 * <p> 337 * The geometry of a view is that of a rectangle. A view has a location, 338 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 339 * two dimensions, expressed as a width and a height. The unit for location 340 * and dimensions is the pixel. 341 * </p> 342 * 343 * <p> 344 * It is possible to retrieve the location of a view by invoking the methods 345 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 346 * coordinate of the rectangle representing the view. The latter returns the 347 * top, or Y, coordinate of the rectangle representing the view. These methods 348 * both return the location of the view relative to its parent. For instance, 349 * when getLeft() returns 20, that means the view is located 20 pixels to the 350 * right of the left edge of its direct parent. 351 * </p> 352 * 353 * <p> 354 * In addition, several convenience methods are offered to avoid unnecessary 355 * computations, namely {@link #getRight()} and {@link #getBottom()}. 356 * These methods return the coordinates of the right and bottom edges of the 357 * rectangle representing the view. For instance, calling {@link #getRight()} 358 * is similar to the following computation: <code>getLeft() + getWidth()</code> 359 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 360 * </p> 361 * 362 * <a name="SizePaddingMargins"></a> 363 * <h3>Size, padding and margins</h3> 364 * <p> 365 * The size of a view is expressed with a width and a height. A view actually 366 * possess two pairs of width and height values. 367 * </p> 368 * 369 * <p> 370 * The first pair is known as <em>measured width</em> and 371 * <em>measured height</em>. These dimensions define how big a view wants to be 372 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 373 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 374 * and {@link #getMeasuredHeight()}. 375 * </p> 376 * 377 * <p> 378 * The second pair is simply known as <em>width</em> and <em>height</em>, or 379 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 380 * dimensions define the actual size of the view on screen, at drawing time and 381 * after layout. These values may, but do not have to, be different from the 382 * measured width and height. The width and height can be obtained by calling 383 * {@link #getWidth()} and {@link #getHeight()}. 384 * </p> 385 * 386 * <p> 387 * To measure its dimensions, a view takes into account its padding. The padding 388 * is expressed in pixels for the left, top, right and bottom parts of the view. 389 * Padding can be used to offset the content of the view by a specific amount of 390 * pixels. For instance, a left padding of 2 will push the view's content by 391 * 2 pixels to the right of the left edge. Padding can be set using the 392 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 393 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 394 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 395 * {@link #getPaddingEnd()}. 396 * </p> 397 * 398 * <p> 399 * Even though a view can define a padding, it does not provide any support for 400 * margins. However, view groups provide such a support. Refer to 401 * {@link android.view.ViewGroup} and 402 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 403 * </p> 404 * 405 * <a name="Layout"></a> 406 * <h3>Layout</h3> 407 * <p> 408 * Layout is a two pass process: a measure pass and a layout pass. The measuring 409 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 410 * of the view tree. Each view pushes dimension specifications down the tree 411 * during the recursion. At the end of the measure pass, every view has stored 412 * its measurements. The second pass happens in 413 * {@link #layout(int,int,int,int)} and is also top-down. During 414 * this pass each parent is responsible for positioning all of its children 415 * using the sizes computed in the measure pass. 416 * </p> 417 * 418 * <p> 419 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 420 * {@link #getMeasuredHeight()} values must be set, along with those for all of 421 * that view's descendants. A view's measured width and measured height values 422 * must respect the constraints imposed by the view's parents. This guarantees 423 * that at the end of the measure pass, all parents accept all of their 424 * children's measurements. A parent view may call measure() more than once on 425 * its children. For example, the parent may measure each child once with 426 * unspecified dimensions to find out how big they want to be, then call 427 * measure() on them again with actual numbers if the sum of all the children's 428 * unconstrained sizes is too big or too small. 429 * </p> 430 * 431 * <p> 432 * The measure pass uses two classes to communicate dimensions. The 433 * {@link MeasureSpec} class is used by views to tell their parents how they 434 * want to be measured and positioned. The base LayoutParams class just 435 * describes how big the view wants to be for both width and height. For each 436 * dimension, it can specify one of: 437 * <ul> 438 * <li> an exact number 439 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 440 * (minus padding) 441 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 442 * enclose its content (plus padding). 443 * </ul> 444 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 445 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 446 * an X and Y value. 447 * </p> 448 * 449 * <p> 450 * MeasureSpecs are used to push requirements down the tree from parent to 451 * child. A MeasureSpec can be in one of three modes: 452 * <ul> 453 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 454 * of a child view. For example, a LinearLayout may call measure() on its child 455 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 456 * tall the child view wants to be given a width of 240 pixels. 457 * <li>EXACTLY: This is used by the parent to impose an exact size on the 458 * child. The child must use this size, and guarantee that all of its 459 * descendants will fit within this size. 460 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 461 * child. The child must guarantee that it and all of its descendants will fit 462 * within this size. 463 * </ul> 464 * </p> 465 * 466 * <p> 467 * To initiate a layout, call {@link #requestLayout}. This method is typically 468 * called by a view on itself when it believes that is can no longer fit within 469 * its current bounds. 470 * </p> 471 * 472 * <a name="Drawing"></a> 473 * <h3>Drawing</h3> 474 * <p> 475 * Drawing is handled by walking the tree and recording the drawing commands of 476 * any View that needs to update. After this, the drawing commands of the 477 * entire tree are issued to screen, clipped to the newly damaged area. 478 * </p> 479 * 480 * <p> 481 * The tree is largely recorded and drawn in order, with parents drawn before 482 * (i.e., behind) their children, with siblings drawn in the order they appear 483 * in the tree. If you set a background drawable for a View, then the View will 484 * draw it before calling back to its <code>onDraw()</code> method. The child 485 * drawing order can be overridden with 486 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 487 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 488 * </p> 489 * 490 * <p> 491 * To force a view to draw, call {@link #invalidate()}. 492 * </p> 493 * 494 * <a name="EventHandlingThreading"></a> 495 * <h3>Event Handling and Threading</h3> 496 * <p> 497 * The basic cycle of a view is as follows: 498 * <ol> 499 * <li>An event comes in and is dispatched to the appropriate view. The view 500 * handles the event and notifies any listeners.</li> 501 * <li>If in the course of processing the event, the view's bounds may need 502 * to be changed, the view will call {@link #requestLayout()}.</li> 503 * <li>Similarly, if in the course of processing the event the view's appearance 504 * may need to be changed, the view will call {@link #invalidate()}.</li> 505 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 506 * the framework will take care of measuring, laying out, and drawing the tree 507 * as appropriate.</li> 508 * </ol> 509 * </p> 510 * 511 * <p><em>Note: The entire view tree is single threaded. You must always be on 512 * the UI thread when calling any method on any view.</em> 513 * If you are doing work on other threads and want to update the state of a view 514 * from that thread, you should use a {@link Handler}. 515 * </p> 516 * 517 * <a name="FocusHandling"></a> 518 * <h3>Focus Handling</h3> 519 * <p> 520 * The framework will handle routine focus movement in response to user input. 521 * This includes changing the focus as views are removed or hidden, or as new 522 * views become available. Views indicate their willingness to take focus 523 * through the {@link #isFocusable} method. To change whether a view can take 524 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 525 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 526 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 527 * </p> 528 * <p> 529 * Focus movement is based on an algorithm which finds the nearest neighbor in a 530 * given direction. In rare cases, the default algorithm may not match the 531 * intended behavior of the developer. In these situations, you can provide 532 * explicit overrides by using these XML attributes in the layout file: 533 * <pre> 534 * nextFocusDown 535 * nextFocusLeft 536 * nextFocusRight 537 * nextFocusUp 538 * </pre> 539 * </p> 540 * 541 * 542 * <p> 543 * To get a particular view to take focus, call {@link #requestFocus()}. 544 * </p> 545 * 546 * <a name="TouchMode"></a> 547 * <h3>Touch Mode</h3> 548 * <p> 549 * When a user is navigating a user interface via directional keys such as a D-pad, it is 550 * necessary to give focus to actionable items such as buttons so the user can see 551 * what will take input. If the device has touch capabilities, however, and the user 552 * begins interacting with the interface by touching it, it is no longer necessary to 553 * always highlight, or give focus to, a particular view. This motivates a mode 554 * for interaction named 'touch mode'. 555 * </p> 556 * <p> 557 * For a touch capable device, once the user touches the screen, the device 558 * will enter touch mode. From this point onward, only views for which 559 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 560 * Other views that are touchable, like buttons, will not take focus when touched; they will 561 * only fire the on click listeners. 562 * </p> 563 * <p> 564 * Any time a user hits a directional key, such as a D-pad direction, the view device will 565 * exit touch mode, and find a view to take focus, so that the user may resume interacting 566 * with the user interface without touching the screen again. 567 * </p> 568 * <p> 569 * The touch mode state is maintained across {@link android.app.Activity}s. Call 570 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 571 * </p> 572 * 573 * <a name="Scrolling"></a> 574 * <h3>Scrolling</h3> 575 * <p> 576 * The framework provides basic support for views that wish to internally 577 * scroll their content. This includes keeping track of the X and Y scroll 578 * offset as well as mechanisms for drawing scrollbars. See 579 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 580 * {@link #awakenScrollBars()} for more details. 581 * </p> 582 * 583 * <a name="Tags"></a> 584 * <h3>Tags</h3> 585 * <p> 586 * Unlike IDs, tags are not used to identify views. Tags are essentially an 587 * extra piece of information that can be associated with a view. They are most 588 * often used as a convenience to store data related to views in the views 589 * themselves rather than by putting them in a separate structure. 590 * </p> 591 * <p> 592 * Tags may be specified with character sequence values in layout XML as either 593 * a single tag using the {@link android.R.styleable#View_tag android:tag} 594 * attribute or multiple tags using the {@code <tag>} child element: 595 * <pre> 596 * <View ... 597 * android:tag="@string/mytag_value" /> 598 * <View ...> 599 * <tag android:id="@+id/mytag" 600 * android:value="@string/mytag_value" /> 601 * </View> 602 * </pre> 603 * </p> 604 * <p> 605 * Tags may also be specified with arbitrary objects from code using 606 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 607 * </p> 608 * 609 * <a name="Themes"></a> 610 * <h3>Themes</h3> 611 * <p> 612 * By default, Views are created using the theme of the Context object supplied 613 * to their constructor; however, a different theme may be specified by using 614 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 615 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 616 * code. 617 * </p> 618 * <p> 619 * When the {@link android.R.styleable#View_theme android:theme} attribute is 620 * used in XML, the specified theme is applied on top of the inflation 621 * context's theme (see {@link LayoutInflater}) and used for the view itself as 622 * well as any child elements. 623 * </p> 624 * <p> 625 * In the following example, both views will be created using the Material dark 626 * color scheme; however, because an overlay theme is used which only defines a 627 * subset of attributes, the value of 628 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 629 * the inflation context's theme (e.g. the Activity theme) will be preserved. 630 * <pre> 631 * <LinearLayout 632 * ... 633 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 634 * <View ...> 635 * </LinearLayout> 636 * </pre> 637 * </p> 638 * 639 * <a name="Properties"></a> 640 * <h3>Properties</h3> 641 * <p> 642 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 643 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 644 * available both in the {@link Property} form as well as in similarly-named setter/getter 645 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 646 * be used to set persistent state associated with these rendering-related properties on the view. 647 * The properties and methods can also be used in conjunction with 648 * {@link android.animation.Animator Animator}-based animations, described more in the 649 * <a href="#Animation">Animation</a> section. 650 * </p> 651 * 652 * <a name="Animation"></a> 653 * <h3>Animation</h3> 654 * <p> 655 * Starting with Android 3.0, the preferred way of animating views is to use the 656 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 657 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 658 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 659 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 660 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 661 * makes animating these View properties particularly easy and efficient. 662 * </p> 663 * <p> 664 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 665 * You can attach an {@link Animation} object to a view using 666 * {@link #setAnimation(Animation)} or 667 * {@link #startAnimation(Animation)}. The animation can alter the scale, 668 * rotation, translation and alpha of a view over time. If the animation is 669 * attached to a view that has children, the animation will affect the entire 670 * subtree rooted by that node. When an animation is started, the framework will 671 * take care of redrawing the appropriate views until the animation completes. 672 * </p> 673 * 674 * <a name="Security"></a> 675 * <h3>Security</h3> 676 * <p> 677 * Sometimes it is essential that an application be able to verify that an action 678 * is being performed with the full knowledge and consent of the user, such as 679 * granting a permission request, making a purchase or clicking on an advertisement. 680 * Unfortunately, a malicious application could try to spoof the user into 681 * performing these actions, unaware, by concealing the intended purpose of the view. 682 * As a remedy, the framework offers a touch filtering mechanism that can be used to 683 * improve the security of views that provide access to sensitive functionality. 684 * </p><p> 685 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 686 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 687 * will discard touches that are received whenever the view's window is obscured by 688 * another visible window. As a result, the view will not receive touches whenever a 689 * toast, dialog or other window appears above the view's window. 690 * </p><p> 691 * For more fine-grained control over security, consider overriding the 692 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 693 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 694 * </p> 695 * 696 * @attr ref android.R.styleable#View_alpha 697 * @attr ref android.R.styleable#View_background 698 * @attr ref android.R.styleable#View_clickable 699 * @attr ref android.R.styleable#View_contentDescription 700 * @attr ref android.R.styleable#View_drawingCacheQuality 701 * @attr ref android.R.styleable#View_duplicateParentState 702 * @attr ref android.R.styleable#View_id 703 * @attr ref android.R.styleable#View_requiresFadingEdge 704 * @attr ref android.R.styleable#View_fadeScrollbars 705 * @attr ref android.R.styleable#View_fadingEdgeLength 706 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 707 * @attr ref android.R.styleable#View_fitsSystemWindows 708 * @attr ref android.R.styleable#View_isScrollContainer 709 * @attr ref android.R.styleable#View_focusable 710 * @attr ref android.R.styleable#View_focusableInTouchMode 711 * @attr ref android.R.styleable#View_focusedByDefault 712 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 713 * @attr ref android.R.styleable#View_keepScreenOn 714 * @attr ref android.R.styleable#View_keyboardNavigationCluster 715 * @attr ref android.R.styleable#View_layerType 716 * @attr ref android.R.styleable#View_layoutDirection 717 * @attr ref android.R.styleable#View_longClickable 718 * @attr ref android.R.styleable#View_minHeight 719 * @attr ref android.R.styleable#View_minWidth 720 * @attr ref android.R.styleable#View_nextClusterForward 721 * @attr ref android.R.styleable#View_nextFocusDown 722 * @attr ref android.R.styleable#View_nextFocusLeft 723 * @attr ref android.R.styleable#View_nextFocusRight 724 * @attr ref android.R.styleable#View_nextFocusUp 725 * @attr ref android.R.styleable#View_onClick 726 * @attr ref android.R.styleable#View_padding 727 * @attr ref android.R.styleable#View_paddingBottom 728 * @attr ref android.R.styleable#View_paddingLeft 729 * @attr ref android.R.styleable#View_paddingRight 730 * @attr ref android.R.styleable#View_paddingTop 731 * @attr ref android.R.styleable#View_paddingStart 732 * @attr ref android.R.styleable#View_paddingEnd 733 * @attr ref android.R.styleable#View_saveEnabled 734 * @attr ref android.R.styleable#View_rotation 735 * @attr ref android.R.styleable#View_rotationX 736 * @attr ref android.R.styleable#View_rotationY 737 * @attr ref android.R.styleable#View_scaleX 738 * @attr ref android.R.styleable#View_scaleY 739 * @attr ref android.R.styleable#View_scrollX 740 * @attr ref android.R.styleable#View_scrollY 741 * @attr ref android.R.styleable#View_scrollbarSize 742 * @attr ref android.R.styleable#View_scrollbarStyle 743 * @attr ref android.R.styleable#View_scrollbars 744 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 745 * @attr ref android.R.styleable#View_scrollbarFadeDuration 746 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 747 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 748 * @attr ref android.R.styleable#View_scrollbarThumbVertical 749 * @attr ref android.R.styleable#View_scrollbarTrackVertical 750 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 751 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 752 * @attr ref android.R.styleable#View_stateListAnimator 753 * @attr ref android.R.styleable#View_transitionName 754 * @attr ref android.R.styleable#View_soundEffectsEnabled 755 * @attr ref android.R.styleable#View_tag 756 * @attr ref android.R.styleable#View_textAlignment 757 * @attr ref android.R.styleable#View_textDirection 758 * @attr ref android.R.styleable#View_transformPivotX 759 * @attr ref android.R.styleable#View_transformPivotY 760 * @attr ref android.R.styleable#View_translationX 761 * @attr ref android.R.styleable#View_translationY 762 * @attr ref android.R.styleable#View_translationZ 763 * @attr ref android.R.styleable#View_visibility 764 * @attr ref android.R.styleable#View_theme 765 * 766 * @see android.view.ViewGroup 767 */ 768@UiThread 769public class View implements Drawable.Callback, KeyEvent.Callback, 770 AccessibilityEventSource { 771 private static final boolean DBG = false; 772 773 /** @hide */ 774 public static boolean DEBUG_DRAW = false; 775 776 /** 777 * The logging tag used by this class with android.util.Log. 778 */ 779 protected static final String VIEW_LOG_TAG = "View"; 780 781 /** 782 * When set to true, apps will draw debugging information about their layouts. 783 * 784 * @hide 785 */ 786 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 787 788 /** 789 * When set to true, this view will save its attribute data. 790 * 791 * @hide 792 */ 793 public static boolean mDebugViewAttributes = false; 794 795 /** 796 * Used to mark a View that has no ID. 797 */ 798 public static final int NO_ID = -1; 799 800 /** 801 * Last ID that is given to Views that are no part of activities. 802 * 803 * {@hide} 804 */ 805 public static final int LAST_APP_ACCESSIBILITY_ID = Integer.MAX_VALUE / 2; 806 807 /** 808 * Attribute to find the autofilled highlight 809 * 810 * @see #getAutofilledDrawable() 811 */ 812 private static final int[] AUTOFILL_HIGHLIGHT_ATTR = 813 new int[]{android.R.attr.autofilledHighlight}; 814 815 /** 816 * Signals that compatibility booleans have been initialized according to 817 * target SDK versions. 818 */ 819 private static boolean sCompatibilityDone = false; 820 821 /** 822 * Use the old (broken) way of building MeasureSpecs. 823 */ 824 private static boolean sUseBrokenMakeMeasureSpec = false; 825 826 /** 827 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 828 */ 829 static boolean sUseZeroUnspecifiedMeasureSpec = false; 830 831 /** 832 * Ignore any optimizations using the measure cache. 833 */ 834 private static boolean sIgnoreMeasureCache = false; 835 836 /** 837 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 838 */ 839 private static boolean sAlwaysRemeasureExactly = false; 840 841 /** 842 * Relax constraints around whether setLayoutParams() must be called after 843 * modifying the layout params. 844 */ 845 private static boolean sLayoutParamsAlwaysChanged = false; 846 847 /** 848 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 849 * without throwing 850 */ 851 static boolean sTextureViewIgnoresDrawableSetters = false; 852 853 /** 854 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 855 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 856 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 857 * check is implemented for backwards compatibility. 858 * 859 * {@hide} 860 */ 861 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 862 863 /** 864 * Prior to N, when drag enters into child of a view that has already received an 865 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 866 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 867 * false from its event handler for these events. 868 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 869 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 870 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 871 */ 872 static boolean sCascadedDragDrop; 873 874 /** 875 * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable 876 * to determine things like whether or not to permit item click events. We can't break 877 * apps that do this just because more things (clickable things) are now auto-focusable 878 * and they would get different results, so give old behavior to old apps. 879 */ 880 static boolean sHasFocusableExcludeAutoFocusable; 881 882 /** 883 * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly 884 * made focusable by default. As a result, apps could (incorrectly) change the clickable 885 * setting of views off the UI thread. Now that clickable can effect the focusable state, 886 * changing the clickable attribute off the UI thread will cause an exception (since changing 887 * the focusable state checks). In order to prevent apps from crashing, we will handle this 888 * specific case and just not notify parents on new focusables resulting from marking views 889 * clickable from outside the UI thread. 890 */ 891 private static boolean sAutoFocusableOffUIThreadWontNotifyParents; 892 893 /** @hide */ 894 @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO}) 895 @Retention(RetentionPolicy.SOURCE) 896 public @interface Focusable {} 897 898 /** 899 * This view does not want keystrokes. 900 * <p> 901 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 902 * android:focusable}. 903 */ 904 public static final int NOT_FOCUSABLE = 0x00000000; 905 906 /** 907 * This view wants keystrokes. 908 * <p> 909 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 910 * android:focusable}. 911 */ 912 public static final int FOCUSABLE = 0x00000001; 913 914 /** 915 * This view determines focusability automatically. This is the default. 916 * <p> 917 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 918 * android:focusable}. 919 */ 920 public static final int FOCUSABLE_AUTO = 0x00000010; 921 922 /** 923 * Mask for use with setFlags indicating bits used for focus. 924 */ 925 private static final int FOCUSABLE_MASK = 0x00000011; 926 927 /** 928 * This view will adjust its padding to fit sytem windows (e.g. status bar) 929 */ 930 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 931 932 /** @hide */ 933 @IntDef({VISIBLE, INVISIBLE, GONE}) 934 @Retention(RetentionPolicy.SOURCE) 935 public @interface Visibility {} 936 937 /** 938 * This view is visible. 939 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 940 * android:visibility}. 941 */ 942 public static final int VISIBLE = 0x00000000; 943 944 /** 945 * This view is invisible, but it still takes up space for layout purposes. 946 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 947 * android:visibility}. 948 */ 949 public static final int INVISIBLE = 0x00000004; 950 951 /** 952 * This view is invisible, and it doesn't take any space for layout 953 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 954 * android:visibility}. 955 */ 956 public static final int GONE = 0x00000008; 957 958 /** 959 * Mask for use with setFlags indicating bits used for visibility. 960 * {@hide} 961 */ 962 static final int VISIBILITY_MASK = 0x0000000C; 963 964 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 965 966 /** 967 * This view contains an email address. 968 * 969 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_EMAIL_ADDRESS}" 970 * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 971 */ 972 public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress"; 973 974 /** 975 * The view contains a real name. 976 * 977 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_NAME}" to 978 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 979 */ 980 public static final String AUTOFILL_HINT_NAME = "name"; 981 982 /** 983 * The view contains a user name. 984 * 985 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_USERNAME}" to 986 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 987 */ 988 public static final String AUTOFILL_HINT_USERNAME = "username"; 989 990 /** 991 * The view contains a password. 992 * 993 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PASSWORD}" to 994 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 995 */ 996 public static final String AUTOFILL_HINT_PASSWORD = "password"; 997 998 /** 999 * The view contains a phone number. 1000 * 1001 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PHONE}" to 1002 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1003 */ 1004 public static final String AUTOFILL_HINT_PHONE = "phone"; 1005 1006 /** 1007 * The view contains a postal address. 1008 * 1009 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_ADDRESS}" 1010 * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1011 */ 1012 public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress"; 1013 1014 /** 1015 * The view contains a postal code. 1016 * 1017 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_CODE}" to 1018 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1019 */ 1020 public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode"; 1021 1022 /** 1023 * The view contains a credit card number. 1024 * 1025 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1026 * #AUTOFILL_HINT_CREDIT_CARD_NUMBER}" to <a href="#attr_android:autofillHint"> {@code 1027 * android:autofillHint}. 1028 */ 1029 public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber"; 1030 1031 /** 1032 * The view contains a credit card security code. 1033 * 1034 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1035 * #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}" to <a href="#attr_android:autofillHint"> {@code 1036 * android:autofillHint}. 1037 */ 1038 public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"; 1039 1040 /** 1041 * The view contains a credit card expiration date. 1042 * 1043 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1044 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}" to <a href="#attr_android:autofillHint"> {@code 1045 * android:autofillHint}. 1046 */ 1047 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = 1048 "creditCardExpirationDate"; 1049 1050 /** 1051 * The view contains the month a credit card expires. 1052 * 1053 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1054 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}" to <a href="#attr_android:autofillHint"> {@code 1055 * android:autofillHint}. 1056 */ 1057 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = 1058 "creditCardExpirationMonth"; 1059 1060 /** 1061 * The view contains the year a credit card expires. 1062 * 1063 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1064 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}" to <a href="#attr_android:autofillHint"> {@code 1065 * android:autofillHint}. 1066 */ 1067 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = 1068 "creditCardExpirationYear"; 1069 1070 /** 1071 * The view contains the day a credit card expires. 1072 * 1073 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1074 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}" to <a href="#attr_android:autofillHint"> {@code 1075 * android:autofillHint}. 1076 */ 1077 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"; 1078 1079 /** 1080 * Hints for the autofill services that describes the content of the view. 1081 */ 1082 private @Nullable String[] mAutofillHints; 1083 1084 /** 1085 * Autofill id, lazily created on calls to {@link #getAutofillId()}. 1086 */ 1087 private AutofillId mAutofillId; 1088 1089 /** @hide */ 1090 @IntDef({ 1091 AUTOFILL_TYPE_NONE, 1092 AUTOFILL_TYPE_TEXT, 1093 AUTOFILL_TYPE_TOGGLE, 1094 AUTOFILL_TYPE_LIST, 1095 AUTOFILL_TYPE_DATE 1096 }) 1097 @Retention(RetentionPolicy.SOURCE) 1098 public @interface AutofillType {} 1099 1100 /** 1101 * Autofill type for views that cannot be autofilled. 1102 */ 1103 public static final int AUTOFILL_TYPE_NONE = 0; 1104 1105 /** 1106 * Autofill type for a text field, which is filled by a {@link CharSequence}. 1107 * 1108 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1109 * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a 1110 * {@link View} can be fetched through {@link AutofillValue#getTextValue()}. 1111 */ 1112 public static final int AUTOFILL_TYPE_TEXT = 1; 1113 1114 /** 1115 * Autofill type for a togglable field, which is filled by a {@code boolean}. 1116 * 1117 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1118 * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a 1119 * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}. 1120 */ 1121 public static final int AUTOFILL_TYPE_TOGGLE = 2; 1122 1123 /** 1124 * Autofill type for a selection list field, which is filled by an {@code int} 1125 * representing the element index inside the list (starting at {@code 0}). 1126 * 1127 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1128 * {@link AutofillValue#forList(int)}, and the value passed to autofill a 1129 * {@link View} can be fetched through {@link AutofillValue#getListValue()}. 1130 * 1131 * <p>The available options in the selection list are typically provided by 1132 * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}. 1133 */ 1134 public static final int AUTOFILL_TYPE_LIST = 3; 1135 1136 1137 /** 1138 * Autofill type for a field that contains a date, which is represented by a long representing 1139 * the number of milliseconds since the standard base time known as "the epoch", namely 1140 * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}. 1141 * 1142 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1143 * {@link AutofillValue#forDate(long)}, and the values passed to 1144 * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}. 1145 */ 1146 public static final int AUTOFILL_TYPE_DATE = 4; 1147 1148 /** @hide */ 1149 @IntDef({ 1150 IMPORTANT_FOR_AUTOFILL_AUTO, 1151 IMPORTANT_FOR_AUTOFILL_YES, 1152 IMPORTANT_FOR_AUTOFILL_NO, 1153 IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS, 1154 IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 1155 }) 1156 @Retention(RetentionPolicy.SOURCE) 1157 public @interface AutofillImportance {} 1158 1159 /** 1160 * Automatically determine whether a view is important for autofill. 1161 */ 1162 public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0; 1163 1164 /** 1165 * The view is important for autofill, and its children (if any) will be traversed. 1166 */ 1167 public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1; 1168 1169 /** 1170 * The view is not important for autofill, but its children (if any) will be traversed. 1171 */ 1172 public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2; 1173 1174 /** 1175 * The view is important for autofill, but its children (if any) will not be traversed. 1176 */ 1177 public static final int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS = 0x4; 1178 1179 /** 1180 * The view is not important for autofill, and its children (if any) will not be traversed. 1181 */ 1182 public static final int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS = 0x8; 1183 1184 /** @hide */ 1185 @IntDef( 1186 flag = true, 1187 value = {AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS}) 1188 @Retention(RetentionPolicy.SOURCE) 1189 public @interface AutofillFlags {} 1190 1191 /** 1192 * Flag requesting you to add views not-important for autofill to the assist data. 1193 */ 1194 public static final int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS = 0x1; 1195 1196 /** 1197 * This view is enabled. Interpretation varies by subclass. 1198 * Use with ENABLED_MASK when calling setFlags. 1199 * {@hide} 1200 */ 1201 static final int ENABLED = 0x00000000; 1202 1203 /** 1204 * This view is disabled. Interpretation varies by subclass. 1205 * Use with ENABLED_MASK when calling setFlags. 1206 * {@hide} 1207 */ 1208 static final int DISABLED = 0x00000020; 1209 1210 /** 1211 * Mask for use with setFlags indicating bits used for indicating whether 1212 * this view is enabled 1213 * {@hide} 1214 */ 1215 static final int ENABLED_MASK = 0x00000020; 1216 1217 /** 1218 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 1219 * called and further optimizations will be performed. It is okay to have 1220 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 1221 * {@hide} 1222 */ 1223 static final int WILL_NOT_DRAW = 0x00000080; 1224 1225 /** 1226 * Mask for use with setFlags indicating bits used for indicating whether 1227 * this view is will draw 1228 * {@hide} 1229 */ 1230 static final int DRAW_MASK = 0x00000080; 1231 1232 /** 1233 * <p>This view doesn't show scrollbars.</p> 1234 * {@hide} 1235 */ 1236 static final int SCROLLBARS_NONE = 0x00000000; 1237 1238 /** 1239 * <p>This view shows horizontal scrollbars.</p> 1240 * {@hide} 1241 */ 1242 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 1243 1244 /** 1245 * <p>This view shows vertical scrollbars.</p> 1246 * {@hide} 1247 */ 1248 static final int SCROLLBARS_VERTICAL = 0x00000200; 1249 1250 /** 1251 * <p>Mask for use with setFlags indicating bits used for indicating which 1252 * scrollbars are enabled.</p> 1253 * {@hide} 1254 */ 1255 static final int SCROLLBARS_MASK = 0x00000300; 1256 1257 /** 1258 * Indicates that the view should filter touches when its window is obscured. 1259 * Refer to the class comments for more information about this security feature. 1260 * {@hide} 1261 */ 1262 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 1263 1264 /** 1265 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 1266 * that they are optional and should be skipped if the window has 1267 * requested system UI flags that ignore those insets for layout. 1268 */ 1269 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 1270 1271 /** 1272 * <p>This view doesn't show fading edges.</p> 1273 * {@hide} 1274 */ 1275 static final int FADING_EDGE_NONE = 0x00000000; 1276 1277 /** 1278 * <p>This view shows horizontal fading edges.</p> 1279 * {@hide} 1280 */ 1281 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 1282 1283 /** 1284 * <p>This view shows vertical fading edges.</p> 1285 * {@hide} 1286 */ 1287 static final int FADING_EDGE_VERTICAL = 0x00002000; 1288 1289 /** 1290 * <p>Mask for use with setFlags indicating bits used for indicating which 1291 * fading edges are enabled.</p> 1292 * {@hide} 1293 */ 1294 static final int FADING_EDGE_MASK = 0x00003000; 1295 1296 /** 1297 * <p>Indicates this view can be clicked. When clickable, a View reacts 1298 * to clicks by notifying the OnClickListener.<p> 1299 * {@hide} 1300 */ 1301 static final int CLICKABLE = 0x00004000; 1302 1303 /** 1304 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1305 * {@hide} 1306 */ 1307 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1308 1309 /** 1310 * <p>Indicates that no icicle should be saved for this view.<p> 1311 * {@hide} 1312 */ 1313 static final int SAVE_DISABLED = 0x000010000; 1314 1315 /** 1316 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1317 * property.</p> 1318 * {@hide} 1319 */ 1320 static final int SAVE_DISABLED_MASK = 0x000010000; 1321 1322 /** 1323 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1324 * {@hide} 1325 */ 1326 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1327 1328 /** 1329 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1330 * {@hide} 1331 */ 1332 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1333 1334 /** @hide */ 1335 @Retention(RetentionPolicy.SOURCE) 1336 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1337 public @interface DrawingCacheQuality {} 1338 1339 /** 1340 * <p>Enables low quality mode for the drawing cache.</p> 1341 */ 1342 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1343 1344 /** 1345 * <p>Enables high quality mode for the drawing cache.</p> 1346 */ 1347 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1348 1349 /** 1350 * <p>Enables automatic quality mode for the drawing cache.</p> 1351 */ 1352 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1353 1354 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1355 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1356 }; 1357 1358 /** 1359 * <p>Mask for use with setFlags indicating bits used for the cache 1360 * quality property.</p> 1361 * {@hide} 1362 */ 1363 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1364 1365 /** 1366 * <p> 1367 * Indicates this view can be long clicked. When long clickable, a View 1368 * reacts to long clicks by notifying the OnLongClickListener or showing a 1369 * context menu. 1370 * </p> 1371 * {@hide} 1372 */ 1373 static final int LONG_CLICKABLE = 0x00200000; 1374 1375 /** 1376 * <p>Indicates that this view gets its drawable states from its direct parent 1377 * and ignores its original internal states.</p> 1378 * 1379 * @hide 1380 */ 1381 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1382 1383 /** 1384 * <p> 1385 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1386 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1387 * OnContextClickListener. 1388 * </p> 1389 * {@hide} 1390 */ 1391 static final int CONTEXT_CLICKABLE = 0x00800000; 1392 1393 1394 /** @hide */ 1395 @IntDef({ 1396 SCROLLBARS_INSIDE_OVERLAY, 1397 SCROLLBARS_INSIDE_INSET, 1398 SCROLLBARS_OUTSIDE_OVERLAY, 1399 SCROLLBARS_OUTSIDE_INSET 1400 }) 1401 @Retention(RetentionPolicy.SOURCE) 1402 public @interface ScrollBarStyle {} 1403 1404 /** 1405 * The scrollbar style to display the scrollbars inside the content area, 1406 * without increasing the padding. The scrollbars will be overlaid with 1407 * translucency on the view's content. 1408 */ 1409 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1410 1411 /** 1412 * The scrollbar style to display the scrollbars inside the padded area, 1413 * increasing the padding of the view. The scrollbars will not overlap the 1414 * content area of the view. 1415 */ 1416 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1417 1418 /** 1419 * The scrollbar style to display the scrollbars at the edge of the view, 1420 * without increasing the padding. The scrollbars will be overlaid with 1421 * translucency. 1422 */ 1423 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1424 1425 /** 1426 * The scrollbar style to display the scrollbars at the edge of the view, 1427 * increasing the padding of the view. The scrollbars will only overlap the 1428 * background, if any. 1429 */ 1430 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1431 1432 /** 1433 * Mask to check if the scrollbar style is overlay or inset. 1434 * {@hide} 1435 */ 1436 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1437 1438 /** 1439 * Mask to check if the scrollbar style is inside or outside. 1440 * {@hide} 1441 */ 1442 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1443 1444 /** 1445 * Mask for scrollbar style. 1446 * {@hide} 1447 */ 1448 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1449 1450 /** 1451 * View flag indicating that the screen should remain on while the 1452 * window containing this view is visible to the user. This effectively 1453 * takes care of automatically setting the WindowManager's 1454 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1455 */ 1456 public static final int KEEP_SCREEN_ON = 0x04000000; 1457 1458 /** 1459 * View flag indicating whether this view should have sound effects enabled 1460 * for events such as clicking and touching. 1461 */ 1462 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1463 1464 /** 1465 * View flag indicating whether this view should have haptic feedback 1466 * enabled for events such as long presses. 1467 */ 1468 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1469 1470 /** 1471 * <p>Indicates that the view hierarchy should stop saving state when 1472 * it reaches this view. If state saving is initiated immediately at 1473 * the view, it will be allowed. 1474 * {@hide} 1475 */ 1476 static final int PARENT_SAVE_DISABLED = 0x20000000; 1477 1478 /** 1479 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1480 * {@hide} 1481 */ 1482 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1483 1484 private static Paint sDebugPaint; 1485 1486 /** 1487 * <p>Indicates this view can display a tooltip on hover or long press.</p> 1488 * {@hide} 1489 */ 1490 static final int TOOLTIP = 0x40000000; 1491 1492 /** @hide */ 1493 @IntDef(flag = true, 1494 value = { 1495 FOCUSABLES_ALL, 1496 FOCUSABLES_TOUCH_MODE 1497 }) 1498 @Retention(RetentionPolicy.SOURCE) 1499 public @interface FocusableMode {} 1500 1501 /** 1502 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1503 * should add all focusable Views regardless if they are focusable in touch mode. 1504 */ 1505 public static final int FOCUSABLES_ALL = 0x00000000; 1506 1507 /** 1508 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1509 * should add only Views focusable in touch mode. 1510 */ 1511 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1512 1513 /** @hide */ 1514 @IntDef({ 1515 FOCUS_BACKWARD, 1516 FOCUS_FORWARD, 1517 FOCUS_LEFT, 1518 FOCUS_UP, 1519 FOCUS_RIGHT, 1520 FOCUS_DOWN 1521 }) 1522 @Retention(RetentionPolicy.SOURCE) 1523 public @interface FocusDirection {} 1524 1525 /** @hide */ 1526 @IntDef({ 1527 FOCUS_LEFT, 1528 FOCUS_UP, 1529 FOCUS_RIGHT, 1530 FOCUS_DOWN 1531 }) 1532 @Retention(RetentionPolicy.SOURCE) 1533 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1534 1535 /** 1536 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1537 * item. 1538 */ 1539 public static final int FOCUS_BACKWARD = 0x00000001; 1540 1541 /** 1542 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1543 * item. 1544 */ 1545 public static final int FOCUS_FORWARD = 0x00000002; 1546 1547 /** 1548 * Use with {@link #focusSearch(int)}. Move focus to the left. 1549 */ 1550 public static final int FOCUS_LEFT = 0x00000011; 1551 1552 /** 1553 * Use with {@link #focusSearch(int)}. Move focus up. 1554 */ 1555 public static final int FOCUS_UP = 0x00000021; 1556 1557 /** 1558 * Use with {@link #focusSearch(int)}. Move focus to the right. 1559 */ 1560 public static final int FOCUS_RIGHT = 0x00000042; 1561 1562 /** 1563 * Use with {@link #focusSearch(int)}. Move focus down. 1564 */ 1565 public static final int FOCUS_DOWN = 0x00000082; 1566 1567 /** 1568 * Bits of {@link #getMeasuredWidthAndState()} and 1569 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1570 */ 1571 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1572 1573 /** 1574 * Bits of {@link #getMeasuredWidthAndState()} and 1575 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1576 */ 1577 public static final int MEASURED_STATE_MASK = 0xff000000; 1578 1579 /** 1580 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1581 * for functions that combine both width and height into a single int, 1582 * such as {@link #getMeasuredState()} and the childState argument of 1583 * {@link #resolveSizeAndState(int, int, int)}. 1584 */ 1585 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1586 1587 /** 1588 * Bit of {@link #getMeasuredWidthAndState()} and 1589 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1590 * is smaller that the space the view would like to have. 1591 */ 1592 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1593 1594 /** 1595 * Base View state sets 1596 */ 1597 // Singles 1598 /** 1599 * Indicates the view has no states set. States are used with 1600 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1601 * view depending on its state. 1602 * 1603 * @see android.graphics.drawable.Drawable 1604 * @see #getDrawableState() 1605 */ 1606 protected static final int[] EMPTY_STATE_SET; 1607 /** 1608 * Indicates the view is enabled. States are used with 1609 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1610 * view depending on its state. 1611 * 1612 * @see android.graphics.drawable.Drawable 1613 * @see #getDrawableState() 1614 */ 1615 protected static final int[] ENABLED_STATE_SET; 1616 /** 1617 * Indicates the view is focused. States are used with 1618 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1619 * view depending on its state. 1620 * 1621 * @see android.graphics.drawable.Drawable 1622 * @see #getDrawableState() 1623 */ 1624 protected static final int[] FOCUSED_STATE_SET; 1625 /** 1626 * Indicates the view is selected. States are used with 1627 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1628 * view depending on its state. 1629 * 1630 * @see android.graphics.drawable.Drawable 1631 * @see #getDrawableState() 1632 */ 1633 protected static final int[] SELECTED_STATE_SET; 1634 /** 1635 * Indicates the view is pressed. States are used with 1636 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1637 * view depending on its state. 1638 * 1639 * @see android.graphics.drawable.Drawable 1640 * @see #getDrawableState() 1641 */ 1642 protected static final int[] PRESSED_STATE_SET; 1643 /** 1644 * Indicates the view's window has focus. States are used with 1645 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1646 * view depending on its state. 1647 * 1648 * @see android.graphics.drawable.Drawable 1649 * @see #getDrawableState() 1650 */ 1651 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1652 // Doubles 1653 /** 1654 * Indicates the view is enabled and has the focus. 1655 * 1656 * @see #ENABLED_STATE_SET 1657 * @see #FOCUSED_STATE_SET 1658 */ 1659 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1660 /** 1661 * Indicates the view is enabled and selected. 1662 * 1663 * @see #ENABLED_STATE_SET 1664 * @see #SELECTED_STATE_SET 1665 */ 1666 protected static final int[] ENABLED_SELECTED_STATE_SET; 1667 /** 1668 * Indicates the view is enabled and that its window has focus. 1669 * 1670 * @see #ENABLED_STATE_SET 1671 * @see #WINDOW_FOCUSED_STATE_SET 1672 */ 1673 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1674 /** 1675 * Indicates the view is focused and selected. 1676 * 1677 * @see #FOCUSED_STATE_SET 1678 * @see #SELECTED_STATE_SET 1679 */ 1680 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1681 /** 1682 * Indicates the view has the focus and that its window has the focus. 1683 * 1684 * @see #FOCUSED_STATE_SET 1685 * @see #WINDOW_FOCUSED_STATE_SET 1686 */ 1687 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1688 /** 1689 * Indicates the view is selected and that its window has the focus. 1690 * 1691 * @see #SELECTED_STATE_SET 1692 * @see #WINDOW_FOCUSED_STATE_SET 1693 */ 1694 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1695 // Triples 1696 /** 1697 * Indicates the view is enabled, focused and selected. 1698 * 1699 * @see #ENABLED_STATE_SET 1700 * @see #FOCUSED_STATE_SET 1701 * @see #SELECTED_STATE_SET 1702 */ 1703 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1704 /** 1705 * Indicates the view is enabled, focused and its window has the focus. 1706 * 1707 * @see #ENABLED_STATE_SET 1708 * @see #FOCUSED_STATE_SET 1709 * @see #WINDOW_FOCUSED_STATE_SET 1710 */ 1711 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1712 /** 1713 * Indicates the view is enabled, selected and its window has the focus. 1714 * 1715 * @see #ENABLED_STATE_SET 1716 * @see #SELECTED_STATE_SET 1717 * @see #WINDOW_FOCUSED_STATE_SET 1718 */ 1719 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1720 /** 1721 * Indicates the view is focused, selected and its window has the focus. 1722 * 1723 * @see #FOCUSED_STATE_SET 1724 * @see #SELECTED_STATE_SET 1725 * @see #WINDOW_FOCUSED_STATE_SET 1726 */ 1727 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1728 /** 1729 * Indicates the view is enabled, focused, selected and its window 1730 * has the focus. 1731 * 1732 * @see #ENABLED_STATE_SET 1733 * @see #FOCUSED_STATE_SET 1734 * @see #SELECTED_STATE_SET 1735 * @see #WINDOW_FOCUSED_STATE_SET 1736 */ 1737 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1738 /** 1739 * Indicates the view is pressed and its window has the focus. 1740 * 1741 * @see #PRESSED_STATE_SET 1742 * @see #WINDOW_FOCUSED_STATE_SET 1743 */ 1744 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1745 /** 1746 * Indicates the view is pressed and selected. 1747 * 1748 * @see #PRESSED_STATE_SET 1749 * @see #SELECTED_STATE_SET 1750 */ 1751 protected static final int[] PRESSED_SELECTED_STATE_SET; 1752 /** 1753 * Indicates the view is pressed, selected and its window has the focus. 1754 * 1755 * @see #PRESSED_STATE_SET 1756 * @see #SELECTED_STATE_SET 1757 * @see #WINDOW_FOCUSED_STATE_SET 1758 */ 1759 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1760 /** 1761 * Indicates the view is pressed and focused. 1762 * 1763 * @see #PRESSED_STATE_SET 1764 * @see #FOCUSED_STATE_SET 1765 */ 1766 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1767 /** 1768 * Indicates the view is pressed, focused and its window has the focus. 1769 * 1770 * @see #PRESSED_STATE_SET 1771 * @see #FOCUSED_STATE_SET 1772 * @see #WINDOW_FOCUSED_STATE_SET 1773 */ 1774 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1775 /** 1776 * Indicates the view is pressed, focused and selected. 1777 * 1778 * @see #PRESSED_STATE_SET 1779 * @see #SELECTED_STATE_SET 1780 * @see #FOCUSED_STATE_SET 1781 */ 1782 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1783 /** 1784 * Indicates the view is pressed, focused, selected and its window has the focus. 1785 * 1786 * @see #PRESSED_STATE_SET 1787 * @see #FOCUSED_STATE_SET 1788 * @see #SELECTED_STATE_SET 1789 * @see #WINDOW_FOCUSED_STATE_SET 1790 */ 1791 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1792 /** 1793 * Indicates the view is pressed and enabled. 1794 * 1795 * @see #PRESSED_STATE_SET 1796 * @see #ENABLED_STATE_SET 1797 */ 1798 protected static final int[] PRESSED_ENABLED_STATE_SET; 1799 /** 1800 * Indicates the view is pressed, enabled and its window has the focus. 1801 * 1802 * @see #PRESSED_STATE_SET 1803 * @see #ENABLED_STATE_SET 1804 * @see #WINDOW_FOCUSED_STATE_SET 1805 */ 1806 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1807 /** 1808 * Indicates the view is pressed, enabled and selected. 1809 * 1810 * @see #PRESSED_STATE_SET 1811 * @see #ENABLED_STATE_SET 1812 * @see #SELECTED_STATE_SET 1813 */ 1814 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1815 /** 1816 * Indicates the view is pressed, enabled, selected and its window has the 1817 * focus. 1818 * 1819 * @see #PRESSED_STATE_SET 1820 * @see #ENABLED_STATE_SET 1821 * @see #SELECTED_STATE_SET 1822 * @see #WINDOW_FOCUSED_STATE_SET 1823 */ 1824 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1825 /** 1826 * Indicates the view is pressed, enabled and focused. 1827 * 1828 * @see #PRESSED_STATE_SET 1829 * @see #ENABLED_STATE_SET 1830 * @see #FOCUSED_STATE_SET 1831 */ 1832 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1833 /** 1834 * Indicates the view is pressed, enabled, focused and its window has the 1835 * focus. 1836 * 1837 * @see #PRESSED_STATE_SET 1838 * @see #ENABLED_STATE_SET 1839 * @see #FOCUSED_STATE_SET 1840 * @see #WINDOW_FOCUSED_STATE_SET 1841 */ 1842 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1843 /** 1844 * Indicates the view is pressed, enabled, focused and selected. 1845 * 1846 * @see #PRESSED_STATE_SET 1847 * @see #ENABLED_STATE_SET 1848 * @see #SELECTED_STATE_SET 1849 * @see #FOCUSED_STATE_SET 1850 */ 1851 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1852 /** 1853 * Indicates the view is pressed, enabled, focused, selected and its window 1854 * has the focus. 1855 * 1856 * @see #PRESSED_STATE_SET 1857 * @see #ENABLED_STATE_SET 1858 * @see #SELECTED_STATE_SET 1859 * @see #FOCUSED_STATE_SET 1860 * @see #WINDOW_FOCUSED_STATE_SET 1861 */ 1862 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1863 1864 static { 1865 EMPTY_STATE_SET = StateSet.get(0); 1866 1867 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1868 1869 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1870 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1871 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1872 1873 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1874 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1875 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1876 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1877 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1878 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1879 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1880 | StateSet.VIEW_STATE_FOCUSED); 1881 1882 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1883 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1884 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1885 ENABLED_SELECTED_STATE_SET = StateSet.get( 1886 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1887 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1888 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1889 | StateSet.VIEW_STATE_ENABLED); 1890 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1891 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1892 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1893 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1894 | StateSet.VIEW_STATE_ENABLED); 1895 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1896 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1897 | StateSet.VIEW_STATE_ENABLED); 1898 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1899 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1900 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1901 1902 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1903 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1904 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1905 PRESSED_SELECTED_STATE_SET = StateSet.get( 1906 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1907 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1908 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1909 | StateSet.VIEW_STATE_PRESSED); 1910 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1911 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1912 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1913 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1914 | StateSet.VIEW_STATE_PRESSED); 1915 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1916 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1917 | StateSet.VIEW_STATE_PRESSED); 1918 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1919 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1920 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1921 PRESSED_ENABLED_STATE_SET = StateSet.get( 1922 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1923 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1924 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1925 | StateSet.VIEW_STATE_PRESSED); 1926 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1927 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1928 | StateSet.VIEW_STATE_PRESSED); 1929 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1930 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1931 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1932 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1933 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1934 | StateSet.VIEW_STATE_PRESSED); 1935 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1936 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1937 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1938 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1939 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1940 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1941 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1942 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1943 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1944 | StateSet.VIEW_STATE_PRESSED); 1945 } 1946 1947 /** 1948 * Accessibility event types that are dispatched for text population. 1949 */ 1950 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1951 AccessibilityEvent.TYPE_VIEW_CLICKED 1952 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1953 | AccessibilityEvent.TYPE_VIEW_SELECTED 1954 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1955 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1956 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1957 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1958 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1959 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1960 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1961 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1962 1963 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255); 1964 1965 static final int DEBUG_CORNERS_SIZE_DIP = 8; 1966 1967 /** 1968 * Temporary Rect currently for use in setBackground(). This will probably 1969 * be extended in the future to hold our own class with more than just 1970 * a Rect. :) 1971 */ 1972 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1973 1974 /** 1975 * Map used to store views' tags. 1976 */ 1977 private SparseArray<Object> mKeyedTags; 1978 1979 /** 1980 * The animation currently associated with this view. 1981 * @hide 1982 */ 1983 protected Animation mCurrentAnimation = null; 1984 1985 /** 1986 * Width as measured during measure pass. 1987 * {@hide} 1988 */ 1989 @ViewDebug.ExportedProperty(category = "measurement") 1990 int mMeasuredWidth; 1991 1992 /** 1993 * Height as measured during measure pass. 1994 * {@hide} 1995 */ 1996 @ViewDebug.ExportedProperty(category = "measurement") 1997 int mMeasuredHeight; 1998 1999 /** 2000 * Flag to indicate that this view was marked INVALIDATED, or had its display list 2001 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 2002 * its display list. This flag, used only when hw accelerated, allows us to clear the 2003 * flag while retaining this information until it's needed (at getDisplayList() time and 2004 * in drawChild(), when we decide to draw a view's children's display lists into our own). 2005 * 2006 * {@hide} 2007 */ 2008 boolean mRecreateDisplayList = false; 2009 2010 /** 2011 * The view's identifier. 2012 * {@hide} 2013 * 2014 * @see #setId(int) 2015 * @see #getId() 2016 */ 2017 @IdRes 2018 @ViewDebug.ExportedProperty(resolveId = true) 2019 int mID = NO_ID; 2020 2021 /** The ID of this view for accessibility and autofill purposes. 2022 * <ul> 2023 * <li>== {@link #NO_ID}: ID has not been assigned yet 2024 * <li>≤ {@link #LAST_APP_ACCESSIBILITY_ID}: View is not part of a activity. The ID is 2025 * unique in the process. This might change 2026 * over activity lifecycle events. 2027 * <li>> {@link #LAST_APP_ACCESSIBILITY_ID}: View is part of a activity. The ID is 2028 * unique in the activity. This stays the same 2029 * over activity lifecycle events. 2030 */ 2031 private int mAccessibilityViewId = NO_ID; 2032 2033 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 2034 2035 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 2036 2037 /** 2038 * The view's tag. 2039 * {@hide} 2040 * 2041 * @see #setTag(Object) 2042 * @see #getTag() 2043 */ 2044 protected Object mTag = null; 2045 2046 // for mPrivateFlags: 2047 /** {@hide} */ 2048 static final int PFLAG_WANTS_FOCUS = 0x00000001; 2049 /** {@hide} */ 2050 static final int PFLAG_FOCUSED = 0x00000002; 2051 /** {@hide} */ 2052 static final int PFLAG_SELECTED = 0x00000004; 2053 /** {@hide} */ 2054 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 2055 /** {@hide} */ 2056 static final int PFLAG_HAS_BOUNDS = 0x00000010; 2057 /** {@hide} */ 2058 static final int PFLAG_DRAWN = 0x00000020; 2059 /** 2060 * When this flag is set, this view is running an animation on behalf of its 2061 * children and should therefore not cancel invalidate requests, even if they 2062 * lie outside of this view's bounds. 2063 * 2064 * {@hide} 2065 */ 2066 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 2067 /** {@hide} */ 2068 static final int PFLAG_SKIP_DRAW = 0x00000080; 2069 /** {@hide} */ 2070 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 2071 /** {@hide} */ 2072 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 2073 /** {@hide} */ 2074 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 2075 /** {@hide} */ 2076 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 2077 /** {@hide} */ 2078 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 2079 2080 private static final int PFLAG_PRESSED = 0x00004000; 2081 2082 /** {@hide} */ 2083 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 2084 /** 2085 * Flag used to indicate that this view should be drawn once more (and only once 2086 * more) after its animation has completed. 2087 * {@hide} 2088 */ 2089 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 2090 2091 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 2092 2093 /** 2094 * Indicates that the View returned true when onSetAlpha() was called and that 2095 * the alpha must be restored. 2096 * {@hide} 2097 */ 2098 static final int PFLAG_ALPHA_SET = 0x00040000; 2099 2100 /** 2101 * Set by {@link #setScrollContainer(boolean)}. 2102 */ 2103 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 2104 2105 /** 2106 * Set by {@link #setScrollContainer(boolean)}. 2107 */ 2108 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 2109 2110 /** 2111 * View flag indicating whether this view was invalidated (fully or partially.) 2112 * 2113 * @hide 2114 */ 2115 static final int PFLAG_DIRTY = 0x00200000; 2116 2117 /** 2118 * View flag indicating whether this view was invalidated by an opaque 2119 * invalidate request. 2120 * 2121 * @hide 2122 */ 2123 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 2124 2125 /** 2126 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 2127 * 2128 * @hide 2129 */ 2130 static final int PFLAG_DIRTY_MASK = 0x00600000; 2131 2132 /** 2133 * Indicates whether the background is opaque. 2134 * 2135 * @hide 2136 */ 2137 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 2138 2139 /** 2140 * Indicates whether the scrollbars are opaque. 2141 * 2142 * @hide 2143 */ 2144 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 2145 2146 /** 2147 * Indicates whether the view is opaque. 2148 * 2149 * @hide 2150 */ 2151 static final int PFLAG_OPAQUE_MASK = 0x01800000; 2152 2153 /** 2154 * Indicates a prepressed state; 2155 * the short time between ACTION_DOWN and recognizing 2156 * a 'real' press. Prepressed is used to recognize quick taps 2157 * even when they are shorter than ViewConfiguration.getTapTimeout(). 2158 * 2159 * @hide 2160 */ 2161 private static final int PFLAG_PREPRESSED = 0x02000000; 2162 2163 /** 2164 * Indicates whether the view is temporarily detached. 2165 * 2166 * @hide 2167 */ 2168 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 2169 2170 /** 2171 * Indicates that we should awaken scroll bars once attached 2172 * 2173 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 2174 * during window attachment and it is no longer needed. Feel free to repurpose it. 2175 * 2176 * @hide 2177 */ 2178 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 2179 2180 /** 2181 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 2182 * @hide 2183 */ 2184 private static final int PFLAG_HOVERED = 0x10000000; 2185 2186 /** 2187 * no longer needed, should be reused 2188 */ 2189 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 2190 2191 /** {@hide} */ 2192 static final int PFLAG_ACTIVATED = 0x40000000; 2193 2194 /** 2195 * Indicates that this view was specifically invalidated, not just dirtied because some 2196 * child view was invalidated. The flag is used to determine when we need to recreate 2197 * a view's display list (as opposed to just returning a reference to its existing 2198 * display list). 2199 * 2200 * @hide 2201 */ 2202 static final int PFLAG_INVALIDATED = 0x80000000; 2203 2204 /** 2205 * Masks for mPrivateFlags2, as generated by dumpFlags(): 2206 * 2207 * |-------|-------|-------|-------| 2208 * 1 PFLAG2_DRAG_CAN_ACCEPT 2209 * 1 PFLAG2_DRAG_HOVERED 2210 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 2211 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 2212 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 2213 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 2214 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 2215 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 2216 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 2217 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 2218 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 2219 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 2220 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 2221 * 111 PFLAG2_TEXT_DIRECTION_MASK 2222 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 2223 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 2224 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 2225 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 2226 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 2227 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 2228 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 2229 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 2230 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 2231 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 2232 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 2233 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 2234 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 2235 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 2236 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 2237 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 2238 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 2239 * 1 PFLAG2_VIEW_QUICK_REJECTED 2240 * 1 PFLAG2_PADDING_RESOLVED 2241 * 1 PFLAG2_DRAWABLE_RESOLVED 2242 * 1 PFLAG2_HAS_TRANSIENT_STATE 2243 * |-------|-------|-------|-------| 2244 */ 2245 2246 /** 2247 * Indicates that this view has reported that it can accept the current drag's content. 2248 * Cleared when the drag operation concludes. 2249 * @hide 2250 */ 2251 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 2252 2253 /** 2254 * Indicates that this view is currently directly under the drag location in a 2255 * drag-and-drop operation involving content that it can accept. Cleared when 2256 * the drag exits the view, or when the drag operation concludes. 2257 * @hide 2258 */ 2259 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 2260 2261 /** @hide */ 2262 @IntDef({ 2263 LAYOUT_DIRECTION_LTR, 2264 LAYOUT_DIRECTION_RTL, 2265 LAYOUT_DIRECTION_INHERIT, 2266 LAYOUT_DIRECTION_LOCALE 2267 }) 2268 @Retention(RetentionPolicy.SOURCE) 2269 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 2270 public @interface LayoutDir {} 2271 2272 /** @hide */ 2273 @IntDef({ 2274 LAYOUT_DIRECTION_LTR, 2275 LAYOUT_DIRECTION_RTL 2276 }) 2277 @Retention(RetentionPolicy.SOURCE) 2278 public @interface ResolvedLayoutDir {} 2279 2280 /** 2281 * A flag to indicate that the layout direction of this view has not been defined yet. 2282 * @hide 2283 */ 2284 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 2285 2286 /** 2287 * Horizontal layout direction of this view is from Left to Right. 2288 * Use with {@link #setLayoutDirection}. 2289 */ 2290 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 2291 2292 /** 2293 * Horizontal layout direction of this view is from Right to Left. 2294 * Use with {@link #setLayoutDirection}. 2295 */ 2296 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 2297 2298 /** 2299 * Horizontal layout direction of this view is inherited from its parent. 2300 * Use with {@link #setLayoutDirection}. 2301 */ 2302 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 2303 2304 /** 2305 * Horizontal layout direction of this view is from deduced from the default language 2306 * script for the locale. Use with {@link #setLayoutDirection}. 2307 */ 2308 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 2309 2310 /** 2311 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2312 * @hide 2313 */ 2314 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2315 2316 /** 2317 * Mask for use with private flags indicating bits used for horizontal layout direction. 2318 * @hide 2319 */ 2320 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2321 2322 /** 2323 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2324 * right-to-left direction. 2325 * @hide 2326 */ 2327 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2328 2329 /** 2330 * Indicates whether the view horizontal layout direction has been resolved. 2331 * @hide 2332 */ 2333 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2334 2335 /** 2336 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2337 * @hide 2338 */ 2339 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2340 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2341 2342 /* 2343 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2344 * flag value. 2345 * @hide 2346 */ 2347 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2348 LAYOUT_DIRECTION_LTR, 2349 LAYOUT_DIRECTION_RTL, 2350 LAYOUT_DIRECTION_INHERIT, 2351 LAYOUT_DIRECTION_LOCALE 2352 }; 2353 2354 /** 2355 * Default horizontal layout direction. 2356 */ 2357 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2358 2359 /** 2360 * Default horizontal layout direction. 2361 * @hide 2362 */ 2363 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2364 2365 /** 2366 * Text direction is inherited through {@link ViewGroup} 2367 */ 2368 public static final int TEXT_DIRECTION_INHERIT = 0; 2369 2370 /** 2371 * Text direction is using "first strong algorithm". The first strong directional character 2372 * determines the paragraph direction. If there is no strong directional character, the 2373 * paragraph direction is the view's resolved layout direction. 2374 */ 2375 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2376 2377 /** 2378 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2379 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2380 * If there are neither, the paragraph direction is the view's resolved layout direction. 2381 */ 2382 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2383 2384 /** 2385 * Text direction is forced to LTR. 2386 */ 2387 public static final int TEXT_DIRECTION_LTR = 3; 2388 2389 /** 2390 * Text direction is forced to RTL. 2391 */ 2392 public static final int TEXT_DIRECTION_RTL = 4; 2393 2394 /** 2395 * Text direction is coming from the system Locale. 2396 */ 2397 public static final int TEXT_DIRECTION_LOCALE = 5; 2398 2399 /** 2400 * Text direction is using "first strong algorithm". The first strong directional character 2401 * determines the paragraph direction. If there is no strong directional character, the 2402 * paragraph direction is LTR. 2403 */ 2404 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2405 2406 /** 2407 * Text direction is using "first strong algorithm". The first strong directional character 2408 * determines the paragraph direction. If there is no strong directional character, the 2409 * paragraph direction is RTL. 2410 */ 2411 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2412 2413 /** 2414 * Default text direction is inherited 2415 */ 2416 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2417 2418 /** 2419 * Default resolved text direction 2420 * @hide 2421 */ 2422 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2423 2424 /** 2425 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2426 * @hide 2427 */ 2428 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2429 2430 /** 2431 * Mask for use with private flags indicating bits used for text direction. 2432 * @hide 2433 */ 2434 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2435 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2436 2437 /** 2438 * Array of text direction flags for mapping attribute "textDirection" to correct 2439 * flag value. 2440 * @hide 2441 */ 2442 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2443 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2444 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2445 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2446 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2447 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2448 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2449 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2450 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2451 }; 2452 2453 /** 2454 * Indicates whether the view text direction has been resolved. 2455 * @hide 2456 */ 2457 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2458 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2459 2460 /** 2461 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2462 * @hide 2463 */ 2464 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2465 2466 /** 2467 * Mask for use with private flags indicating bits used for resolved text direction. 2468 * @hide 2469 */ 2470 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2471 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2472 2473 /** 2474 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2475 * @hide 2476 */ 2477 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2478 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2479 2480 /** @hide */ 2481 @IntDef({ 2482 TEXT_ALIGNMENT_INHERIT, 2483 TEXT_ALIGNMENT_GRAVITY, 2484 TEXT_ALIGNMENT_CENTER, 2485 TEXT_ALIGNMENT_TEXT_START, 2486 TEXT_ALIGNMENT_TEXT_END, 2487 TEXT_ALIGNMENT_VIEW_START, 2488 TEXT_ALIGNMENT_VIEW_END 2489 }) 2490 @Retention(RetentionPolicy.SOURCE) 2491 public @interface TextAlignment {} 2492 2493 /** 2494 * Default text alignment. The text alignment of this View is inherited from its parent. 2495 * Use with {@link #setTextAlignment(int)} 2496 */ 2497 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2498 2499 /** 2500 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2501 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2502 * 2503 * Use with {@link #setTextAlignment(int)} 2504 */ 2505 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2506 2507 /** 2508 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2509 * 2510 * Use with {@link #setTextAlignment(int)} 2511 */ 2512 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2513 2514 /** 2515 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2516 * 2517 * Use with {@link #setTextAlignment(int)} 2518 */ 2519 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2520 2521 /** 2522 * Center the paragraph, e.g. ALIGN_CENTER. 2523 * 2524 * Use with {@link #setTextAlignment(int)} 2525 */ 2526 public static final int TEXT_ALIGNMENT_CENTER = 4; 2527 2528 /** 2529 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2530 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2531 * 2532 * Use with {@link #setTextAlignment(int)} 2533 */ 2534 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2535 2536 /** 2537 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2538 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2539 * 2540 * Use with {@link #setTextAlignment(int)} 2541 */ 2542 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2543 2544 /** 2545 * Default text alignment is inherited 2546 */ 2547 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2548 2549 /** 2550 * Default resolved text alignment 2551 * @hide 2552 */ 2553 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2554 2555 /** 2556 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2557 * @hide 2558 */ 2559 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2560 2561 /** 2562 * Mask for use with private flags indicating bits used for text alignment. 2563 * @hide 2564 */ 2565 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2566 2567 /** 2568 * Array of text direction flags for mapping attribute "textAlignment" to correct 2569 * flag value. 2570 * @hide 2571 */ 2572 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2573 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2574 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2575 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2576 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2577 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2578 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2579 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2580 }; 2581 2582 /** 2583 * Indicates whether the view text alignment has been resolved. 2584 * @hide 2585 */ 2586 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2587 2588 /** 2589 * Bit shift to get the resolved text alignment. 2590 * @hide 2591 */ 2592 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2593 2594 /** 2595 * Mask for use with private flags indicating bits used for text alignment. 2596 * @hide 2597 */ 2598 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2599 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2600 2601 /** 2602 * Indicates whether if the view text alignment has been resolved to gravity 2603 */ 2604 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2605 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2606 2607 // Accessiblity constants for mPrivateFlags2 2608 2609 /** 2610 * Shift for the bits in {@link #mPrivateFlags2} related to the 2611 * "importantForAccessibility" attribute. 2612 */ 2613 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2614 2615 /** 2616 * Automatically determine whether a view is important for accessibility. 2617 */ 2618 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2619 2620 /** 2621 * The view is important for accessibility. 2622 */ 2623 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2624 2625 /** 2626 * The view is not important for accessibility. 2627 */ 2628 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2629 2630 /** 2631 * The view is not important for accessibility, nor are any of its 2632 * descendant views. 2633 */ 2634 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2635 2636 /** 2637 * The default whether the view is important for accessibility. 2638 */ 2639 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2640 2641 /** 2642 * Mask for obtaining the bits which specify how to determine 2643 * whether a view is important for accessibility. 2644 */ 2645 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2646 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2647 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2648 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2649 2650 /** 2651 * Shift for the bits in {@link #mPrivateFlags2} related to the 2652 * "accessibilityLiveRegion" attribute. 2653 */ 2654 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2655 2656 /** 2657 * Live region mode specifying that accessibility services should not 2658 * automatically announce changes to this view. This is the default live 2659 * region mode for most views. 2660 * <p> 2661 * Use with {@link #setAccessibilityLiveRegion(int)}. 2662 */ 2663 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2664 2665 /** 2666 * Live region mode specifying that accessibility services should announce 2667 * changes to this view. 2668 * <p> 2669 * Use with {@link #setAccessibilityLiveRegion(int)}. 2670 */ 2671 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2672 2673 /** 2674 * Live region mode specifying that accessibility services should interrupt 2675 * ongoing speech to immediately announce changes to this view. 2676 * <p> 2677 * Use with {@link #setAccessibilityLiveRegion(int)}. 2678 */ 2679 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2680 2681 /** 2682 * The default whether the view is important for accessibility. 2683 */ 2684 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2685 2686 /** 2687 * Mask for obtaining the bits which specify a view's accessibility live 2688 * region mode. 2689 */ 2690 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2691 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2692 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2693 2694 /** 2695 * Flag indicating whether a view has accessibility focus. 2696 */ 2697 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2698 2699 /** 2700 * Flag whether the accessibility state of the subtree rooted at this view changed. 2701 */ 2702 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2703 2704 /** 2705 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2706 * is used to check whether later changes to the view's transform should invalidate the 2707 * view to force the quickReject test to run again. 2708 */ 2709 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2710 2711 /** 2712 * Flag indicating that start/end padding has been resolved into left/right padding 2713 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2714 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2715 * during measurement. In some special cases this is required such as when an adapter-based 2716 * view measures prospective children without attaching them to a window. 2717 */ 2718 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2719 2720 /** 2721 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2722 */ 2723 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2724 2725 /** 2726 * Indicates that the view is tracking some sort of transient state 2727 * that the app should not need to be aware of, but that the framework 2728 * should take special care to preserve. 2729 */ 2730 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2731 2732 /** 2733 * Group of bits indicating that RTL properties resolution is done. 2734 */ 2735 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2736 PFLAG2_TEXT_DIRECTION_RESOLVED | 2737 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2738 PFLAG2_PADDING_RESOLVED | 2739 PFLAG2_DRAWABLE_RESOLVED; 2740 2741 // There are a couple of flags left in mPrivateFlags2 2742 2743 /* End of masks for mPrivateFlags2 */ 2744 2745 /** 2746 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2747 * 2748 * |-------|-------|-------|-------| 2749 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2750 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2751 * 1 PFLAG3_IS_LAID_OUT 2752 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2753 * 1 PFLAG3_CALLED_SUPER 2754 * 1 PFLAG3_APPLYING_INSETS 2755 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2756 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2757 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2758 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2759 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2760 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2761 * 1 PFLAG3_SCROLL_INDICATOR_START 2762 * 1 PFLAG3_SCROLL_INDICATOR_END 2763 * 1 PFLAG3_ASSIST_BLOCKED 2764 * 1 PFLAG3_CLUSTER 2765 * 1 PFLAG3_IS_AUTOFILLED 2766 * 1 PFLAG3_FINGER_DOWN 2767 * 1 PFLAG3_FOCUSED_BY_DEFAULT 2768 * 1111 PFLAG3_IMPORTANT_FOR_AUTOFILL 2769 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2770 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2771 * 1 PFLAG3_TEMPORARY_DETACH 2772 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2773 * |-------|-------|-------|-------| 2774 */ 2775 2776 /** 2777 * Flag indicating that view has a transform animation set on it. This is used to track whether 2778 * an animation is cleared between successive frames, in order to tell the associated 2779 * DisplayList to clear its animation matrix. 2780 */ 2781 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2782 2783 /** 2784 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2785 * animation is cleared between successive frames, in order to tell the associated 2786 * DisplayList to restore its alpha value. 2787 */ 2788 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2789 2790 /** 2791 * Flag indicating that the view has been through at least one layout since it 2792 * was last attached to a window. 2793 */ 2794 static final int PFLAG3_IS_LAID_OUT = 0x4; 2795 2796 /** 2797 * Flag indicating that a call to measure() was skipped and should be done 2798 * instead when layout() is invoked. 2799 */ 2800 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2801 2802 /** 2803 * Flag indicating that an overridden method correctly called down to 2804 * the superclass implementation as required by the API spec. 2805 */ 2806 static final int PFLAG3_CALLED_SUPER = 0x10; 2807 2808 /** 2809 * Flag indicating that we're in the process of applying window insets. 2810 */ 2811 static final int PFLAG3_APPLYING_INSETS = 0x20; 2812 2813 /** 2814 * Flag indicating that we're in the process of fitting system windows using the old method. 2815 */ 2816 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2817 2818 /** 2819 * Flag indicating that nested scrolling is enabled for this view. 2820 * The view will optionally cooperate with views up its parent chain to allow for 2821 * integrated nested scrolling along the same axis. 2822 */ 2823 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2824 2825 /** 2826 * Flag indicating that the bottom scroll indicator should be displayed 2827 * when this view can scroll up. 2828 */ 2829 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2830 2831 /** 2832 * Flag indicating that the bottom scroll indicator should be displayed 2833 * when this view can scroll down. 2834 */ 2835 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2836 2837 /** 2838 * Flag indicating that the left scroll indicator should be displayed 2839 * when this view can scroll left. 2840 */ 2841 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2842 2843 /** 2844 * Flag indicating that the right scroll indicator should be displayed 2845 * when this view can scroll right. 2846 */ 2847 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2848 2849 /** 2850 * Flag indicating that the start scroll indicator should be displayed 2851 * when this view can scroll in the start direction. 2852 */ 2853 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2854 2855 /** 2856 * Flag indicating that the end scroll indicator should be displayed 2857 * when this view can scroll in the end direction. 2858 */ 2859 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2860 2861 /** 2862 * Flag indicating that when layout is completed we should notify 2863 * that the view was entered for autofill purposes. To minimize 2864 * showing autofill for views not visible to the user we evaluate 2865 * user visibility which cannot be done until the view is laid out. 2866 */ 2867 static final int PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT = 0x4000; 2868 2869 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2870 2871 static final int SCROLL_INDICATORS_NONE = 0x0000; 2872 2873 /** 2874 * Mask for use with setFlags indicating bits used for indicating which 2875 * scroll indicators are enabled. 2876 */ 2877 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2878 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2879 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2880 | PFLAG3_SCROLL_INDICATOR_END; 2881 2882 /** 2883 * Left-shift required to translate between public scroll indicator flags 2884 * and internal PFLAGS3 flags. When used as a right-shift, translates 2885 * PFLAGS3 flags to public flags. 2886 */ 2887 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2888 2889 /** @hide */ 2890 @Retention(RetentionPolicy.SOURCE) 2891 @IntDef(flag = true, 2892 value = { 2893 SCROLL_INDICATOR_TOP, 2894 SCROLL_INDICATOR_BOTTOM, 2895 SCROLL_INDICATOR_LEFT, 2896 SCROLL_INDICATOR_RIGHT, 2897 SCROLL_INDICATOR_START, 2898 SCROLL_INDICATOR_END, 2899 }) 2900 public @interface ScrollIndicators {} 2901 2902 /** 2903 * Scroll indicator direction for the top edge of the view. 2904 * 2905 * @see #setScrollIndicators(int) 2906 * @see #setScrollIndicators(int, int) 2907 * @see #getScrollIndicators() 2908 */ 2909 public static final int SCROLL_INDICATOR_TOP = 2910 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2911 2912 /** 2913 * Scroll indicator direction for the bottom edge of the view. 2914 * 2915 * @see #setScrollIndicators(int) 2916 * @see #setScrollIndicators(int, int) 2917 * @see #getScrollIndicators() 2918 */ 2919 public static final int SCROLL_INDICATOR_BOTTOM = 2920 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2921 2922 /** 2923 * Scroll indicator direction for the left edge of the view. 2924 * 2925 * @see #setScrollIndicators(int) 2926 * @see #setScrollIndicators(int, int) 2927 * @see #getScrollIndicators() 2928 */ 2929 public static final int SCROLL_INDICATOR_LEFT = 2930 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2931 2932 /** 2933 * Scroll indicator direction for the right edge of the view. 2934 * 2935 * @see #setScrollIndicators(int) 2936 * @see #setScrollIndicators(int, int) 2937 * @see #getScrollIndicators() 2938 */ 2939 public static final int SCROLL_INDICATOR_RIGHT = 2940 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2941 2942 /** 2943 * Scroll indicator direction for the starting edge of the view. 2944 * <p> 2945 * Resolved according to the view's layout direction, see 2946 * {@link #getLayoutDirection()} for more information. 2947 * 2948 * @see #setScrollIndicators(int) 2949 * @see #setScrollIndicators(int, int) 2950 * @see #getScrollIndicators() 2951 */ 2952 public static final int SCROLL_INDICATOR_START = 2953 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2954 2955 /** 2956 * Scroll indicator direction for the ending edge of the view. 2957 * <p> 2958 * Resolved according to the view's layout direction, see 2959 * {@link #getLayoutDirection()} for more information. 2960 * 2961 * @see #setScrollIndicators(int) 2962 * @see #setScrollIndicators(int, int) 2963 * @see #getScrollIndicators() 2964 */ 2965 public static final int SCROLL_INDICATOR_END = 2966 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2967 2968 /** 2969 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2970 * into this view.<p> 2971 */ 2972 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2973 2974 /** 2975 * Flag indicating that the view is a root of a keyboard navigation cluster. 2976 * 2977 * @see #isKeyboardNavigationCluster() 2978 * @see #setKeyboardNavigationCluster(boolean) 2979 */ 2980 private static final int PFLAG3_CLUSTER = 0x8000; 2981 2982 /** 2983 * Flag indicating that the view is autofilled 2984 * 2985 * @see #isAutofilled() 2986 * @see #setAutofilled(boolean) 2987 */ 2988 private static final int PFLAG3_IS_AUTOFILLED = 0x10000; 2989 2990 /** 2991 * Indicates that the user is currently touching the screen. 2992 * Currently used for the tooltip positioning only. 2993 */ 2994 private static final int PFLAG3_FINGER_DOWN = 0x20000; 2995 2996 /** 2997 * Flag indicating that this view is the default-focus view. 2998 * 2999 * @see #isFocusedByDefault() 3000 * @see #setFocusedByDefault(boolean) 3001 */ 3002 private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000; 3003 3004 /** 3005 * Shift for the bits in {@link #mPrivateFlags3} related to the 3006 * "importantForAutofill" attribute. 3007 */ 3008 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 19; 3009 3010 /** 3011 * Mask for obtaining the bits which specify how to determine 3012 * whether a view is important for autofill. 3013 */ 3014 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO 3015 | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO 3016 | IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 3017 | IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS) 3018 << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 3019 3020 /** 3021 * Whether this view has rendered elements that overlap (see {@link 3022 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 3023 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 3024 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 3025 * determined by whatever {@link #hasOverlappingRendering()} returns. 3026 */ 3027 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 3028 3029 /** 3030 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 3031 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 3032 */ 3033 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 3034 3035 /** 3036 * Flag indicating that the view is temporarily detached from the parent view. 3037 * 3038 * @see #onStartTemporaryDetach() 3039 * @see #onFinishTemporaryDetach() 3040 */ 3041 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 3042 3043 /** 3044 * Flag indicating that the view does not wish to be revealed within its parent 3045 * hierarchy when it gains focus. Expressed in the negative since the historical 3046 * default behavior is to reveal on focus; this flag suppresses that behavior. 3047 * 3048 * @see #setRevealOnFocusHint(boolean) 3049 * @see #getRevealOnFocusHint() 3050 */ 3051 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 3052 3053 /* End of masks for mPrivateFlags3 */ 3054 3055 /** 3056 * Always allow a user to over-scroll this view, provided it is a 3057 * view that can scroll. 3058 * 3059 * @see #getOverScrollMode() 3060 * @see #setOverScrollMode(int) 3061 */ 3062 public static final int OVER_SCROLL_ALWAYS = 0; 3063 3064 /** 3065 * Allow a user to over-scroll this view only if the content is large 3066 * enough to meaningfully scroll, provided it is a view that can scroll. 3067 * 3068 * @see #getOverScrollMode() 3069 * @see #setOverScrollMode(int) 3070 */ 3071 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 3072 3073 /** 3074 * Never allow a user to over-scroll this view. 3075 * 3076 * @see #getOverScrollMode() 3077 * @see #setOverScrollMode(int) 3078 */ 3079 public static final int OVER_SCROLL_NEVER = 2; 3080 3081 /** 3082 * Special constant for {@link #setSystemUiVisibility(int)}: View has 3083 * requested the system UI (status bar) to be visible (the default). 3084 * 3085 * @see #setSystemUiVisibility(int) 3086 */ 3087 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 3088 3089 /** 3090 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 3091 * system UI to enter an unobtrusive "low profile" mode. 3092 * 3093 * <p>This is for use in games, book readers, video players, or any other 3094 * "immersive" application where the usual system chrome is deemed too distracting. 3095 * 3096 * <p>In low profile mode, the status bar and/or navigation icons may dim. 3097 * 3098 * @see #setSystemUiVisibility(int) 3099 */ 3100 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 3101 3102 /** 3103 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 3104 * system navigation be temporarily hidden. 3105 * 3106 * <p>This is an even less obtrusive state than that called for by 3107 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 3108 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 3109 * those to disappear. This is useful (in conjunction with the 3110 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 3111 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 3112 * window flags) for displaying content using every last pixel on the display. 3113 * 3114 * <p>There is a limitation: because navigation controls are so important, the least user 3115 * interaction will cause them to reappear immediately. When this happens, both 3116 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 3117 * so that both elements reappear at the same time. 3118 * 3119 * @see #setSystemUiVisibility(int) 3120 */ 3121 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 3122 3123 /** 3124 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 3125 * into the normal fullscreen mode so that its content can take over the screen 3126 * while still allowing the user to interact with the application. 3127 * 3128 * <p>This has the same visual effect as 3129 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 3130 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 3131 * meaning that non-critical screen decorations (such as the status bar) will be 3132 * hidden while the user is in the View's window, focusing the experience on 3133 * that content. Unlike the window flag, if you are using ActionBar in 3134 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3135 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 3136 * hide the action bar. 3137 * 3138 * <p>This approach to going fullscreen is best used over the window flag when 3139 * it is a transient state -- that is, the application does this at certain 3140 * points in its user interaction where it wants to allow the user to focus 3141 * on content, but not as a continuous state. For situations where the application 3142 * would like to simply stay full screen the entire time (such as a game that 3143 * wants to take over the screen), the 3144 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 3145 * is usually a better approach. The state set here will be removed by the system 3146 * in various situations (such as the user moving to another application) like 3147 * the other system UI states. 3148 * 3149 * <p>When using this flag, the application should provide some easy facility 3150 * for the user to go out of it. A common example would be in an e-book 3151 * reader, where tapping on the screen brings back whatever screen and UI 3152 * decorations that had been hidden while the user was immersed in reading 3153 * the book. 3154 * 3155 * @see #setSystemUiVisibility(int) 3156 */ 3157 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 3158 3159 /** 3160 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 3161 * flags, we would like a stable view of the content insets given to 3162 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 3163 * will always represent the worst case that the application can expect 3164 * as a continuous state. In the stock Android UI this is the space for 3165 * the system bar, nav bar, and status bar, but not more transient elements 3166 * such as an input method. 3167 * 3168 * The stable layout your UI sees is based on the system UI modes you can 3169 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 3170 * then you will get a stable layout for changes of the 3171 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 3172 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 3173 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 3174 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 3175 * with a stable layout. (Note that you should avoid using 3176 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 3177 * 3178 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 3179 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 3180 * then a hidden status bar will be considered a "stable" state for purposes 3181 * here. This allows your UI to continually hide the status bar, while still 3182 * using the system UI flags to hide the action bar while still retaining 3183 * a stable layout. Note that changing the window fullscreen flag will never 3184 * provide a stable layout for a clean transition. 3185 * 3186 * <p>If you are using ActionBar in 3187 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3188 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 3189 * insets it adds to those given to the application. 3190 */ 3191 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 3192 3193 /** 3194 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3195 * to be laid out as if it has requested 3196 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 3197 * allows it to avoid artifacts when switching in and out of that mode, at 3198 * the expense that some of its user interface may be covered by screen 3199 * decorations when they are shown. You can perform layout of your inner 3200 * UI elements to account for the navigation system UI through the 3201 * {@link #fitSystemWindows(Rect)} method. 3202 */ 3203 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 3204 3205 /** 3206 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3207 * to be laid out as if it has requested 3208 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 3209 * allows it to avoid artifacts when switching in and out of that mode, at 3210 * the expense that some of its user interface may be covered by screen 3211 * decorations when they are shown. You can perform layout of your inner 3212 * UI elements to account for non-fullscreen system UI through the 3213 * {@link #fitSystemWindows(Rect)} method. 3214 */ 3215 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 3216 3217 /** 3218 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3219 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 3220 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 3221 * user interaction. 3222 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 3223 * has an effect when used in combination with that flag.</p> 3224 */ 3225 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 3226 3227 /** 3228 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3229 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 3230 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 3231 * experience while also hiding the system bars. If this flag is not set, 3232 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 3233 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 3234 * if the user swipes from the top of the screen. 3235 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 3236 * system gestures, such as swiping from the top of the screen. These transient system bars 3237 * will overlay app’s content, may have some degree of transparency, and will automatically 3238 * hide after a short timeout. 3239 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 3240 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 3241 * with one or both of those flags.</p> 3242 */ 3243 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 3244 3245 /** 3246 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 3247 * is compatible with light status bar backgrounds. 3248 * 3249 * <p>For this to take effect, the window must request 3250 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3251 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3252 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 3253 * FLAG_TRANSLUCENT_STATUS}. 3254 * 3255 * @see android.R.attr#windowLightStatusBar 3256 */ 3257 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 3258 3259 /** 3260 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3261 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3262 */ 3263 private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000; 3264 3265 /** 3266 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3267 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3268 */ 3269 private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000; 3270 3271 /** 3272 * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode 3273 * that is compatible with light navigation bar backgrounds. 3274 * 3275 * <p>For this to take effect, the window must request 3276 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3277 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3278 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION 3279 * FLAG_TRANSLUCENT_NAVIGATION}. 3280 */ 3281 public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010; 3282 3283 /** 3284 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 3285 */ 3286 @Deprecated 3287 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 3288 3289 /** 3290 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 3291 */ 3292 @Deprecated 3293 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 3294 3295 /** 3296 * @hide 3297 * 3298 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3299 * out of the public fields to keep the undefined bits out of the developer's way. 3300 * 3301 * Flag to make the status bar not expandable. Unless you also 3302 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 3303 */ 3304 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 3305 3306 /** 3307 * @hide 3308 * 3309 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3310 * out of the public fields to keep the undefined bits out of the developer's way. 3311 * 3312 * Flag to hide notification icons and scrolling ticker text. 3313 */ 3314 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 3315 3316 /** 3317 * @hide 3318 * 3319 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3320 * out of the public fields to keep the undefined bits out of the developer's way. 3321 * 3322 * Flag to disable incoming notification alerts. This will not block 3323 * icons, but it will block sound, vibrating and other visual or aural notifications. 3324 */ 3325 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 3326 3327 /** 3328 * @hide 3329 * 3330 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3331 * out of the public fields to keep the undefined bits out of the developer's way. 3332 * 3333 * Flag to hide only the scrolling ticker. Note that 3334 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 3335 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 3336 */ 3337 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 3338 3339 /** 3340 * @hide 3341 * 3342 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3343 * out of the public fields to keep the undefined bits out of the developer's way. 3344 * 3345 * Flag to hide the center system info area. 3346 */ 3347 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 3348 3349 /** 3350 * @hide 3351 * 3352 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3353 * out of the public fields to keep the undefined bits out of the developer's way. 3354 * 3355 * Flag to hide only the home button. Don't use this 3356 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3357 */ 3358 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 3359 3360 /** 3361 * @hide 3362 * 3363 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3364 * out of the public fields to keep the undefined bits out of the developer's way. 3365 * 3366 * Flag to hide only the back button. Don't use this 3367 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3368 */ 3369 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 3370 3371 /** 3372 * @hide 3373 * 3374 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3375 * out of the public fields to keep the undefined bits out of the developer's way. 3376 * 3377 * Flag to hide only the clock. You might use this if your activity has 3378 * its own clock making the status bar's clock redundant. 3379 */ 3380 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 3381 3382 /** 3383 * @hide 3384 * 3385 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3386 * out of the public fields to keep the undefined bits out of the developer's way. 3387 * 3388 * Flag to hide only the recent apps button. Don't use this 3389 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3390 */ 3391 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 3392 3393 /** 3394 * @hide 3395 * 3396 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3397 * out of the public fields to keep the undefined bits out of the developer's way. 3398 * 3399 * Flag to disable the global search gesture. Don't use this 3400 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3401 */ 3402 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3403 3404 /** 3405 * @hide 3406 * 3407 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3408 * out of the public fields to keep the undefined bits out of the developer's way. 3409 * 3410 * Flag to specify that the status bar is displayed in transient mode. 3411 */ 3412 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3413 3414 /** 3415 * @hide 3416 * 3417 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3418 * out of the public fields to keep the undefined bits out of the developer's way. 3419 * 3420 * Flag to specify that the navigation bar is displayed in transient mode. 3421 */ 3422 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3423 3424 /** 3425 * @hide 3426 * 3427 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3428 * out of the public fields to keep the undefined bits out of the developer's way. 3429 * 3430 * Flag to specify that the hidden status bar would like to be shown. 3431 */ 3432 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3433 3434 /** 3435 * @hide 3436 * 3437 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3438 * out of the public fields to keep the undefined bits out of the developer's way. 3439 * 3440 * Flag to specify that the hidden navigation bar would like to be shown. 3441 */ 3442 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3443 3444 /** 3445 * @hide 3446 * 3447 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3448 * out of the public fields to keep the undefined bits out of the developer's way. 3449 * 3450 * Flag to specify that the status bar is displayed in translucent mode. 3451 */ 3452 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3453 3454 /** 3455 * @hide 3456 * 3457 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3458 * out of the public fields to keep the undefined bits out of the developer's way. 3459 * 3460 * Flag to specify that the navigation bar is displayed in translucent mode. 3461 */ 3462 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3463 3464 /** 3465 * @hide 3466 * 3467 * Makes navigation bar transparent (but not the status bar). 3468 */ 3469 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3470 3471 /** 3472 * @hide 3473 * 3474 * Makes status bar transparent (but not the navigation bar). 3475 */ 3476 public static final int STATUS_BAR_TRANSPARENT = 0x00000008; 3477 3478 /** 3479 * @hide 3480 * 3481 * Makes both status bar and navigation bar transparent. 3482 */ 3483 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3484 | STATUS_BAR_TRANSPARENT; 3485 3486 /** 3487 * @hide 3488 */ 3489 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3490 3491 /** 3492 * These are the system UI flags that can be cleared by events outside 3493 * of an application. Currently this is just the ability to tap on the 3494 * screen while hiding the navigation bar to have it return. 3495 * @hide 3496 */ 3497 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3498 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3499 | SYSTEM_UI_FLAG_FULLSCREEN; 3500 3501 /** 3502 * Flags that can impact the layout in relation to system UI. 3503 */ 3504 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3505 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3506 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3507 3508 /** @hide */ 3509 @IntDef(flag = true, 3510 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3511 @Retention(RetentionPolicy.SOURCE) 3512 public @interface FindViewFlags {} 3513 3514 /** 3515 * Find views that render the specified text. 3516 * 3517 * @see #findViewsWithText(ArrayList, CharSequence, int) 3518 */ 3519 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3520 3521 /** 3522 * Find find views that contain the specified content description. 3523 * 3524 * @see #findViewsWithText(ArrayList, CharSequence, int) 3525 */ 3526 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3527 3528 /** 3529 * Find views that contain {@link AccessibilityNodeProvider}. Such 3530 * a View is a root of virtual view hierarchy and may contain the searched 3531 * text. If this flag is set Views with providers are automatically 3532 * added and it is a responsibility of the client to call the APIs of 3533 * the provider to determine whether the virtual tree rooted at this View 3534 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3535 * representing the virtual views with this text. 3536 * 3537 * @see #findViewsWithText(ArrayList, CharSequence, int) 3538 * 3539 * @hide 3540 */ 3541 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3542 3543 /** 3544 * The undefined cursor position. 3545 * 3546 * @hide 3547 */ 3548 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3549 3550 /** 3551 * Indicates that the screen has changed state and is now off. 3552 * 3553 * @see #onScreenStateChanged(int) 3554 */ 3555 public static final int SCREEN_STATE_OFF = 0x0; 3556 3557 /** 3558 * Indicates that the screen has changed state and is now on. 3559 * 3560 * @see #onScreenStateChanged(int) 3561 */ 3562 public static final int SCREEN_STATE_ON = 0x1; 3563 3564 /** 3565 * Indicates no axis of view scrolling. 3566 */ 3567 public static final int SCROLL_AXIS_NONE = 0; 3568 3569 /** 3570 * Indicates scrolling along the horizontal axis. 3571 */ 3572 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3573 3574 /** 3575 * Indicates scrolling along the vertical axis. 3576 */ 3577 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3578 3579 /** 3580 * Controls the over-scroll mode for this view. 3581 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3582 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3583 * and {@link #OVER_SCROLL_NEVER}. 3584 */ 3585 private int mOverScrollMode; 3586 3587 /** 3588 * The parent this view is attached to. 3589 * {@hide} 3590 * 3591 * @see #getParent() 3592 */ 3593 protected ViewParent mParent; 3594 3595 /** 3596 * {@hide} 3597 */ 3598 AttachInfo mAttachInfo; 3599 3600 /** 3601 * {@hide} 3602 */ 3603 @ViewDebug.ExportedProperty(flagMapping = { 3604 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3605 name = "FORCE_LAYOUT"), 3606 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3607 name = "LAYOUT_REQUIRED"), 3608 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3609 name = "DRAWING_CACHE_INVALID", outputIf = false), 3610 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3611 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3612 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3613 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3614 }, formatToHexString = true) 3615 3616 /* @hide */ 3617 public int mPrivateFlags; 3618 int mPrivateFlags2; 3619 int mPrivateFlags3; 3620 3621 /** 3622 * This view's request for the visibility of the status bar. 3623 * @hide 3624 */ 3625 @ViewDebug.ExportedProperty(flagMapping = { 3626 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3627 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3628 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3629 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3630 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3631 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3632 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3633 equals = SYSTEM_UI_FLAG_VISIBLE, 3634 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3635 }, formatToHexString = true) 3636 int mSystemUiVisibility; 3637 3638 /** 3639 * Reference count for transient state. 3640 * @see #setHasTransientState(boolean) 3641 */ 3642 int mTransientStateCount = 0; 3643 3644 /** 3645 * Count of how many windows this view has been attached to. 3646 */ 3647 int mWindowAttachCount; 3648 3649 /** 3650 * The layout parameters associated with this view and used by the parent 3651 * {@link android.view.ViewGroup} to determine how this view should be 3652 * laid out. 3653 * {@hide} 3654 */ 3655 protected ViewGroup.LayoutParams mLayoutParams; 3656 3657 /** 3658 * The view flags hold various views states. 3659 * {@hide} 3660 */ 3661 @ViewDebug.ExportedProperty(formatToHexString = true) 3662 int mViewFlags; 3663 3664 static class TransformationInfo { 3665 /** 3666 * The transform matrix for the View. This transform is calculated internally 3667 * based on the translation, rotation, and scale properties. 3668 * 3669 * Do *not* use this variable directly; instead call getMatrix(), which will 3670 * load the value from the View's RenderNode. 3671 */ 3672 private final Matrix mMatrix = new Matrix(); 3673 3674 /** 3675 * The inverse transform matrix for the View. This transform is calculated 3676 * internally based on the translation, rotation, and scale properties. 3677 * 3678 * Do *not* use this variable directly; instead call getInverseMatrix(), 3679 * which will load the value from the View's RenderNode. 3680 */ 3681 private Matrix mInverseMatrix; 3682 3683 /** 3684 * The opacity of the View. This is a value from 0 to 1, where 0 means 3685 * completely transparent and 1 means completely opaque. 3686 */ 3687 @ViewDebug.ExportedProperty 3688 float mAlpha = 1f; 3689 3690 /** 3691 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3692 * property only used by transitions, which is composited with the other alpha 3693 * values to calculate the final visual alpha value. 3694 */ 3695 float mTransitionAlpha = 1f; 3696 } 3697 3698 /** @hide */ 3699 public TransformationInfo mTransformationInfo; 3700 3701 /** 3702 * Current clip bounds. to which all drawing of this view are constrained. 3703 */ 3704 Rect mClipBounds = null; 3705 3706 private boolean mLastIsOpaque; 3707 3708 /** 3709 * The distance in pixels from the left edge of this view's parent 3710 * to the left edge of this view. 3711 * {@hide} 3712 */ 3713 @ViewDebug.ExportedProperty(category = "layout") 3714 protected int mLeft; 3715 /** 3716 * The distance in pixels from the left edge of this view's parent 3717 * to the right edge of this view. 3718 * {@hide} 3719 */ 3720 @ViewDebug.ExportedProperty(category = "layout") 3721 protected int mRight; 3722 /** 3723 * The distance in pixels from the top edge of this view's parent 3724 * to the top edge of this view. 3725 * {@hide} 3726 */ 3727 @ViewDebug.ExportedProperty(category = "layout") 3728 protected int mTop; 3729 /** 3730 * The distance in pixels from the top edge of this view's parent 3731 * to the bottom edge of this view. 3732 * {@hide} 3733 */ 3734 @ViewDebug.ExportedProperty(category = "layout") 3735 protected int mBottom; 3736 3737 /** 3738 * The offset, in pixels, by which the content of this view is scrolled 3739 * horizontally. 3740 * {@hide} 3741 */ 3742 @ViewDebug.ExportedProperty(category = "scrolling") 3743 protected int mScrollX; 3744 /** 3745 * The offset, in pixels, by which the content of this view is scrolled 3746 * vertically. 3747 * {@hide} 3748 */ 3749 @ViewDebug.ExportedProperty(category = "scrolling") 3750 protected int mScrollY; 3751 3752 /** 3753 * The left padding in pixels, that is the distance in pixels between the 3754 * left edge of this view and the left edge of its content. 3755 * {@hide} 3756 */ 3757 @ViewDebug.ExportedProperty(category = "padding") 3758 protected int mPaddingLeft = 0; 3759 /** 3760 * The right padding in pixels, that is the distance in pixels between the 3761 * right edge of this view and the right edge of its content. 3762 * {@hide} 3763 */ 3764 @ViewDebug.ExportedProperty(category = "padding") 3765 protected int mPaddingRight = 0; 3766 /** 3767 * The top padding in pixels, that is the distance in pixels between the 3768 * top edge of this view and the top edge of its content. 3769 * {@hide} 3770 */ 3771 @ViewDebug.ExportedProperty(category = "padding") 3772 protected int mPaddingTop; 3773 /** 3774 * The bottom padding in pixels, that is the distance in pixels between the 3775 * bottom edge of this view and the bottom edge of its content. 3776 * {@hide} 3777 */ 3778 @ViewDebug.ExportedProperty(category = "padding") 3779 protected int mPaddingBottom; 3780 3781 /** 3782 * The layout insets in pixels, that is the distance in pixels between the 3783 * visible edges of this view its bounds. 3784 */ 3785 private Insets mLayoutInsets; 3786 3787 /** 3788 * Briefly describes the view and is primarily used for accessibility support. 3789 */ 3790 private CharSequence mContentDescription; 3791 3792 /** 3793 * Specifies the id of a view for which this view serves as a label for 3794 * accessibility purposes. 3795 */ 3796 private int mLabelForId = View.NO_ID; 3797 3798 /** 3799 * Predicate for matching labeled view id with its label for 3800 * accessibility purposes. 3801 */ 3802 private MatchLabelForPredicate mMatchLabelForPredicate; 3803 3804 /** 3805 * Specifies a view before which this one is visited in accessibility traversal. 3806 */ 3807 private int mAccessibilityTraversalBeforeId = NO_ID; 3808 3809 /** 3810 * Specifies a view after which this one is visited in accessibility traversal. 3811 */ 3812 private int mAccessibilityTraversalAfterId = NO_ID; 3813 3814 /** 3815 * Predicate for matching a view by its id. 3816 */ 3817 private MatchIdPredicate mMatchIdPredicate; 3818 3819 /** 3820 * Cache the paddingRight set by the user to append to the scrollbar's size. 3821 * 3822 * @hide 3823 */ 3824 @ViewDebug.ExportedProperty(category = "padding") 3825 protected int mUserPaddingRight; 3826 3827 /** 3828 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3829 * 3830 * @hide 3831 */ 3832 @ViewDebug.ExportedProperty(category = "padding") 3833 protected int mUserPaddingBottom; 3834 3835 /** 3836 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3837 * 3838 * @hide 3839 */ 3840 @ViewDebug.ExportedProperty(category = "padding") 3841 protected int mUserPaddingLeft; 3842 3843 /** 3844 * Cache the paddingStart set by the user to append to the scrollbar's size. 3845 * 3846 */ 3847 @ViewDebug.ExportedProperty(category = "padding") 3848 int mUserPaddingStart; 3849 3850 /** 3851 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3852 * 3853 */ 3854 @ViewDebug.ExportedProperty(category = "padding") 3855 int mUserPaddingEnd; 3856 3857 /** 3858 * Cache initial left padding. 3859 * 3860 * @hide 3861 */ 3862 int mUserPaddingLeftInitial; 3863 3864 /** 3865 * Cache initial right padding. 3866 * 3867 * @hide 3868 */ 3869 int mUserPaddingRightInitial; 3870 3871 /** 3872 * Default undefined padding 3873 */ 3874 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3875 3876 /** 3877 * Cache if a left padding has been defined 3878 */ 3879 private boolean mLeftPaddingDefined = false; 3880 3881 /** 3882 * Cache if a right padding has been defined 3883 */ 3884 private boolean mRightPaddingDefined = false; 3885 3886 /** 3887 * @hide 3888 */ 3889 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3890 /** 3891 * @hide 3892 */ 3893 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3894 3895 private LongSparseLongArray mMeasureCache; 3896 3897 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3898 private Drawable mBackground; 3899 private TintInfo mBackgroundTint; 3900 3901 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3902 private ForegroundInfo mForegroundInfo; 3903 3904 private Drawable mScrollIndicatorDrawable; 3905 3906 /** 3907 * RenderNode used for backgrounds. 3908 * <p> 3909 * When non-null and valid, this is expected to contain an up-to-date copy 3910 * of the background drawable. It is cleared on temporary detach, and reset 3911 * on cleanup. 3912 */ 3913 private RenderNode mBackgroundRenderNode; 3914 3915 private int mBackgroundResource; 3916 private boolean mBackgroundSizeChanged; 3917 3918 /** The default focus highlight. 3919 * @see #mDefaultFocusHighlightEnabled 3920 * @see Drawable#hasFocusStateSpecified() 3921 */ 3922 private Drawable mDefaultFocusHighlight; 3923 private Drawable mDefaultFocusHighlightCache; 3924 private boolean mDefaultFocusHighlightSizeChanged; 3925 /** 3926 * True if the default focus highlight is needed on the target device. 3927 */ 3928 private static boolean sUseDefaultFocusHighlight; 3929 3930 private String mTransitionName; 3931 3932 static class TintInfo { 3933 ColorStateList mTintList; 3934 PorterDuff.Mode mTintMode; 3935 boolean mHasTintMode; 3936 boolean mHasTintList; 3937 } 3938 3939 private static class ForegroundInfo { 3940 private Drawable mDrawable; 3941 private TintInfo mTintInfo; 3942 private int mGravity = Gravity.FILL; 3943 private boolean mInsidePadding = true; 3944 private boolean mBoundsChanged = true; 3945 private final Rect mSelfBounds = new Rect(); 3946 private final Rect mOverlayBounds = new Rect(); 3947 } 3948 3949 static class ListenerInfo { 3950 /** 3951 * Listener used to dispatch focus change events. 3952 * This field should be made private, so it is hidden from the SDK. 3953 * {@hide} 3954 */ 3955 protected OnFocusChangeListener mOnFocusChangeListener; 3956 3957 /** 3958 * Listeners for layout change events. 3959 */ 3960 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3961 3962 protected OnScrollChangeListener mOnScrollChangeListener; 3963 3964 /** 3965 * Listeners for attach events. 3966 */ 3967 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3968 3969 /** 3970 * Listener used to dispatch click events. 3971 * This field should be made private, so it is hidden from the SDK. 3972 * {@hide} 3973 */ 3974 public OnClickListener mOnClickListener; 3975 3976 /** 3977 * Listener used to dispatch long click events. 3978 * This field should be made private, so it is hidden from the SDK. 3979 * {@hide} 3980 */ 3981 protected OnLongClickListener mOnLongClickListener; 3982 3983 /** 3984 * Listener used to dispatch context click events. This field should be made private, so it 3985 * is hidden from the SDK. 3986 * {@hide} 3987 */ 3988 protected OnContextClickListener mOnContextClickListener; 3989 3990 /** 3991 * Listener used to build the context menu. 3992 * This field should be made private, so it is hidden from the SDK. 3993 * {@hide} 3994 */ 3995 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3996 3997 private OnKeyListener mOnKeyListener; 3998 3999 private OnTouchListener mOnTouchListener; 4000 4001 private OnHoverListener mOnHoverListener; 4002 4003 private OnGenericMotionListener mOnGenericMotionListener; 4004 4005 private OnDragListener mOnDragListener; 4006 4007 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 4008 4009 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 4010 4011 OnCapturedPointerListener mOnCapturedPointerListener; 4012 } 4013 4014 ListenerInfo mListenerInfo; 4015 4016 private static class TooltipInfo { 4017 /** 4018 * Text to be displayed in a tooltip popup. 4019 */ 4020 @Nullable 4021 CharSequence mTooltipText; 4022 4023 /** 4024 * View-relative position of the tooltip anchor point. 4025 */ 4026 int mAnchorX; 4027 int mAnchorY; 4028 4029 /** 4030 * The tooltip popup. 4031 */ 4032 @Nullable 4033 TooltipPopup mTooltipPopup; 4034 4035 /** 4036 * Set to true if the tooltip was shown as a result of a long click. 4037 */ 4038 boolean mTooltipFromLongClick; 4039 4040 /** 4041 * Keep these Runnables so that they can be used to reschedule. 4042 */ 4043 Runnable mShowTooltipRunnable; 4044 Runnable mHideTooltipRunnable; 4045 } 4046 4047 TooltipInfo mTooltipInfo; 4048 4049 // Temporary values used to hold (x,y) coordinates when delegating from the 4050 // two-arg performLongClick() method to the legacy no-arg version. 4051 private float mLongClickX = Float.NaN; 4052 private float mLongClickY = Float.NaN; 4053 4054 /** 4055 * The application environment this view lives in. 4056 * This field should be made private, so it is hidden from the SDK. 4057 * {@hide} 4058 */ 4059 @ViewDebug.ExportedProperty(deepExport = true) 4060 protected Context mContext; 4061 4062 private final Resources mResources; 4063 4064 private ScrollabilityCache mScrollCache; 4065 4066 private int[] mDrawableState = null; 4067 4068 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 4069 4070 /** 4071 * Animator that automatically runs based on state changes. 4072 */ 4073 private StateListAnimator mStateListAnimator; 4074 4075 /** 4076 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 4077 * the user may specify which view to go to next. 4078 */ 4079 private int mNextFocusLeftId = View.NO_ID; 4080 4081 /** 4082 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 4083 * the user may specify which view to go to next. 4084 */ 4085 private int mNextFocusRightId = View.NO_ID; 4086 4087 /** 4088 * When this view has focus and the next focus is {@link #FOCUS_UP}, 4089 * the user may specify which view to go to next. 4090 */ 4091 private int mNextFocusUpId = View.NO_ID; 4092 4093 /** 4094 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 4095 * the user may specify which view to go to next. 4096 */ 4097 private int mNextFocusDownId = View.NO_ID; 4098 4099 /** 4100 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 4101 * the user may specify which view to go to next. 4102 */ 4103 int mNextFocusForwardId = View.NO_ID; 4104 4105 /** 4106 * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction. 4107 * 4108 * @see #findUserSetNextKeyboardNavigationCluster(View, int) 4109 */ 4110 int mNextClusterForwardId = View.NO_ID; 4111 4112 /** 4113 * Whether this View should use a default focus highlight when it gets focused but doesn't 4114 * have {@link android.R.attr#state_focused} defined in its background. 4115 */ 4116 boolean mDefaultFocusHighlightEnabled = true; 4117 4118 private CheckForLongPress mPendingCheckForLongPress; 4119 private CheckForTap mPendingCheckForTap = null; 4120 private PerformClick mPerformClick; 4121 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 4122 4123 private UnsetPressedState mUnsetPressedState; 4124 4125 /** 4126 * Whether the long press's action has been invoked. The tap's action is invoked on the 4127 * up event while a long press is invoked as soon as the long press duration is reached, so 4128 * a long press could be performed before the tap is checked, in which case the tap's action 4129 * should not be invoked. 4130 */ 4131 private boolean mHasPerformedLongPress; 4132 4133 /** 4134 * Whether a context click button is currently pressed down. This is true when the stylus is 4135 * touching the screen and the primary button has been pressed, or if a mouse's right button is 4136 * pressed. This is false once the button is released or if the stylus has been lifted. 4137 */ 4138 private boolean mInContextButtonPress; 4139 4140 /** 4141 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 4142 * true after a stylus button press has occured, when the next up event should not be recognized 4143 * as a tap. 4144 */ 4145 private boolean mIgnoreNextUpEvent; 4146 4147 /** 4148 * The minimum height of the view. We'll try our best to have the height 4149 * of this view to at least this amount. 4150 */ 4151 @ViewDebug.ExportedProperty(category = "measurement") 4152 private int mMinHeight; 4153 4154 /** 4155 * The minimum width of the view. We'll try our best to have the width 4156 * of this view to at least this amount. 4157 */ 4158 @ViewDebug.ExportedProperty(category = "measurement") 4159 private int mMinWidth; 4160 4161 /** 4162 * The delegate to handle touch events that are physically in this view 4163 * but should be handled by another view. 4164 */ 4165 private TouchDelegate mTouchDelegate = null; 4166 4167 /** 4168 * Solid color to use as a background when creating the drawing cache. Enables 4169 * the cache to use 16 bit bitmaps instead of 32 bit. 4170 */ 4171 private int mDrawingCacheBackgroundColor = 0; 4172 4173 /** 4174 * Special tree observer used when mAttachInfo is null. 4175 */ 4176 private ViewTreeObserver mFloatingTreeObserver; 4177 4178 /** 4179 * Cache the touch slop from the context that created the view. 4180 */ 4181 private int mTouchSlop; 4182 4183 /** 4184 * Object that handles automatic animation of view properties. 4185 */ 4186 private ViewPropertyAnimator mAnimator = null; 4187 4188 /** 4189 * List of registered FrameMetricsObservers. 4190 */ 4191 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 4192 4193 /** 4194 * Flag indicating that a drag can cross window boundaries. When 4195 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4196 * with this flag set, all visible applications with targetSdkVersion >= 4197 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 4198 * in the drag operation and receive the dragged content. 4199 * 4200 * <p>If this is the only flag set, then the drag recipient will only have access to text data 4201 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 4202 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 4203 */ 4204 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 4205 4206 /** 4207 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4208 * request read access to the content URI(s) contained in the {@link ClipData} object. 4209 * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION 4210 */ 4211 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 4212 4213 /** 4214 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4215 * request write access to the content URI(s) contained in the {@link ClipData} object. 4216 * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION 4217 */ 4218 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 4219 4220 /** 4221 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4222 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 4223 * reboots until explicitly revoked with 4224 * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}. 4225 * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION 4226 */ 4227 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 4228 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 4229 4230 /** 4231 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4232 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 4233 * match against the original granted URI. 4234 * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION 4235 */ 4236 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 4237 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 4238 4239 /** 4240 * Flag indicating that the drag shadow will be opaque. When 4241 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4242 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 4243 */ 4244 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 4245 4246 /** 4247 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 4248 */ 4249 private float mVerticalScrollFactor; 4250 4251 /** 4252 * Position of the vertical scroll bar. 4253 */ 4254 private int mVerticalScrollbarPosition; 4255 4256 /** 4257 * Position the scroll bar at the default position as determined by the system. 4258 */ 4259 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 4260 4261 /** 4262 * Position the scroll bar along the left edge. 4263 */ 4264 public static final int SCROLLBAR_POSITION_LEFT = 1; 4265 4266 /** 4267 * Position the scroll bar along the right edge. 4268 */ 4269 public static final int SCROLLBAR_POSITION_RIGHT = 2; 4270 4271 /** 4272 * Indicates that the view does not have a layer. 4273 * 4274 * @see #getLayerType() 4275 * @see #setLayerType(int, android.graphics.Paint) 4276 * @see #LAYER_TYPE_SOFTWARE 4277 * @see #LAYER_TYPE_HARDWARE 4278 */ 4279 public static final int LAYER_TYPE_NONE = 0; 4280 4281 /** 4282 * <p>Indicates that the view has a software layer. A software layer is backed 4283 * by a bitmap and causes the view to be rendered using Android's software 4284 * rendering pipeline, even if hardware acceleration is enabled.</p> 4285 * 4286 * <p>Software layers have various usages:</p> 4287 * <p>When the application is not using hardware acceleration, a software layer 4288 * is useful to apply a specific color filter and/or blending mode and/or 4289 * translucency to a view and all its children.</p> 4290 * <p>When the application is using hardware acceleration, a software layer 4291 * is useful to render drawing primitives not supported by the hardware 4292 * accelerated pipeline. It can also be used to cache a complex view tree 4293 * into a texture and reduce the complexity of drawing operations. For instance, 4294 * when animating a complex view tree with a translation, a software layer can 4295 * be used to render the view tree only once.</p> 4296 * <p>Software layers should be avoided when the affected view tree updates 4297 * often. Every update will require to re-render the software layer, which can 4298 * potentially be slow (particularly when hardware acceleration is turned on 4299 * since the layer will have to be uploaded into a hardware texture after every 4300 * update.)</p> 4301 * 4302 * @see #getLayerType() 4303 * @see #setLayerType(int, android.graphics.Paint) 4304 * @see #LAYER_TYPE_NONE 4305 * @see #LAYER_TYPE_HARDWARE 4306 */ 4307 public static final int LAYER_TYPE_SOFTWARE = 1; 4308 4309 /** 4310 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 4311 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 4312 * OpenGL hardware) and causes the view to be rendered using Android's hardware 4313 * rendering pipeline, but only if hardware acceleration is turned on for the 4314 * view hierarchy. When hardware acceleration is turned off, hardware layers 4315 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 4316 * 4317 * <p>A hardware layer is useful to apply a specific color filter and/or 4318 * blending mode and/or translucency to a view and all its children.</p> 4319 * <p>A hardware layer can be used to cache a complex view tree into a 4320 * texture and reduce the complexity of drawing operations. For instance, 4321 * when animating a complex view tree with a translation, a hardware layer can 4322 * be used to render the view tree only once.</p> 4323 * <p>A hardware layer can also be used to increase the rendering quality when 4324 * rotation transformations are applied on a view. It can also be used to 4325 * prevent potential clipping issues when applying 3D transforms on a view.</p> 4326 * 4327 * @see #getLayerType() 4328 * @see #setLayerType(int, android.graphics.Paint) 4329 * @see #LAYER_TYPE_NONE 4330 * @see #LAYER_TYPE_SOFTWARE 4331 */ 4332 public static final int LAYER_TYPE_HARDWARE = 2; 4333 4334 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4335 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 4336 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 4337 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 4338 }) 4339 int mLayerType = LAYER_TYPE_NONE; 4340 Paint mLayerPaint; 4341 4342 /** 4343 * Set to true when drawing cache is enabled and cannot be created. 4344 * 4345 * @hide 4346 */ 4347 public boolean mCachingFailed; 4348 private Bitmap mDrawingCache; 4349 private Bitmap mUnscaledDrawingCache; 4350 4351 /** 4352 * RenderNode holding View properties, potentially holding a DisplayList of View content. 4353 * <p> 4354 * When non-null and valid, this is expected to contain an up-to-date copy 4355 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 4356 * cleanup. 4357 */ 4358 final RenderNode mRenderNode; 4359 4360 /** 4361 * Set to true when the view is sending hover accessibility events because it 4362 * is the innermost hovered view. 4363 */ 4364 private boolean mSendingHoverAccessibilityEvents; 4365 4366 /** 4367 * Delegate for injecting accessibility functionality. 4368 */ 4369 AccessibilityDelegate mAccessibilityDelegate; 4370 4371 /** 4372 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 4373 * and add/remove objects to/from the overlay directly through the Overlay methods. 4374 */ 4375 ViewOverlay mOverlay; 4376 4377 /** 4378 * The currently active parent view for receiving delegated nested scrolling events. 4379 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 4380 * by {@link #stopNestedScroll()} at the same point where we clear 4381 * requestDisallowInterceptTouchEvent. 4382 */ 4383 private ViewParent mNestedScrollingParent; 4384 4385 /** 4386 * Consistency verifier for debugging purposes. 4387 * @hide 4388 */ 4389 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 4390 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 4391 new InputEventConsistencyVerifier(this, 0) : null; 4392 4393 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 4394 4395 private int[] mTempNestedScrollConsumed; 4396 4397 /** 4398 * An overlay is going to draw this View instead of being drawn as part of this 4399 * View's parent. mGhostView is the View in the Overlay that must be invalidated 4400 * when this view is invalidated. 4401 */ 4402 GhostView mGhostView; 4403 4404 /** 4405 * Holds pairs of adjacent attribute data: attribute name followed by its value. 4406 * @hide 4407 */ 4408 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 4409 public String[] mAttributes; 4410 4411 /** 4412 * Maps a Resource id to its name. 4413 */ 4414 private static SparseArray<String> mAttributeMap; 4415 4416 /** 4417 * Queue of pending runnables. Used to postpone calls to post() until this 4418 * view is attached and has a handler. 4419 */ 4420 private HandlerActionQueue mRunQueue; 4421 4422 /** 4423 * The pointer icon when the mouse hovers on this view. The default is null. 4424 */ 4425 private PointerIcon mPointerIcon; 4426 4427 /** 4428 * @hide 4429 */ 4430 String mStartActivityRequestWho; 4431 4432 @Nullable 4433 private RoundScrollbarRenderer mRoundScrollbarRenderer; 4434 4435 /** Used to delay visibility updates sent to the autofill manager */ 4436 private Handler mVisibilityChangeForAutofillHandler; 4437 4438 /** 4439 * Simple constructor to use when creating a view from code. 4440 * 4441 * @param context The Context the view is running in, through which it can 4442 * access the current theme, resources, etc. 4443 */ 4444 public View(Context context) { 4445 mContext = context; 4446 mResources = context != null ? context.getResources() : null; 4447 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO; 4448 // Set some flags defaults 4449 mPrivateFlags2 = 4450 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 4451 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 4452 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 4453 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4454 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4455 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4456 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4457 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4458 mUserPaddingStart = UNDEFINED_PADDING; 4459 mUserPaddingEnd = UNDEFINED_PADDING; 4460 mRenderNode = RenderNode.create(getClass().getName(), this); 4461 4462 if (!sCompatibilityDone && context != null) { 4463 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4464 4465 // Older apps may need this compatibility hack for measurement. 4466 sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1; 4467 4468 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4469 // of whether a layout was requested on that View. 4470 sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT; 4471 4472 Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M; 4473 Canvas.sCompatibilitySetBitmap = targetSdkVersion < Build.VERSION_CODES.O; 4474 4475 // In M and newer, our widgets can pass a "hint" value in the size 4476 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4477 // know what the expected parent size is going to be, so e.g. list items can size 4478 // themselves at 1/3 the size of their container. It breaks older apps though, 4479 // specifically apps that use some popular open source libraries. 4480 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M; 4481 4482 // Old versions of the platform would give different results from 4483 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4484 // modes, so we always need to run an additional EXACTLY pass. 4485 sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M; 4486 4487 // Prior to N, layout params could change without requiring a 4488 // subsequent call to setLayoutParams() and they would usually 4489 // work. Partial layout breaks this assumption. 4490 sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M; 4491 4492 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4493 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4494 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M; 4495 4496 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4497 // in apps so we target check it to avoid breaking existing apps. 4498 sPreserveMarginParamsInLayoutParamConversion = 4499 targetSdkVersion >= Build.VERSION_CODES.N; 4500 4501 sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N; 4502 4503 sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O; 4504 4505 sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O; 4506 4507 sUseDefaultFocusHighlight = context.getResources().getBoolean( 4508 com.android.internal.R.bool.config_useDefaultFocusHighlight); 4509 4510 sCompatibilityDone = true; 4511 } 4512 } 4513 4514 /** 4515 * Constructor that is called when inflating a view from XML. This is called 4516 * when a view is being constructed from an XML file, supplying attributes 4517 * that were specified in the XML file. This version uses a default style of 4518 * 0, so the only attribute values applied are those in the Context's Theme 4519 * and the given AttributeSet. 4520 * 4521 * <p> 4522 * The method onFinishInflate() will be called after all children have been 4523 * added. 4524 * 4525 * @param context The Context the view is running in, through which it can 4526 * access the current theme, resources, etc. 4527 * @param attrs The attributes of the XML tag that is inflating the view. 4528 * @see #View(Context, AttributeSet, int) 4529 */ 4530 public View(Context context, @Nullable AttributeSet attrs) { 4531 this(context, attrs, 0); 4532 } 4533 4534 /** 4535 * Perform inflation from XML and apply a class-specific base style from a 4536 * theme attribute. This constructor of View allows subclasses to use their 4537 * own base style when they are inflating. For example, a Button class's 4538 * constructor would call this version of the super class constructor and 4539 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4540 * allows the theme's button style to modify all of the base view attributes 4541 * (in particular its background) as well as the Button class's attributes. 4542 * 4543 * @param context The Context the view is running in, through which it can 4544 * access the current theme, resources, etc. 4545 * @param attrs The attributes of the XML tag that is inflating the view. 4546 * @param defStyleAttr An attribute in the current theme that contains a 4547 * reference to a style resource that supplies default values for 4548 * the view. Can be 0 to not look for defaults. 4549 * @see #View(Context, AttributeSet) 4550 */ 4551 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4552 this(context, attrs, defStyleAttr, 0); 4553 } 4554 4555 /** 4556 * Perform inflation from XML and apply a class-specific base style from a 4557 * theme attribute or style resource. This constructor of View allows 4558 * subclasses to use their own base style when they are inflating. 4559 * <p> 4560 * When determining the final value of a particular attribute, there are 4561 * four inputs that come into play: 4562 * <ol> 4563 * <li>Any attribute values in the given AttributeSet. 4564 * <li>The style resource specified in the AttributeSet (named "style"). 4565 * <li>The default style specified by <var>defStyleAttr</var>. 4566 * <li>The default style specified by <var>defStyleRes</var>. 4567 * <li>The base values in this theme. 4568 * </ol> 4569 * <p> 4570 * Each of these inputs is considered in-order, with the first listed taking 4571 * precedence over the following ones. In other words, if in the 4572 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4573 * , then the button's text will <em>always</em> be black, regardless of 4574 * what is specified in any of the styles. 4575 * 4576 * @param context The Context the view is running in, through which it can 4577 * access the current theme, resources, etc. 4578 * @param attrs The attributes of the XML tag that is inflating the view. 4579 * @param defStyleAttr An attribute in the current theme that contains a 4580 * reference to a style resource that supplies default values for 4581 * the view. Can be 0 to not look for defaults. 4582 * @param defStyleRes A resource identifier of a style resource that 4583 * supplies default values for the view, used only if 4584 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4585 * to not look for defaults. 4586 * @see #View(Context, AttributeSet, int) 4587 */ 4588 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4589 this(context); 4590 4591 final TypedArray a = context.obtainStyledAttributes( 4592 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4593 4594 if (mDebugViewAttributes) { 4595 saveAttributeData(attrs, a); 4596 } 4597 4598 Drawable background = null; 4599 4600 int leftPadding = -1; 4601 int topPadding = -1; 4602 int rightPadding = -1; 4603 int bottomPadding = -1; 4604 int startPadding = UNDEFINED_PADDING; 4605 int endPadding = UNDEFINED_PADDING; 4606 4607 int padding = -1; 4608 int paddingHorizontal = -1; 4609 int paddingVertical = -1; 4610 4611 int viewFlagValues = 0; 4612 int viewFlagMasks = 0; 4613 4614 boolean setScrollContainer = false; 4615 4616 int x = 0; 4617 int y = 0; 4618 4619 float tx = 0; 4620 float ty = 0; 4621 float tz = 0; 4622 float elevation = 0; 4623 float rotation = 0; 4624 float rotationX = 0; 4625 float rotationY = 0; 4626 float sx = 1f; 4627 float sy = 1f; 4628 boolean transformSet = false; 4629 4630 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4631 int overScrollMode = mOverScrollMode; 4632 boolean initializeScrollbars = false; 4633 boolean initializeScrollIndicators = false; 4634 4635 boolean startPaddingDefined = false; 4636 boolean endPaddingDefined = false; 4637 boolean leftPaddingDefined = false; 4638 boolean rightPaddingDefined = false; 4639 4640 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4641 4642 // Set default values. 4643 viewFlagValues |= FOCUSABLE_AUTO; 4644 viewFlagMasks |= FOCUSABLE_AUTO; 4645 4646 final int N = a.getIndexCount(); 4647 for (int i = 0; i < N; i++) { 4648 int attr = a.getIndex(i); 4649 switch (attr) { 4650 case com.android.internal.R.styleable.View_background: 4651 background = a.getDrawable(attr); 4652 break; 4653 case com.android.internal.R.styleable.View_padding: 4654 padding = a.getDimensionPixelSize(attr, -1); 4655 mUserPaddingLeftInitial = padding; 4656 mUserPaddingRightInitial = padding; 4657 leftPaddingDefined = true; 4658 rightPaddingDefined = true; 4659 break; 4660 case com.android.internal.R.styleable.View_paddingHorizontal: 4661 paddingHorizontal = a.getDimensionPixelSize(attr, -1); 4662 mUserPaddingLeftInitial = paddingHorizontal; 4663 mUserPaddingRightInitial = paddingHorizontal; 4664 leftPaddingDefined = true; 4665 rightPaddingDefined = true; 4666 break; 4667 case com.android.internal.R.styleable.View_paddingVertical: 4668 paddingVertical = a.getDimensionPixelSize(attr, -1); 4669 break; 4670 case com.android.internal.R.styleable.View_paddingLeft: 4671 leftPadding = a.getDimensionPixelSize(attr, -1); 4672 mUserPaddingLeftInitial = leftPadding; 4673 leftPaddingDefined = true; 4674 break; 4675 case com.android.internal.R.styleable.View_paddingTop: 4676 topPadding = a.getDimensionPixelSize(attr, -1); 4677 break; 4678 case com.android.internal.R.styleable.View_paddingRight: 4679 rightPadding = a.getDimensionPixelSize(attr, -1); 4680 mUserPaddingRightInitial = rightPadding; 4681 rightPaddingDefined = true; 4682 break; 4683 case com.android.internal.R.styleable.View_paddingBottom: 4684 bottomPadding = a.getDimensionPixelSize(attr, -1); 4685 break; 4686 case com.android.internal.R.styleable.View_paddingStart: 4687 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4688 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4689 break; 4690 case com.android.internal.R.styleable.View_paddingEnd: 4691 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4692 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4693 break; 4694 case com.android.internal.R.styleable.View_scrollX: 4695 x = a.getDimensionPixelOffset(attr, 0); 4696 break; 4697 case com.android.internal.R.styleable.View_scrollY: 4698 y = a.getDimensionPixelOffset(attr, 0); 4699 break; 4700 case com.android.internal.R.styleable.View_alpha: 4701 setAlpha(a.getFloat(attr, 1f)); 4702 break; 4703 case com.android.internal.R.styleable.View_transformPivotX: 4704 setPivotX(a.getDimension(attr, 0)); 4705 break; 4706 case com.android.internal.R.styleable.View_transformPivotY: 4707 setPivotY(a.getDimension(attr, 0)); 4708 break; 4709 case com.android.internal.R.styleable.View_translationX: 4710 tx = a.getDimension(attr, 0); 4711 transformSet = true; 4712 break; 4713 case com.android.internal.R.styleable.View_translationY: 4714 ty = a.getDimension(attr, 0); 4715 transformSet = true; 4716 break; 4717 case com.android.internal.R.styleable.View_translationZ: 4718 tz = a.getDimension(attr, 0); 4719 transformSet = true; 4720 break; 4721 case com.android.internal.R.styleable.View_elevation: 4722 elevation = a.getDimension(attr, 0); 4723 transformSet = true; 4724 break; 4725 case com.android.internal.R.styleable.View_rotation: 4726 rotation = a.getFloat(attr, 0); 4727 transformSet = true; 4728 break; 4729 case com.android.internal.R.styleable.View_rotationX: 4730 rotationX = a.getFloat(attr, 0); 4731 transformSet = true; 4732 break; 4733 case com.android.internal.R.styleable.View_rotationY: 4734 rotationY = a.getFloat(attr, 0); 4735 transformSet = true; 4736 break; 4737 case com.android.internal.R.styleable.View_scaleX: 4738 sx = a.getFloat(attr, 1f); 4739 transformSet = true; 4740 break; 4741 case com.android.internal.R.styleable.View_scaleY: 4742 sy = a.getFloat(attr, 1f); 4743 transformSet = true; 4744 break; 4745 case com.android.internal.R.styleable.View_id: 4746 mID = a.getResourceId(attr, NO_ID); 4747 break; 4748 case com.android.internal.R.styleable.View_tag: 4749 mTag = a.getText(attr); 4750 break; 4751 case com.android.internal.R.styleable.View_fitsSystemWindows: 4752 if (a.getBoolean(attr, false)) { 4753 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4754 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4755 } 4756 break; 4757 case com.android.internal.R.styleable.View_focusable: 4758 viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a); 4759 if ((viewFlagValues & FOCUSABLE_AUTO) == 0) { 4760 viewFlagMasks |= FOCUSABLE_MASK; 4761 } 4762 break; 4763 case com.android.internal.R.styleable.View_focusableInTouchMode: 4764 if (a.getBoolean(attr, false)) { 4765 // unset auto focus since focusableInTouchMode implies explicit focusable 4766 viewFlagValues &= ~FOCUSABLE_AUTO; 4767 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4768 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4769 } 4770 break; 4771 case com.android.internal.R.styleable.View_clickable: 4772 if (a.getBoolean(attr, false)) { 4773 viewFlagValues |= CLICKABLE; 4774 viewFlagMasks |= CLICKABLE; 4775 } 4776 break; 4777 case com.android.internal.R.styleable.View_longClickable: 4778 if (a.getBoolean(attr, false)) { 4779 viewFlagValues |= LONG_CLICKABLE; 4780 viewFlagMasks |= LONG_CLICKABLE; 4781 } 4782 break; 4783 case com.android.internal.R.styleable.View_contextClickable: 4784 if (a.getBoolean(attr, false)) { 4785 viewFlagValues |= CONTEXT_CLICKABLE; 4786 viewFlagMasks |= CONTEXT_CLICKABLE; 4787 } 4788 break; 4789 case com.android.internal.R.styleable.View_saveEnabled: 4790 if (!a.getBoolean(attr, true)) { 4791 viewFlagValues |= SAVE_DISABLED; 4792 viewFlagMasks |= SAVE_DISABLED_MASK; 4793 } 4794 break; 4795 case com.android.internal.R.styleable.View_duplicateParentState: 4796 if (a.getBoolean(attr, false)) { 4797 viewFlagValues |= DUPLICATE_PARENT_STATE; 4798 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4799 } 4800 break; 4801 case com.android.internal.R.styleable.View_visibility: 4802 final int visibility = a.getInt(attr, 0); 4803 if (visibility != 0) { 4804 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4805 viewFlagMasks |= VISIBILITY_MASK; 4806 } 4807 break; 4808 case com.android.internal.R.styleable.View_layoutDirection: 4809 // Clear any layout direction flags (included resolved bits) already set 4810 mPrivateFlags2 &= 4811 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4812 // Set the layout direction flags depending on the value of the attribute 4813 final int layoutDirection = a.getInt(attr, -1); 4814 final int value = (layoutDirection != -1) ? 4815 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4816 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4817 break; 4818 case com.android.internal.R.styleable.View_drawingCacheQuality: 4819 final int cacheQuality = a.getInt(attr, 0); 4820 if (cacheQuality != 0) { 4821 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4822 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4823 } 4824 break; 4825 case com.android.internal.R.styleable.View_contentDescription: 4826 setContentDescription(a.getString(attr)); 4827 break; 4828 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4829 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4830 break; 4831 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4832 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4833 break; 4834 case com.android.internal.R.styleable.View_labelFor: 4835 setLabelFor(a.getResourceId(attr, NO_ID)); 4836 break; 4837 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4838 if (!a.getBoolean(attr, true)) { 4839 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4840 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4841 } 4842 break; 4843 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4844 if (!a.getBoolean(attr, true)) { 4845 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4846 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4847 } 4848 break; 4849 case R.styleable.View_scrollbars: 4850 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4851 if (scrollbars != SCROLLBARS_NONE) { 4852 viewFlagValues |= scrollbars; 4853 viewFlagMasks |= SCROLLBARS_MASK; 4854 initializeScrollbars = true; 4855 } 4856 break; 4857 //noinspection deprecation 4858 case R.styleable.View_fadingEdge: 4859 if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 4860 // Ignore the attribute starting with ICS 4861 break; 4862 } 4863 // With builds < ICS, fall through and apply fading edges 4864 case R.styleable.View_requiresFadingEdge: 4865 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4866 if (fadingEdge != FADING_EDGE_NONE) { 4867 viewFlagValues |= fadingEdge; 4868 viewFlagMasks |= FADING_EDGE_MASK; 4869 initializeFadingEdgeInternal(a); 4870 } 4871 break; 4872 case R.styleable.View_scrollbarStyle: 4873 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4874 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4875 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4876 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4877 } 4878 break; 4879 case R.styleable.View_isScrollContainer: 4880 setScrollContainer = true; 4881 if (a.getBoolean(attr, false)) { 4882 setScrollContainer(true); 4883 } 4884 break; 4885 case com.android.internal.R.styleable.View_keepScreenOn: 4886 if (a.getBoolean(attr, false)) { 4887 viewFlagValues |= KEEP_SCREEN_ON; 4888 viewFlagMasks |= KEEP_SCREEN_ON; 4889 } 4890 break; 4891 case R.styleable.View_filterTouchesWhenObscured: 4892 if (a.getBoolean(attr, false)) { 4893 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4894 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4895 } 4896 break; 4897 case R.styleable.View_nextFocusLeft: 4898 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4899 break; 4900 case R.styleable.View_nextFocusRight: 4901 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4902 break; 4903 case R.styleable.View_nextFocusUp: 4904 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4905 break; 4906 case R.styleable.View_nextFocusDown: 4907 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4908 break; 4909 case R.styleable.View_nextFocusForward: 4910 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4911 break; 4912 case R.styleable.View_nextClusterForward: 4913 mNextClusterForwardId = a.getResourceId(attr, View.NO_ID); 4914 break; 4915 case R.styleable.View_minWidth: 4916 mMinWidth = a.getDimensionPixelSize(attr, 0); 4917 break; 4918 case R.styleable.View_minHeight: 4919 mMinHeight = a.getDimensionPixelSize(attr, 0); 4920 break; 4921 case R.styleable.View_onClick: 4922 if (context.isRestricted()) { 4923 throw new IllegalStateException("The android:onClick attribute cannot " 4924 + "be used within a restricted context"); 4925 } 4926 4927 final String handlerName = a.getString(attr); 4928 if (handlerName != null) { 4929 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4930 } 4931 break; 4932 case R.styleable.View_overScrollMode: 4933 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4934 break; 4935 case R.styleable.View_verticalScrollbarPosition: 4936 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4937 break; 4938 case R.styleable.View_layerType: 4939 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4940 break; 4941 case R.styleable.View_textDirection: 4942 // Clear any text direction flag already set 4943 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4944 // Set the text direction flags depending on the value of the attribute 4945 final int textDirection = a.getInt(attr, -1); 4946 if (textDirection != -1) { 4947 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4948 } 4949 break; 4950 case R.styleable.View_textAlignment: 4951 // Clear any text alignment flag already set 4952 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4953 // Set the text alignment flag depending on the value of the attribute 4954 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4955 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4956 break; 4957 case R.styleable.View_importantForAccessibility: 4958 setImportantForAccessibility(a.getInt(attr, 4959 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4960 break; 4961 case R.styleable.View_accessibilityLiveRegion: 4962 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4963 break; 4964 case R.styleable.View_transitionName: 4965 setTransitionName(a.getString(attr)); 4966 break; 4967 case R.styleable.View_nestedScrollingEnabled: 4968 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4969 break; 4970 case R.styleable.View_stateListAnimator: 4971 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4972 a.getResourceId(attr, 0))); 4973 break; 4974 case R.styleable.View_backgroundTint: 4975 // This will get applied later during setBackground(). 4976 if (mBackgroundTint == null) { 4977 mBackgroundTint = new TintInfo(); 4978 } 4979 mBackgroundTint.mTintList = a.getColorStateList( 4980 R.styleable.View_backgroundTint); 4981 mBackgroundTint.mHasTintList = true; 4982 break; 4983 case R.styleable.View_backgroundTintMode: 4984 // This will get applied later during setBackground(). 4985 if (mBackgroundTint == null) { 4986 mBackgroundTint = new TintInfo(); 4987 } 4988 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4989 R.styleable.View_backgroundTintMode, -1), null); 4990 mBackgroundTint.mHasTintMode = true; 4991 break; 4992 case R.styleable.View_outlineProvider: 4993 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4994 PROVIDER_BACKGROUND)); 4995 break; 4996 case R.styleable.View_foreground: 4997 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4998 setForeground(a.getDrawable(attr)); 4999 } 5000 break; 5001 case R.styleable.View_foregroundGravity: 5002 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5003 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 5004 } 5005 break; 5006 case R.styleable.View_foregroundTintMode: 5007 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5008 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 5009 } 5010 break; 5011 case R.styleable.View_foregroundTint: 5012 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5013 setForegroundTintList(a.getColorStateList(attr)); 5014 } 5015 break; 5016 case R.styleable.View_foregroundInsidePadding: 5017 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 5018 if (mForegroundInfo == null) { 5019 mForegroundInfo = new ForegroundInfo(); 5020 } 5021 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 5022 mForegroundInfo.mInsidePadding); 5023 } 5024 break; 5025 case R.styleable.View_scrollIndicators: 5026 final int scrollIndicators = 5027 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 5028 & SCROLL_INDICATORS_PFLAG3_MASK; 5029 if (scrollIndicators != 0) { 5030 mPrivateFlags3 |= scrollIndicators; 5031 initializeScrollIndicators = true; 5032 } 5033 break; 5034 case R.styleable.View_pointerIcon: 5035 final int resourceId = a.getResourceId(attr, 0); 5036 if (resourceId != 0) { 5037 setPointerIcon(PointerIcon.load( 5038 context.getResources(), resourceId)); 5039 } else { 5040 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 5041 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 5042 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 5043 } 5044 } 5045 break; 5046 case R.styleable.View_forceHasOverlappingRendering: 5047 if (a.peekValue(attr) != null) { 5048 forceHasOverlappingRendering(a.getBoolean(attr, true)); 5049 } 5050 break; 5051 case R.styleable.View_tooltipText: 5052 setTooltipText(a.getText(attr)); 5053 break; 5054 case R.styleable.View_keyboardNavigationCluster: 5055 if (a.peekValue(attr) != null) { 5056 setKeyboardNavigationCluster(a.getBoolean(attr, true)); 5057 } 5058 break; 5059 case R.styleable.View_focusedByDefault: 5060 if (a.peekValue(attr) != null) { 5061 setFocusedByDefault(a.getBoolean(attr, true)); 5062 } 5063 break; 5064 case R.styleable.View_autofillHints: 5065 if (a.peekValue(attr) != null) { 5066 CharSequence[] rawHints = null; 5067 String rawString = null; 5068 5069 if (a.getType(attr) == TypedValue.TYPE_REFERENCE) { 5070 int resId = a.getResourceId(attr, 0); 5071 5072 try { 5073 rawHints = a.getTextArray(attr); 5074 } catch (Resources.NotFoundException e) { 5075 rawString = getResources().getString(resId); 5076 } 5077 } else { 5078 rawString = a.getString(attr); 5079 } 5080 5081 if (rawHints == null) { 5082 if (rawString == null) { 5083 throw new IllegalArgumentException( 5084 "Could not resolve autofillHints"); 5085 } else { 5086 rawHints = rawString.split(","); 5087 } 5088 } 5089 5090 String[] hints = new String[rawHints.length]; 5091 5092 int numHints = rawHints.length; 5093 for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) { 5094 hints[rawHintNum] = rawHints[rawHintNum].toString().trim(); 5095 } 5096 setAutofillHints(hints); 5097 } 5098 break; 5099 case R.styleable.View_importantForAutofill: 5100 if (a.peekValue(attr) != null) { 5101 setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO)); 5102 } 5103 break; 5104 case R.styleable.View_defaultFocusHighlightEnabled: 5105 if (a.peekValue(attr) != null) { 5106 setDefaultFocusHighlightEnabled(a.getBoolean(attr, true)); 5107 } 5108 break; 5109 } 5110 } 5111 5112 setOverScrollMode(overScrollMode); 5113 5114 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 5115 // the resolved layout direction). Those cached values will be used later during padding 5116 // resolution. 5117 mUserPaddingStart = startPadding; 5118 mUserPaddingEnd = endPadding; 5119 5120 if (background != null) { 5121 setBackground(background); 5122 } 5123 5124 // setBackground above will record that padding is currently provided by the background. 5125 // If we have padding specified via xml, record that here instead and use it. 5126 mLeftPaddingDefined = leftPaddingDefined; 5127 mRightPaddingDefined = rightPaddingDefined; 5128 5129 if (padding >= 0) { 5130 leftPadding = padding; 5131 topPadding = padding; 5132 rightPadding = padding; 5133 bottomPadding = padding; 5134 mUserPaddingLeftInitial = padding; 5135 mUserPaddingRightInitial = padding; 5136 } else { 5137 if (paddingHorizontal >= 0) { 5138 leftPadding = paddingHorizontal; 5139 rightPadding = paddingHorizontal; 5140 mUserPaddingLeftInitial = paddingHorizontal; 5141 mUserPaddingRightInitial = paddingHorizontal; 5142 } 5143 if (paddingVertical >= 0) { 5144 topPadding = paddingVertical; 5145 bottomPadding = paddingVertical; 5146 } 5147 } 5148 5149 if (isRtlCompatibilityMode()) { 5150 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 5151 // left / right padding are used if defined (meaning here nothing to do). If they are not 5152 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 5153 // start / end and resolve them as left / right (layout direction is not taken into account). 5154 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5155 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5156 // defined. 5157 if (!mLeftPaddingDefined && startPaddingDefined) { 5158 leftPadding = startPadding; 5159 } 5160 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 5161 if (!mRightPaddingDefined && endPaddingDefined) { 5162 rightPadding = endPadding; 5163 } 5164 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 5165 } else { 5166 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 5167 // values defined. Otherwise, left /right values are used. 5168 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5169 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5170 // defined. 5171 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 5172 5173 if (mLeftPaddingDefined && !hasRelativePadding) { 5174 mUserPaddingLeftInitial = leftPadding; 5175 } 5176 if (mRightPaddingDefined && !hasRelativePadding) { 5177 mUserPaddingRightInitial = rightPadding; 5178 } 5179 } 5180 5181 internalSetPadding( 5182 mUserPaddingLeftInitial, 5183 topPadding >= 0 ? topPadding : mPaddingTop, 5184 mUserPaddingRightInitial, 5185 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 5186 5187 if (viewFlagMasks != 0) { 5188 setFlags(viewFlagValues, viewFlagMasks); 5189 } 5190 5191 if (initializeScrollbars) { 5192 initializeScrollbarsInternal(a); 5193 } 5194 5195 if (initializeScrollIndicators) { 5196 initializeScrollIndicatorsInternal(); 5197 } 5198 5199 a.recycle(); 5200 5201 // Needs to be called after mViewFlags is set 5202 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 5203 recomputePadding(); 5204 } 5205 5206 if (x != 0 || y != 0) { 5207 scrollTo(x, y); 5208 } 5209 5210 if (transformSet) { 5211 setTranslationX(tx); 5212 setTranslationY(ty); 5213 setTranslationZ(tz); 5214 setElevation(elevation); 5215 setRotation(rotation); 5216 setRotationX(rotationX); 5217 setRotationY(rotationY); 5218 setScaleX(sx); 5219 setScaleY(sy); 5220 } 5221 5222 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 5223 setScrollContainer(true); 5224 } 5225 5226 computeOpaqueFlags(); 5227 } 5228 5229 /** 5230 * An implementation of OnClickListener that attempts to lazily load a 5231 * named click handling method from a parent or ancestor context. 5232 */ 5233 private static class DeclaredOnClickListener implements OnClickListener { 5234 private final View mHostView; 5235 private final String mMethodName; 5236 5237 private Method mResolvedMethod; 5238 private Context mResolvedContext; 5239 5240 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 5241 mHostView = hostView; 5242 mMethodName = methodName; 5243 } 5244 5245 @Override 5246 public void onClick(@NonNull View v) { 5247 if (mResolvedMethod == null) { 5248 resolveMethod(mHostView.getContext(), mMethodName); 5249 } 5250 5251 try { 5252 mResolvedMethod.invoke(mResolvedContext, v); 5253 } catch (IllegalAccessException e) { 5254 throw new IllegalStateException( 5255 "Could not execute non-public method for android:onClick", e); 5256 } catch (InvocationTargetException e) { 5257 throw new IllegalStateException( 5258 "Could not execute method for android:onClick", e); 5259 } 5260 } 5261 5262 @NonNull 5263 private void resolveMethod(@Nullable Context context, @NonNull String name) { 5264 while (context != null) { 5265 try { 5266 if (!context.isRestricted()) { 5267 final Method method = context.getClass().getMethod(mMethodName, View.class); 5268 if (method != null) { 5269 mResolvedMethod = method; 5270 mResolvedContext = context; 5271 return; 5272 } 5273 } 5274 } catch (NoSuchMethodException e) { 5275 // Failed to find method, keep searching up the hierarchy. 5276 } 5277 5278 if (context instanceof ContextWrapper) { 5279 context = ((ContextWrapper) context).getBaseContext(); 5280 } else { 5281 // Can't search up the hierarchy, null out and fail. 5282 context = null; 5283 } 5284 } 5285 5286 final int id = mHostView.getId(); 5287 final String idText = id == NO_ID ? "" : " with id '" 5288 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 5289 throw new IllegalStateException("Could not find method " + mMethodName 5290 + "(View) in a parent or ancestor Context for android:onClick " 5291 + "attribute defined on view " + mHostView.getClass() + idText); 5292 } 5293 } 5294 5295 /** 5296 * Non-public constructor for use in testing 5297 */ 5298 View() { 5299 mResources = null; 5300 mRenderNode = RenderNode.create(getClass().getName(), this); 5301 } 5302 5303 final boolean debugDraw() { 5304 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout; 5305 } 5306 5307 private static SparseArray<String> getAttributeMap() { 5308 if (mAttributeMap == null) { 5309 mAttributeMap = new SparseArray<>(); 5310 } 5311 return mAttributeMap; 5312 } 5313 5314 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 5315 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 5316 final int indexCount = t.getIndexCount(); 5317 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 5318 5319 int i = 0; 5320 5321 // Store raw XML attributes. 5322 for (int j = 0; j < attrsCount; ++j) { 5323 attributes[i] = attrs.getAttributeName(j); 5324 attributes[i + 1] = attrs.getAttributeValue(j); 5325 i += 2; 5326 } 5327 5328 // Store resolved styleable attributes. 5329 final Resources res = t.getResources(); 5330 final SparseArray<String> attributeMap = getAttributeMap(); 5331 for (int j = 0; j < indexCount; ++j) { 5332 final int index = t.getIndex(j); 5333 if (!t.hasValueOrEmpty(index)) { 5334 // Value is undefined. Skip it. 5335 continue; 5336 } 5337 5338 final int resourceId = t.getResourceId(index, 0); 5339 if (resourceId == 0) { 5340 // Value is not a reference. Skip it. 5341 continue; 5342 } 5343 5344 String resourceName = attributeMap.get(resourceId); 5345 if (resourceName == null) { 5346 try { 5347 resourceName = res.getResourceName(resourceId); 5348 } catch (Resources.NotFoundException e) { 5349 resourceName = "0x" + Integer.toHexString(resourceId); 5350 } 5351 attributeMap.put(resourceId, resourceName); 5352 } 5353 5354 attributes[i] = resourceName; 5355 attributes[i + 1] = t.getString(index); 5356 i += 2; 5357 } 5358 5359 // Trim to fit contents. 5360 final String[] trimmed = new String[i]; 5361 System.arraycopy(attributes, 0, trimmed, 0, i); 5362 mAttributes = trimmed; 5363 } 5364 5365 public String toString() { 5366 StringBuilder out = new StringBuilder(128); 5367 out.append(getClass().getName()); 5368 out.append('{'); 5369 out.append(Integer.toHexString(System.identityHashCode(this))); 5370 out.append(' '); 5371 switch (mViewFlags&VISIBILITY_MASK) { 5372 case VISIBLE: out.append('V'); break; 5373 case INVISIBLE: out.append('I'); break; 5374 case GONE: out.append('G'); break; 5375 default: out.append('.'); break; 5376 } 5377 out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.'); 5378 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 5379 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 5380 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 5381 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 5382 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 5383 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 5384 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 5385 out.append(' '); 5386 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 5387 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 5388 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 5389 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 5390 out.append('p'); 5391 } else { 5392 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 5393 } 5394 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 5395 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 5396 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 5397 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 5398 out.append(' '); 5399 out.append(mLeft); 5400 out.append(','); 5401 out.append(mTop); 5402 out.append('-'); 5403 out.append(mRight); 5404 out.append(','); 5405 out.append(mBottom); 5406 final int id = getId(); 5407 if (id != NO_ID) { 5408 out.append(" #"); 5409 out.append(Integer.toHexString(id)); 5410 final Resources r = mResources; 5411 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 5412 try { 5413 String pkgname; 5414 switch (id&0xff000000) { 5415 case 0x7f000000: 5416 pkgname="app"; 5417 break; 5418 case 0x01000000: 5419 pkgname="android"; 5420 break; 5421 default: 5422 pkgname = r.getResourcePackageName(id); 5423 break; 5424 } 5425 String typename = r.getResourceTypeName(id); 5426 String entryname = r.getResourceEntryName(id); 5427 out.append(" "); 5428 out.append(pkgname); 5429 out.append(":"); 5430 out.append(typename); 5431 out.append("/"); 5432 out.append(entryname); 5433 } catch (Resources.NotFoundException e) { 5434 } 5435 } 5436 } 5437 out.append("}"); 5438 return out.toString(); 5439 } 5440 5441 /** 5442 * <p> 5443 * Initializes the fading edges from a given set of styled attributes. This 5444 * method should be called by subclasses that need fading edges and when an 5445 * instance of these subclasses is created programmatically rather than 5446 * being inflated from XML. This method is automatically called when the XML 5447 * is inflated. 5448 * </p> 5449 * 5450 * @param a the styled attributes set to initialize the fading edges from 5451 * 5452 * @removed 5453 */ 5454 protected void initializeFadingEdge(TypedArray a) { 5455 // This method probably shouldn't have been included in the SDK to begin with. 5456 // It relies on 'a' having been initialized using an attribute filter array that is 5457 // not publicly available to the SDK. The old method has been renamed 5458 // to initializeFadingEdgeInternal and hidden for framework use only; 5459 // this one initializes using defaults to make it safe to call for apps. 5460 5461 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5462 5463 initializeFadingEdgeInternal(arr); 5464 5465 arr.recycle(); 5466 } 5467 5468 /** 5469 * <p> 5470 * Initializes the fading edges from a given set of styled attributes. This 5471 * method should be called by subclasses that need fading edges and when an 5472 * instance of these subclasses is created programmatically rather than 5473 * being inflated from XML. This method is automatically called when the XML 5474 * is inflated. 5475 * </p> 5476 * 5477 * @param a the styled attributes set to initialize the fading edges from 5478 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 5479 */ 5480 protected void initializeFadingEdgeInternal(TypedArray a) { 5481 initScrollCache(); 5482 5483 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 5484 R.styleable.View_fadingEdgeLength, 5485 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 5486 } 5487 5488 /** 5489 * Returns the size of the vertical faded edges used to indicate that more 5490 * content in this view is visible. 5491 * 5492 * @return The size in pixels of the vertical faded edge or 0 if vertical 5493 * faded edges are not enabled for this view. 5494 * @attr ref android.R.styleable#View_fadingEdgeLength 5495 */ 5496 public int getVerticalFadingEdgeLength() { 5497 if (isVerticalFadingEdgeEnabled()) { 5498 ScrollabilityCache cache = mScrollCache; 5499 if (cache != null) { 5500 return cache.fadingEdgeLength; 5501 } 5502 } 5503 return 0; 5504 } 5505 5506 /** 5507 * Set the size of the faded edge used to indicate that more content in this 5508 * view is available. Will not change whether the fading edge is enabled; use 5509 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 5510 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 5511 * for the vertical or horizontal fading edges. 5512 * 5513 * @param length The size in pixels of the faded edge used to indicate that more 5514 * content in this view is visible. 5515 */ 5516 public void setFadingEdgeLength(int length) { 5517 initScrollCache(); 5518 mScrollCache.fadingEdgeLength = length; 5519 } 5520 5521 /** 5522 * Returns the size of the horizontal faded edges used to indicate that more 5523 * content in this view is visible. 5524 * 5525 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 5526 * faded edges are not enabled for this view. 5527 * @attr ref android.R.styleable#View_fadingEdgeLength 5528 */ 5529 public int getHorizontalFadingEdgeLength() { 5530 if (isHorizontalFadingEdgeEnabled()) { 5531 ScrollabilityCache cache = mScrollCache; 5532 if (cache != null) { 5533 return cache.fadingEdgeLength; 5534 } 5535 } 5536 return 0; 5537 } 5538 5539 /** 5540 * Returns the width of the vertical scrollbar. 5541 * 5542 * @return The width in pixels of the vertical scrollbar or 0 if there 5543 * is no vertical scrollbar. 5544 */ 5545 public int getVerticalScrollbarWidth() { 5546 ScrollabilityCache cache = mScrollCache; 5547 if (cache != null) { 5548 ScrollBarDrawable scrollBar = cache.scrollBar; 5549 if (scrollBar != null) { 5550 int size = scrollBar.getSize(true); 5551 if (size <= 0) { 5552 size = cache.scrollBarSize; 5553 } 5554 return size; 5555 } 5556 return 0; 5557 } 5558 return 0; 5559 } 5560 5561 /** 5562 * Returns the height of the horizontal scrollbar. 5563 * 5564 * @return The height in pixels of the horizontal scrollbar or 0 if 5565 * there is no horizontal scrollbar. 5566 */ 5567 protected int getHorizontalScrollbarHeight() { 5568 ScrollabilityCache cache = mScrollCache; 5569 if (cache != null) { 5570 ScrollBarDrawable scrollBar = cache.scrollBar; 5571 if (scrollBar != null) { 5572 int size = scrollBar.getSize(false); 5573 if (size <= 0) { 5574 size = cache.scrollBarSize; 5575 } 5576 return size; 5577 } 5578 return 0; 5579 } 5580 return 0; 5581 } 5582 5583 /** 5584 * <p> 5585 * Initializes the scrollbars from a given set of styled attributes. This 5586 * method should be called by subclasses that need scrollbars and when an 5587 * instance of these subclasses is created programmatically rather than 5588 * being inflated from XML. This method is automatically called when the XML 5589 * is inflated. 5590 * </p> 5591 * 5592 * @param a the styled attributes set to initialize the scrollbars from 5593 * 5594 * @removed 5595 */ 5596 protected void initializeScrollbars(TypedArray a) { 5597 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5598 // using the View filter array which is not available to the SDK. As such, internal 5599 // framework usage now uses initializeScrollbarsInternal and we grab a default 5600 // TypedArray with the right filter instead here. 5601 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5602 5603 initializeScrollbarsInternal(arr); 5604 5605 // We ignored the method parameter. Recycle the one we actually did use. 5606 arr.recycle(); 5607 } 5608 5609 /** 5610 * <p> 5611 * Initializes the scrollbars from a given set of styled attributes. This 5612 * method should be called by subclasses that need scrollbars and when an 5613 * instance of these subclasses is created programmatically rather than 5614 * being inflated from XML. This method is automatically called when the XML 5615 * is inflated. 5616 * </p> 5617 * 5618 * @param a the styled attributes set to initialize the scrollbars from 5619 * @hide 5620 */ 5621 protected void initializeScrollbarsInternal(TypedArray a) { 5622 initScrollCache(); 5623 5624 final ScrollabilityCache scrollabilityCache = mScrollCache; 5625 5626 if (scrollabilityCache.scrollBar == null) { 5627 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5628 scrollabilityCache.scrollBar.setState(getDrawableState()); 5629 scrollabilityCache.scrollBar.setCallback(this); 5630 } 5631 5632 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5633 5634 if (!fadeScrollbars) { 5635 scrollabilityCache.state = ScrollabilityCache.ON; 5636 } 5637 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5638 5639 5640 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5641 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5642 .getScrollBarFadeDuration()); 5643 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5644 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5645 ViewConfiguration.getScrollDefaultDelay()); 5646 5647 5648 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5649 com.android.internal.R.styleable.View_scrollbarSize, 5650 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5651 5652 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5653 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5654 5655 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5656 if (thumb != null) { 5657 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5658 } 5659 5660 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5661 false); 5662 if (alwaysDraw) { 5663 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5664 } 5665 5666 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5667 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5668 5669 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5670 if (thumb != null) { 5671 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5672 } 5673 5674 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5675 false); 5676 if (alwaysDraw) { 5677 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5678 } 5679 5680 // Apply layout direction to the new Drawables if needed 5681 final int layoutDirection = getLayoutDirection(); 5682 if (track != null) { 5683 track.setLayoutDirection(layoutDirection); 5684 } 5685 if (thumb != null) { 5686 thumb.setLayoutDirection(layoutDirection); 5687 } 5688 5689 // Re-apply user/background padding so that scrollbar(s) get added 5690 resolvePadding(); 5691 } 5692 5693 private void initializeScrollIndicatorsInternal() { 5694 // Some day maybe we'll break this into top/left/start/etc. and let the 5695 // client control it. Until then, you can have any scroll indicator you 5696 // want as long as it's a 1dp foreground-colored rectangle. 5697 if (mScrollIndicatorDrawable == null) { 5698 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5699 } 5700 } 5701 5702 /** 5703 * <p> 5704 * Initalizes the scrollability cache if necessary. 5705 * </p> 5706 */ 5707 private void initScrollCache() { 5708 if (mScrollCache == null) { 5709 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5710 } 5711 } 5712 5713 private ScrollabilityCache getScrollCache() { 5714 initScrollCache(); 5715 return mScrollCache; 5716 } 5717 5718 /** 5719 * Set the position of the vertical scroll bar. Should be one of 5720 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5721 * {@link #SCROLLBAR_POSITION_RIGHT}. 5722 * 5723 * @param position Where the vertical scroll bar should be positioned. 5724 */ 5725 public void setVerticalScrollbarPosition(int position) { 5726 if (mVerticalScrollbarPosition != position) { 5727 mVerticalScrollbarPosition = position; 5728 computeOpaqueFlags(); 5729 resolvePadding(); 5730 } 5731 } 5732 5733 /** 5734 * @return The position where the vertical scroll bar will show, if applicable. 5735 * @see #setVerticalScrollbarPosition(int) 5736 */ 5737 public int getVerticalScrollbarPosition() { 5738 return mVerticalScrollbarPosition; 5739 } 5740 5741 boolean isOnScrollbar(float x, float y) { 5742 if (mScrollCache == null) { 5743 return false; 5744 } 5745 x += getScrollX(); 5746 y += getScrollY(); 5747 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5748 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5749 getVerticalScrollBarBounds(null, touchBounds); 5750 if (touchBounds.contains((int) x, (int) y)) { 5751 return true; 5752 } 5753 } 5754 if (isHorizontalScrollBarEnabled()) { 5755 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5756 getHorizontalScrollBarBounds(null, touchBounds); 5757 if (touchBounds.contains((int) x, (int) y)) { 5758 return true; 5759 } 5760 } 5761 return false; 5762 } 5763 5764 boolean isOnScrollbarThumb(float x, float y) { 5765 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5766 } 5767 5768 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5769 if (mScrollCache == null) { 5770 return false; 5771 } 5772 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5773 x += getScrollX(); 5774 y += getScrollY(); 5775 final Rect bounds = mScrollCache.mScrollBarBounds; 5776 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5777 getVerticalScrollBarBounds(bounds, touchBounds); 5778 final int range = computeVerticalScrollRange(); 5779 final int offset = computeVerticalScrollOffset(); 5780 final int extent = computeVerticalScrollExtent(); 5781 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5782 extent, range); 5783 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5784 extent, range, offset); 5785 final int thumbTop = bounds.top + thumbOffset; 5786 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 5787 if (x >= touchBounds.left && x <= touchBounds.right 5788 && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) { 5789 return true; 5790 } 5791 } 5792 return false; 5793 } 5794 5795 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5796 if (mScrollCache == null) { 5797 return false; 5798 } 5799 if (isHorizontalScrollBarEnabled()) { 5800 x += getScrollX(); 5801 y += getScrollY(); 5802 final Rect bounds = mScrollCache.mScrollBarBounds; 5803 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5804 getHorizontalScrollBarBounds(bounds, touchBounds); 5805 final int range = computeHorizontalScrollRange(); 5806 final int offset = computeHorizontalScrollOffset(); 5807 final int extent = computeHorizontalScrollExtent(); 5808 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5809 extent, range); 5810 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5811 extent, range, offset); 5812 final int thumbLeft = bounds.left + thumbOffset; 5813 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 5814 if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust 5815 && y >= touchBounds.top && y <= touchBounds.bottom) { 5816 return true; 5817 } 5818 } 5819 return false; 5820 } 5821 5822 boolean isDraggingScrollBar() { 5823 return mScrollCache != null 5824 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5825 } 5826 5827 /** 5828 * Sets the state of all scroll indicators. 5829 * <p> 5830 * See {@link #setScrollIndicators(int, int)} for usage information. 5831 * 5832 * @param indicators a bitmask of indicators that should be enabled, or 5833 * {@code 0} to disable all indicators 5834 * @see #setScrollIndicators(int, int) 5835 * @see #getScrollIndicators() 5836 * @attr ref android.R.styleable#View_scrollIndicators 5837 */ 5838 public void setScrollIndicators(@ScrollIndicators int indicators) { 5839 setScrollIndicators(indicators, 5840 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5841 } 5842 5843 /** 5844 * Sets the state of the scroll indicators specified by the mask. To change 5845 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5846 * <p> 5847 * When a scroll indicator is enabled, it will be displayed if the view 5848 * can scroll in the direction of the indicator. 5849 * <p> 5850 * Multiple indicator types may be enabled or disabled by passing the 5851 * logical OR of the desired types. If multiple types are specified, they 5852 * will all be set to the same enabled state. 5853 * <p> 5854 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5855 * 5856 * @param indicators the indicator direction, or the logical OR of multiple 5857 * indicator directions. One or more of: 5858 * <ul> 5859 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5860 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5861 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5862 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5863 * <li>{@link #SCROLL_INDICATOR_START}</li> 5864 * <li>{@link #SCROLL_INDICATOR_END}</li> 5865 * </ul> 5866 * @see #setScrollIndicators(int) 5867 * @see #getScrollIndicators() 5868 * @attr ref android.R.styleable#View_scrollIndicators 5869 */ 5870 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5871 // Shift and sanitize mask. 5872 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5873 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5874 5875 // Shift and mask indicators. 5876 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5877 indicators &= mask; 5878 5879 // Merge with non-masked flags. 5880 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5881 5882 if (mPrivateFlags3 != updatedFlags) { 5883 mPrivateFlags3 = updatedFlags; 5884 5885 if (indicators != 0) { 5886 initializeScrollIndicatorsInternal(); 5887 } 5888 invalidate(); 5889 } 5890 } 5891 5892 /** 5893 * Returns a bitmask representing the enabled scroll indicators. 5894 * <p> 5895 * For example, if the top and left scroll indicators are enabled and all 5896 * other indicators are disabled, the return value will be 5897 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5898 * <p> 5899 * To check whether the bottom scroll indicator is enabled, use the value 5900 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5901 * 5902 * @return a bitmask representing the enabled scroll indicators 5903 */ 5904 @ScrollIndicators 5905 public int getScrollIndicators() { 5906 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5907 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5908 } 5909 5910 ListenerInfo getListenerInfo() { 5911 if (mListenerInfo != null) { 5912 return mListenerInfo; 5913 } 5914 mListenerInfo = new ListenerInfo(); 5915 return mListenerInfo; 5916 } 5917 5918 /** 5919 * Register a callback to be invoked when the scroll X or Y positions of 5920 * this view change. 5921 * <p> 5922 * <b>Note:</b> Some views handle scrolling independently from View and may 5923 * have their own separate listeners for scroll-type events. For example, 5924 * {@link android.widget.ListView ListView} allows clients to register an 5925 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5926 * to listen for changes in list scroll position. 5927 * 5928 * @param l The listener to notify when the scroll X or Y position changes. 5929 * @see android.view.View#getScrollX() 5930 * @see android.view.View#getScrollY() 5931 */ 5932 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5933 getListenerInfo().mOnScrollChangeListener = l; 5934 } 5935 5936 /** 5937 * Register a callback to be invoked when focus of this view changed. 5938 * 5939 * @param l The callback that will run. 5940 */ 5941 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5942 getListenerInfo().mOnFocusChangeListener = l; 5943 } 5944 5945 /** 5946 * Add a listener that will be called when the bounds of the view change due to 5947 * layout processing. 5948 * 5949 * @param listener The listener that will be called when layout bounds change. 5950 */ 5951 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5952 ListenerInfo li = getListenerInfo(); 5953 if (li.mOnLayoutChangeListeners == null) { 5954 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5955 } 5956 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5957 li.mOnLayoutChangeListeners.add(listener); 5958 } 5959 } 5960 5961 /** 5962 * Remove a listener for layout changes. 5963 * 5964 * @param listener The listener for layout bounds change. 5965 */ 5966 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5967 ListenerInfo li = mListenerInfo; 5968 if (li == null || li.mOnLayoutChangeListeners == null) { 5969 return; 5970 } 5971 li.mOnLayoutChangeListeners.remove(listener); 5972 } 5973 5974 /** 5975 * Add a listener for attach state changes. 5976 * 5977 * This listener will be called whenever this view is attached or detached 5978 * from a window. Remove the listener using 5979 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5980 * 5981 * @param listener Listener to attach 5982 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5983 */ 5984 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5985 ListenerInfo li = getListenerInfo(); 5986 if (li.mOnAttachStateChangeListeners == null) { 5987 li.mOnAttachStateChangeListeners 5988 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5989 } 5990 li.mOnAttachStateChangeListeners.add(listener); 5991 } 5992 5993 /** 5994 * Remove a listener for attach state changes. The listener will receive no further 5995 * notification of window attach/detach events. 5996 * 5997 * @param listener Listener to remove 5998 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5999 */ 6000 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 6001 ListenerInfo li = mListenerInfo; 6002 if (li == null || li.mOnAttachStateChangeListeners == null) { 6003 return; 6004 } 6005 li.mOnAttachStateChangeListeners.remove(listener); 6006 } 6007 6008 /** 6009 * Returns the focus-change callback registered for this view. 6010 * 6011 * @return The callback, or null if one is not registered. 6012 */ 6013 public OnFocusChangeListener getOnFocusChangeListener() { 6014 ListenerInfo li = mListenerInfo; 6015 return li != null ? li.mOnFocusChangeListener : null; 6016 } 6017 6018 /** 6019 * Register a callback to be invoked when this view is clicked. If this view is not 6020 * clickable, it becomes clickable. 6021 * 6022 * @param l The callback that will run 6023 * 6024 * @see #setClickable(boolean) 6025 */ 6026 public void setOnClickListener(@Nullable OnClickListener l) { 6027 if (!isClickable()) { 6028 setClickable(true); 6029 } 6030 getListenerInfo().mOnClickListener = l; 6031 } 6032 6033 /** 6034 * Return whether this view has an attached OnClickListener. Returns 6035 * true if there is a listener, false if there is none. 6036 */ 6037 public boolean hasOnClickListeners() { 6038 ListenerInfo li = mListenerInfo; 6039 return (li != null && li.mOnClickListener != null); 6040 } 6041 6042 /** 6043 * Register a callback to be invoked when this view is clicked and held. If this view is not 6044 * long clickable, it becomes long clickable. 6045 * 6046 * @param l The callback that will run 6047 * 6048 * @see #setLongClickable(boolean) 6049 */ 6050 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 6051 if (!isLongClickable()) { 6052 setLongClickable(true); 6053 } 6054 getListenerInfo().mOnLongClickListener = l; 6055 } 6056 6057 /** 6058 * Register a callback to be invoked when this view is context clicked. If the view is not 6059 * context clickable, it becomes context clickable. 6060 * 6061 * @param l The callback that will run 6062 * @see #setContextClickable(boolean) 6063 */ 6064 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 6065 if (!isContextClickable()) { 6066 setContextClickable(true); 6067 } 6068 getListenerInfo().mOnContextClickListener = l; 6069 } 6070 6071 /** 6072 * Register a callback to be invoked when the context menu for this view is 6073 * being built. If this view is not long clickable, it becomes long clickable. 6074 * 6075 * @param l The callback that will run 6076 * 6077 */ 6078 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 6079 if (!isLongClickable()) { 6080 setLongClickable(true); 6081 } 6082 getListenerInfo().mOnCreateContextMenuListener = l; 6083 } 6084 6085 /** 6086 * Set an observer to collect stats for each frame rendered for this view. 6087 * 6088 * @hide 6089 */ 6090 public void addFrameMetricsListener(Window window, 6091 Window.OnFrameMetricsAvailableListener listener, 6092 Handler handler) { 6093 if (mAttachInfo != null) { 6094 if (mAttachInfo.mThreadedRenderer != null) { 6095 if (mFrameMetricsObservers == null) { 6096 mFrameMetricsObservers = new ArrayList<>(); 6097 } 6098 6099 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6100 handler.getLooper(), listener); 6101 mFrameMetricsObservers.add(fmo); 6102 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 6103 } else { 6104 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6105 } 6106 } else { 6107 if (mFrameMetricsObservers == null) { 6108 mFrameMetricsObservers = new ArrayList<>(); 6109 } 6110 6111 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6112 handler.getLooper(), listener); 6113 mFrameMetricsObservers.add(fmo); 6114 } 6115 } 6116 6117 /** 6118 * Remove observer configured to collect frame stats for this view. 6119 * 6120 * @hide 6121 */ 6122 public void removeFrameMetricsListener( 6123 Window.OnFrameMetricsAvailableListener listener) { 6124 ThreadedRenderer renderer = getThreadedRenderer(); 6125 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 6126 if (fmo == null) { 6127 throw new IllegalArgumentException( 6128 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 6129 } 6130 6131 if (mFrameMetricsObservers != null) { 6132 mFrameMetricsObservers.remove(fmo); 6133 if (renderer != null) { 6134 renderer.removeFrameMetricsObserver(fmo); 6135 } 6136 } 6137 } 6138 6139 private void registerPendingFrameMetricsObservers() { 6140 if (mFrameMetricsObservers != null) { 6141 ThreadedRenderer renderer = getThreadedRenderer(); 6142 if (renderer != null) { 6143 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 6144 renderer.addFrameMetricsObserver(fmo); 6145 } 6146 } else { 6147 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6148 } 6149 } 6150 } 6151 6152 private FrameMetricsObserver findFrameMetricsObserver( 6153 Window.OnFrameMetricsAvailableListener listener) { 6154 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 6155 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 6156 if (observer.mListener == listener) { 6157 return observer; 6158 } 6159 } 6160 6161 return null; 6162 } 6163 6164 /** 6165 * Call this view's OnClickListener, if it is defined. Performs all normal 6166 * actions associated with clicking: reporting accessibility event, playing 6167 * a sound, etc. 6168 * 6169 * @return True there was an assigned OnClickListener that was called, false 6170 * otherwise is returned. 6171 */ 6172 public boolean performClick() { 6173 final boolean result; 6174 final ListenerInfo li = mListenerInfo; 6175 if (li != null && li.mOnClickListener != null) { 6176 playSoundEffect(SoundEffectConstants.CLICK); 6177 li.mOnClickListener.onClick(this); 6178 result = true; 6179 } else { 6180 result = false; 6181 } 6182 6183 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 6184 6185 notifyEnterOrExitForAutoFillIfNeeded(true); 6186 6187 return result; 6188 } 6189 6190 /** 6191 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 6192 * this only calls the listener, and does not do any associated clicking 6193 * actions like reporting an accessibility event. 6194 * 6195 * @return True there was an assigned OnClickListener that was called, false 6196 * otherwise is returned. 6197 */ 6198 public boolean callOnClick() { 6199 ListenerInfo li = mListenerInfo; 6200 if (li != null && li.mOnClickListener != null) { 6201 li.mOnClickListener.onClick(this); 6202 return true; 6203 } 6204 return false; 6205 } 6206 6207 /** 6208 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6209 * context menu if the OnLongClickListener did not consume the event. 6210 * 6211 * @return {@code true} if one of the above receivers consumed the event, 6212 * {@code false} otherwise 6213 */ 6214 public boolean performLongClick() { 6215 return performLongClickInternal(mLongClickX, mLongClickY); 6216 } 6217 6218 /** 6219 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6220 * context menu if the OnLongClickListener did not consume the event, 6221 * anchoring it to an (x,y) coordinate. 6222 * 6223 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6224 * to disable anchoring 6225 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6226 * to disable anchoring 6227 * @return {@code true} if one of the above receivers consumed the event, 6228 * {@code false} otherwise 6229 */ 6230 public boolean performLongClick(float x, float y) { 6231 mLongClickX = x; 6232 mLongClickY = y; 6233 final boolean handled = performLongClick(); 6234 mLongClickX = Float.NaN; 6235 mLongClickY = Float.NaN; 6236 return handled; 6237 } 6238 6239 /** 6240 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6241 * context menu if the OnLongClickListener did not consume the event, 6242 * optionally anchoring it to an (x,y) coordinate. 6243 * 6244 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6245 * to disable anchoring 6246 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6247 * to disable anchoring 6248 * @return {@code true} if one of the above receivers consumed the event, 6249 * {@code false} otherwise 6250 */ 6251 private boolean performLongClickInternal(float x, float y) { 6252 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 6253 6254 boolean handled = false; 6255 final ListenerInfo li = mListenerInfo; 6256 if (li != null && li.mOnLongClickListener != null) { 6257 handled = li.mOnLongClickListener.onLongClick(View.this); 6258 } 6259 if (!handled) { 6260 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 6261 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 6262 } 6263 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 6264 if (!handled) { 6265 handled = showLongClickTooltip((int) x, (int) y); 6266 } 6267 } 6268 if (handled) { 6269 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 6270 } 6271 return handled; 6272 } 6273 6274 /** 6275 * Call this view's OnContextClickListener, if it is defined. 6276 * 6277 * @param x the x coordinate of the context click 6278 * @param y the y coordinate of the context click 6279 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6280 * otherwise. 6281 */ 6282 public boolean performContextClick(float x, float y) { 6283 return performContextClick(); 6284 } 6285 6286 /** 6287 * Call this view's OnContextClickListener, if it is defined. 6288 * 6289 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6290 * otherwise. 6291 */ 6292 public boolean performContextClick() { 6293 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 6294 6295 boolean handled = false; 6296 ListenerInfo li = mListenerInfo; 6297 if (li != null && li.mOnContextClickListener != null) { 6298 handled = li.mOnContextClickListener.onContextClick(View.this); 6299 } 6300 if (handled) { 6301 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 6302 } 6303 return handled; 6304 } 6305 6306 /** 6307 * Performs button-related actions during a touch down event. 6308 * 6309 * @param event The event. 6310 * @return True if the down was consumed. 6311 * 6312 * @hide 6313 */ 6314 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 6315 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 6316 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 6317 showContextMenu(event.getX(), event.getY()); 6318 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 6319 return true; 6320 } 6321 return false; 6322 } 6323 6324 /** 6325 * Shows the context menu for this view. 6326 * 6327 * @return {@code true} if the context menu was shown, {@code false} 6328 * otherwise 6329 * @see #showContextMenu(float, float) 6330 */ 6331 public boolean showContextMenu() { 6332 return getParent().showContextMenuForChild(this); 6333 } 6334 6335 /** 6336 * Shows the context menu for this view anchored to the specified 6337 * view-relative coordinate. 6338 * 6339 * @param x the X coordinate in pixels relative to the view to which the 6340 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6341 * @param y the Y coordinate in pixels relative to the view to which the 6342 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6343 * @return {@code true} if the context menu was shown, {@code false} 6344 * otherwise 6345 */ 6346 public boolean showContextMenu(float x, float y) { 6347 return getParent().showContextMenuForChild(this, x, y); 6348 } 6349 6350 /** 6351 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 6352 * 6353 * @param callback Callback that will control the lifecycle of the action mode 6354 * @return The new action mode if it is started, null otherwise 6355 * 6356 * @see ActionMode 6357 * @see #startActionMode(android.view.ActionMode.Callback, int) 6358 */ 6359 public ActionMode startActionMode(ActionMode.Callback callback) { 6360 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 6361 } 6362 6363 /** 6364 * Start an action mode with the given type. 6365 * 6366 * @param callback Callback that will control the lifecycle of the action mode 6367 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 6368 * @return The new action mode if it is started, null otherwise 6369 * 6370 * @see ActionMode 6371 */ 6372 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 6373 ViewParent parent = getParent(); 6374 if (parent == null) return null; 6375 try { 6376 return parent.startActionModeForChild(this, callback, type); 6377 } catch (AbstractMethodError ame) { 6378 // Older implementations of custom views might not implement this. 6379 return parent.startActionModeForChild(this, callback); 6380 } 6381 } 6382 6383 /** 6384 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 6385 * Context, creating a unique View identifier to retrieve the result. 6386 * 6387 * @param intent The Intent to be started. 6388 * @param requestCode The request code to use. 6389 * @hide 6390 */ 6391 public void startActivityForResult(Intent intent, int requestCode) { 6392 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 6393 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 6394 } 6395 6396 /** 6397 * If this View corresponds to the calling who, dispatches the activity result. 6398 * @param who The identifier for the targeted View to receive the result. 6399 * @param requestCode The integer request code originally supplied to 6400 * startActivityForResult(), allowing you to identify who this 6401 * result came from. 6402 * @param resultCode The integer result code returned by the child activity 6403 * through its setResult(). 6404 * @param data An Intent, which can return result data to the caller 6405 * (various data can be attached to Intent "extras"). 6406 * @return {@code true} if the activity result was dispatched. 6407 * @hide 6408 */ 6409 public boolean dispatchActivityResult( 6410 String who, int requestCode, int resultCode, Intent data) { 6411 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 6412 onActivityResult(requestCode, resultCode, data); 6413 mStartActivityRequestWho = null; 6414 return true; 6415 } 6416 return false; 6417 } 6418 6419 /** 6420 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 6421 * 6422 * @param requestCode The integer request code originally supplied to 6423 * startActivityForResult(), allowing you to identify who this 6424 * result came from. 6425 * @param resultCode The integer result code returned by the child activity 6426 * through its setResult(). 6427 * @param data An Intent, which can return result data to the caller 6428 * (various data can be attached to Intent "extras"). 6429 * @hide 6430 */ 6431 public void onActivityResult(int requestCode, int resultCode, Intent data) { 6432 // Do nothing. 6433 } 6434 6435 /** 6436 * Register a callback to be invoked when a hardware key is pressed in this view. 6437 * Key presses in software input methods will generally not trigger the methods of 6438 * this listener. 6439 * @param l the key listener to attach to this view 6440 */ 6441 public void setOnKeyListener(OnKeyListener l) { 6442 getListenerInfo().mOnKeyListener = l; 6443 } 6444 6445 /** 6446 * Register a callback to be invoked when a touch event is sent to this view. 6447 * @param l the touch listener to attach to this view 6448 */ 6449 public void setOnTouchListener(OnTouchListener l) { 6450 getListenerInfo().mOnTouchListener = l; 6451 } 6452 6453 /** 6454 * Register a callback to be invoked when a generic motion event is sent to this view. 6455 * @param l the generic motion listener to attach to this view 6456 */ 6457 public void setOnGenericMotionListener(OnGenericMotionListener l) { 6458 getListenerInfo().mOnGenericMotionListener = l; 6459 } 6460 6461 /** 6462 * Register a callback to be invoked when a hover event is sent to this view. 6463 * @param l the hover listener to attach to this view 6464 */ 6465 public void setOnHoverListener(OnHoverListener l) { 6466 getListenerInfo().mOnHoverListener = l; 6467 } 6468 6469 /** 6470 * Register a drag event listener callback object for this View. The parameter is 6471 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 6472 * View, the system calls the 6473 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 6474 * @param l An implementation of {@link android.view.View.OnDragListener}. 6475 */ 6476 public void setOnDragListener(OnDragListener l) { 6477 getListenerInfo().mOnDragListener = l; 6478 } 6479 6480 /** 6481 * Give this view focus. This will cause 6482 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 6483 * 6484 * Note: this does not check whether this {@link View} should get focus, it just 6485 * gives it focus no matter what. It should only be called internally by framework 6486 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 6487 * 6488 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 6489 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 6490 * focus moved when requestFocus() is called. It may not always 6491 * apply, in which case use the default View.FOCUS_DOWN. 6492 * @param previouslyFocusedRect The rectangle of the view that had focus 6493 * prior in this View's coordinate system. 6494 */ 6495 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 6496 if (DBG) { 6497 System.out.println(this + " requestFocus()"); 6498 } 6499 6500 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 6501 mPrivateFlags |= PFLAG_FOCUSED; 6502 6503 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 6504 6505 if (mParent != null) { 6506 mParent.requestChildFocus(this, this); 6507 updateFocusedInCluster(oldFocus, direction); 6508 } 6509 6510 if (mAttachInfo != null) { 6511 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 6512 } 6513 6514 onFocusChanged(true, direction, previouslyFocusedRect); 6515 refreshDrawableState(); 6516 } 6517 } 6518 6519 /** 6520 * Sets this view's preference for reveal behavior when it gains focus. 6521 * 6522 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 6523 * this view would prefer to be brought fully into view when it gains focus. 6524 * For example, a text field that a user is meant to type into. Other views such 6525 * as scrolling containers may prefer to opt-out of this behavior.</p> 6526 * 6527 * <p>The default value for views is true, though subclasses may change this 6528 * based on their preferred behavior.</p> 6529 * 6530 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 6531 * 6532 * @see #getRevealOnFocusHint() 6533 */ 6534 public final void setRevealOnFocusHint(boolean revealOnFocus) { 6535 if (revealOnFocus) { 6536 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 6537 } else { 6538 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 6539 } 6540 } 6541 6542 /** 6543 * Returns this view's preference for reveal behavior when it gains focus. 6544 * 6545 * <p>When this method returns true for a child view requesting focus, ancestor 6546 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 6547 * should make a best effort to make the newly focused child fully visible to the user. 6548 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 6549 * other properties affecting visibility to the user as part of the focus change.</p> 6550 * 6551 * @return true if this view would prefer to become fully visible when it gains focus, 6552 * false if it would prefer not to disrupt scroll positioning 6553 * 6554 * @see #setRevealOnFocusHint(boolean) 6555 */ 6556 public final boolean getRevealOnFocusHint() { 6557 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 6558 } 6559 6560 /** 6561 * Populates <code>outRect</code> with the hotspot bounds. By default, 6562 * the hotspot bounds are identical to the screen bounds. 6563 * 6564 * @param outRect rect to populate with hotspot bounds 6565 * @hide Only for internal use by views and widgets. 6566 */ 6567 public void getHotspotBounds(Rect outRect) { 6568 final Drawable background = getBackground(); 6569 if (background != null) { 6570 background.getHotspotBounds(outRect); 6571 } else { 6572 getBoundsOnScreen(outRect); 6573 } 6574 } 6575 6576 /** 6577 * Request that a rectangle of this view be visible on the screen, 6578 * scrolling if necessary just enough. 6579 * 6580 * <p>A View should call this if it maintains some notion of which part 6581 * of its content is interesting. For example, a text editing view 6582 * should call this when its cursor moves. 6583 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6584 * It should not be affected by which part of the View is currently visible or its scroll 6585 * position. 6586 * 6587 * @param rectangle The rectangle in the View's content coordinate space 6588 * @return Whether any parent scrolled. 6589 */ 6590 public boolean requestRectangleOnScreen(Rect rectangle) { 6591 return requestRectangleOnScreen(rectangle, false); 6592 } 6593 6594 /** 6595 * Request that a rectangle of this view be visible on the screen, 6596 * scrolling if necessary just enough. 6597 * 6598 * <p>A View should call this if it maintains some notion of which part 6599 * of its content is interesting. For example, a text editing view 6600 * should call this when its cursor moves. 6601 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6602 * It should not be affected by which part of the View is currently visible or its scroll 6603 * position. 6604 * <p>When <code>immediate</code> is set to true, scrolling will not be 6605 * animated. 6606 * 6607 * @param rectangle The rectangle in the View's content coordinate space 6608 * @param immediate True to forbid animated scrolling, false otherwise 6609 * @return Whether any parent scrolled. 6610 */ 6611 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 6612 if (mParent == null) { 6613 return false; 6614 } 6615 6616 View child = this; 6617 6618 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6619 position.set(rectangle); 6620 6621 ViewParent parent = mParent; 6622 boolean scrolled = false; 6623 while (parent != null) { 6624 rectangle.set((int) position.left, (int) position.top, 6625 (int) position.right, (int) position.bottom); 6626 6627 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6628 6629 if (!(parent instanceof View)) { 6630 break; 6631 } 6632 6633 // move it from child's content coordinate space to parent's content coordinate space 6634 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6635 6636 child = (View) parent; 6637 parent = child.getParent(); 6638 } 6639 6640 return scrolled; 6641 } 6642 6643 /** 6644 * Called when this view wants to give up focus. If focus is cleared 6645 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6646 * <p> 6647 * <strong>Note:</strong> When a View clears focus the framework is trying 6648 * to give focus to the first focusable View from the top. Hence, if this 6649 * View is the first from the top that can take focus, then all callbacks 6650 * related to clearing focus will be invoked after which the framework will 6651 * give focus to this view. 6652 * </p> 6653 */ 6654 public void clearFocus() { 6655 if (DBG) { 6656 System.out.println(this + " clearFocus()"); 6657 } 6658 6659 clearFocusInternal(null, true, true); 6660 } 6661 6662 /** 6663 * Clears focus from the view, optionally propagating the change up through 6664 * the parent hierarchy and requesting that the root view place new focus. 6665 * 6666 * @param propagate whether to propagate the change up through the parent 6667 * hierarchy 6668 * @param refocus when propagate is true, specifies whether to request the 6669 * root view place new focus 6670 */ 6671 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6672 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6673 mPrivateFlags &= ~PFLAG_FOCUSED; 6674 6675 if (propagate && mParent != null) { 6676 mParent.clearChildFocus(this); 6677 } 6678 6679 onFocusChanged(false, 0, null); 6680 refreshDrawableState(); 6681 6682 if (propagate && (!refocus || !rootViewRequestFocus())) { 6683 notifyGlobalFocusCleared(this); 6684 } 6685 } 6686 } 6687 6688 void notifyGlobalFocusCleared(View oldFocus) { 6689 if (oldFocus != null && mAttachInfo != null) { 6690 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6691 } 6692 } 6693 6694 boolean rootViewRequestFocus() { 6695 final View root = getRootView(); 6696 return root != null && root.requestFocus(); 6697 } 6698 6699 /** 6700 * Called internally by the view system when a new view is getting focus. 6701 * This is what clears the old focus. 6702 * <p> 6703 * <b>NOTE:</b> The parent view's focused child must be updated manually 6704 * after calling this method. Otherwise, the view hierarchy may be left in 6705 * an inconstent state. 6706 */ 6707 void unFocus(View focused) { 6708 if (DBG) { 6709 System.out.println(this + " unFocus()"); 6710 } 6711 6712 clearFocusInternal(focused, false, false); 6713 } 6714 6715 /** 6716 * Returns true if this view has focus itself, or is the ancestor of the 6717 * view that has focus. 6718 * 6719 * @return True if this view has or contains focus, false otherwise. 6720 */ 6721 @ViewDebug.ExportedProperty(category = "focus") 6722 public boolean hasFocus() { 6723 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6724 } 6725 6726 /** 6727 * Returns true if this view is focusable or if it contains a reachable View 6728 * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()" 6729 * is a view whose parents do not block descendants focus. 6730 * Only {@link #VISIBLE} views are considered focusable. 6731 * 6732 * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable 6733 * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}. 6734 * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of 6735 * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return 6736 * {@code false} for views not explicitly marked as focusable. 6737 * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O} 6738 * behavior.</p> 6739 * 6740 * @return {@code true} if the view is focusable or if the view contains a focusable 6741 * view, {@code false} otherwise 6742 * 6743 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6744 * @see ViewGroup#getTouchscreenBlocksFocus() 6745 * @see #hasExplicitFocusable() 6746 */ 6747 public boolean hasFocusable() { 6748 return hasFocusable(!sHasFocusableExcludeAutoFocusable, false); 6749 } 6750 6751 /** 6752 * Returns true if this view is focusable or if it contains a reachable View 6753 * for which {@link #hasExplicitFocusable()} returns {@code true}. 6754 * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus. 6755 * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return 6756 * {@link #FOCUSABLE} are considered focusable. 6757 * 6758 * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of 6759 * {@link #hasFocusable()} in that only views explicitly set focusable will cause 6760 * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves 6761 * to focusable will not.</p> 6762 * 6763 * @return {@code true} if the view is focusable or if the view contains a focusable 6764 * view, {@code false} otherwise 6765 * 6766 * @see #hasFocusable() 6767 */ 6768 public boolean hasExplicitFocusable() { 6769 return hasFocusable(false, true); 6770 } 6771 6772 boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) { 6773 if (!isFocusableInTouchMode()) { 6774 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6775 final ViewGroup g = (ViewGroup) p; 6776 if (g.shouldBlockFocusForTouchscreen()) { 6777 return false; 6778 } 6779 } 6780 } 6781 6782 // Invisible and gone views are never focusable. 6783 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6784 return false; 6785 } 6786 6787 // Only use effective focusable value when allowed. 6788 if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) { 6789 return true; 6790 } 6791 6792 return false; 6793 } 6794 6795 /** 6796 * Called by the view system when the focus state of this view changes. 6797 * When the focus change event is caused by directional navigation, direction 6798 * and previouslyFocusedRect provide insight into where the focus is coming from. 6799 * When overriding, be sure to call up through to the super class so that 6800 * the standard focus handling will occur. 6801 * 6802 * @param gainFocus True if the View has focus; false otherwise. 6803 * @param direction The direction focus has moved when requestFocus() 6804 * is called to give this view focus. Values are 6805 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6806 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6807 * It may not always apply, in which case use the default. 6808 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6809 * system, of the previously focused view. If applicable, this will be 6810 * passed in as finer grained information about where the focus is coming 6811 * from (in addition to direction). Will be <code>null</code> otherwise. 6812 */ 6813 @CallSuper 6814 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6815 @Nullable Rect previouslyFocusedRect) { 6816 if (gainFocus) { 6817 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6818 } else { 6819 notifyViewAccessibilityStateChangedIfNeeded( 6820 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6821 } 6822 6823 // Here we check whether we still need the default focus highlight, and switch it on/off. 6824 switchDefaultFocusHighlight(); 6825 6826 InputMethodManager imm = InputMethodManager.peekInstance(); 6827 if (!gainFocus) { 6828 if (isPressed()) { 6829 setPressed(false); 6830 } 6831 if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6832 imm.focusOut(this); 6833 } 6834 onFocusLost(); 6835 } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6836 imm.focusIn(this); 6837 } 6838 6839 invalidate(true); 6840 ListenerInfo li = mListenerInfo; 6841 if (li != null && li.mOnFocusChangeListener != null) { 6842 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6843 } 6844 6845 if (mAttachInfo != null) { 6846 mAttachInfo.mKeyDispatchState.reset(this); 6847 } 6848 6849 notifyEnterOrExitForAutoFillIfNeeded(gainFocus); 6850 } 6851 6852 private void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) { 6853 if (isAutofillable() && isAttachedToWindow()) { 6854 AutofillManager afm = getAutofillManager(); 6855 if (afm != null) { 6856 if (enter && hasWindowFocus() && isFocused()) { 6857 // We have not been laid out yet, hence cannot evaluate 6858 // whether this view is visible to the user, we will do 6859 // the evaluation once layout is complete. 6860 if (!isLaidOut()) { 6861 mPrivateFlags3 |= PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT; 6862 } else if (isVisibleToUser()) { 6863 afm.notifyViewEntered(this); 6864 } 6865 } else if (!hasWindowFocus() || !isFocused()) { 6866 afm.notifyViewExited(this); 6867 } 6868 } 6869 } 6870 } 6871 6872 /** 6873 * Sends an accessibility event of the given type. If accessibility is 6874 * not enabled this method has no effect. The default implementation calls 6875 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6876 * to populate information about the event source (this View), then calls 6877 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6878 * populate the text content of the event source including its descendants, 6879 * and last calls 6880 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6881 * on its parent to request sending of the event to interested parties. 6882 * <p> 6883 * If an {@link AccessibilityDelegate} has been specified via calling 6884 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6885 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6886 * responsible for handling this call. 6887 * </p> 6888 * 6889 * @param eventType The type of the event to send, as defined by several types from 6890 * {@link android.view.accessibility.AccessibilityEvent}, such as 6891 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6892 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6893 * 6894 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6895 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6896 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6897 * @see AccessibilityDelegate 6898 */ 6899 public void sendAccessibilityEvent(int eventType) { 6900 if (mAccessibilityDelegate != null) { 6901 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6902 } else { 6903 sendAccessibilityEventInternal(eventType); 6904 } 6905 } 6906 6907 /** 6908 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6909 * {@link AccessibilityEvent} to make an announcement which is related to some 6910 * sort of a context change for which none of the events representing UI transitions 6911 * is a good fit. For example, announcing a new page in a book. If accessibility 6912 * is not enabled this method does nothing. 6913 * 6914 * @param text The announcement text. 6915 */ 6916 public void announceForAccessibility(CharSequence text) { 6917 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6918 AccessibilityEvent event = AccessibilityEvent.obtain( 6919 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6920 onInitializeAccessibilityEvent(event); 6921 event.getText().add(text); 6922 event.setContentDescription(null); 6923 mParent.requestSendAccessibilityEvent(this, event); 6924 } 6925 } 6926 6927 /** 6928 * @see #sendAccessibilityEvent(int) 6929 * 6930 * Note: Called from the default {@link AccessibilityDelegate}. 6931 * 6932 * @hide 6933 */ 6934 public void sendAccessibilityEventInternal(int eventType) { 6935 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6936 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6937 } 6938 } 6939 6940 /** 6941 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6942 * takes as an argument an empty {@link AccessibilityEvent} and does not 6943 * perform a check whether accessibility is enabled. 6944 * <p> 6945 * If an {@link AccessibilityDelegate} has been specified via calling 6946 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6947 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6948 * is responsible for handling this call. 6949 * </p> 6950 * 6951 * @param event The event to send. 6952 * 6953 * @see #sendAccessibilityEvent(int) 6954 */ 6955 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6956 if (mAccessibilityDelegate != null) { 6957 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6958 } else { 6959 sendAccessibilityEventUncheckedInternal(event); 6960 } 6961 } 6962 6963 /** 6964 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6965 * 6966 * Note: Called from the default {@link AccessibilityDelegate}. 6967 * 6968 * @hide 6969 */ 6970 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6971 if (!isShown()) { 6972 return; 6973 } 6974 onInitializeAccessibilityEvent(event); 6975 // Only a subset of accessibility events populates text content. 6976 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6977 dispatchPopulateAccessibilityEvent(event); 6978 } 6979 // In the beginning we called #isShown(), so we know that getParent() is not null. 6980 ViewParent parent = getParent(); 6981 if (parent != null) { 6982 getParent().requestSendAccessibilityEvent(this, event); 6983 } 6984 } 6985 6986 /** 6987 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6988 * to its children for adding their text content to the event. Note that the 6989 * event text is populated in a separate dispatch path since we add to the 6990 * event not only the text of the source but also the text of all its descendants. 6991 * A typical implementation will call 6992 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6993 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6994 * on each child. Override this method if custom population of the event text 6995 * content is required. 6996 * <p> 6997 * If an {@link AccessibilityDelegate} has been specified via calling 6998 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6999 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 7000 * is responsible for handling this call. 7001 * </p> 7002 * <p> 7003 * <em>Note:</em> Accessibility events of certain types are not dispatched for 7004 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 7005 * </p> 7006 * 7007 * @param event The event. 7008 * 7009 * @return True if the event population was completed. 7010 */ 7011 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 7012 if (mAccessibilityDelegate != null) { 7013 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 7014 } else { 7015 return dispatchPopulateAccessibilityEventInternal(event); 7016 } 7017 } 7018 7019 /** 7020 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7021 * 7022 * Note: Called from the default {@link AccessibilityDelegate}. 7023 * 7024 * @hide 7025 */ 7026 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7027 onPopulateAccessibilityEvent(event); 7028 return false; 7029 } 7030 7031 /** 7032 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 7033 * giving a chance to this View to populate the accessibility event with its 7034 * text content. While this method is free to modify event 7035 * attributes other than text content, doing so should normally be performed in 7036 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 7037 * <p> 7038 * Example: Adding formatted date string to an accessibility event in addition 7039 * to the text added by the super implementation: 7040 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7041 * super.onPopulateAccessibilityEvent(event); 7042 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 7043 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 7044 * mCurrentDate.getTimeInMillis(), flags); 7045 * event.getText().add(selectedDateUtterance); 7046 * }</pre> 7047 * <p> 7048 * If an {@link AccessibilityDelegate} has been specified via calling 7049 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7050 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 7051 * is responsible for handling this call. 7052 * </p> 7053 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7054 * information to the event, in case the default implementation has basic information to add. 7055 * </p> 7056 * 7057 * @param event The accessibility event which to populate. 7058 * 7059 * @see #sendAccessibilityEvent(int) 7060 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7061 */ 7062 @CallSuper 7063 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7064 if (mAccessibilityDelegate != null) { 7065 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 7066 } else { 7067 onPopulateAccessibilityEventInternal(event); 7068 } 7069 } 7070 7071 /** 7072 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 7073 * 7074 * Note: Called from the default {@link AccessibilityDelegate}. 7075 * 7076 * @hide 7077 */ 7078 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7079 } 7080 7081 /** 7082 * Initializes an {@link AccessibilityEvent} with information about 7083 * this View which is the event source. In other words, the source of 7084 * an accessibility event is the view whose state change triggered firing 7085 * the event. 7086 * <p> 7087 * Example: Setting the password property of an event in addition 7088 * to properties set by the super implementation: 7089 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7090 * super.onInitializeAccessibilityEvent(event); 7091 * event.setPassword(true); 7092 * }</pre> 7093 * <p> 7094 * If an {@link AccessibilityDelegate} has been specified via calling 7095 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7096 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 7097 * is responsible for handling this call. 7098 * </p> 7099 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7100 * information to the event, in case the default implementation has basic information to add. 7101 * </p> 7102 * @param event The event to initialize. 7103 * 7104 * @see #sendAccessibilityEvent(int) 7105 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7106 */ 7107 @CallSuper 7108 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7109 if (mAccessibilityDelegate != null) { 7110 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 7111 } else { 7112 onInitializeAccessibilityEventInternal(event); 7113 } 7114 } 7115 7116 /** 7117 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 7118 * 7119 * Note: Called from the default {@link AccessibilityDelegate}. 7120 * 7121 * @hide 7122 */ 7123 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 7124 event.setSource(this); 7125 event.setClassName(getAccessibilityClassName()); 7126 event.setPackageName(getContext().getPackageName()); 7127 event.setEnabled(isEnabled()); 7128 event.setContentDescription(mContentDescription); 7129 7130 switch (event.getEventType()) { 7131 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 7132 ArrayList<View> focusablesTempList = (mAttachInfo != null) 7133 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 7134 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 7135 event.setItemCount(focusablesTempList.size()); 7136 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 7137 if (mAttachInfo != null) { 7138 focusablesTempList.clear(); 7139 } 7140 } break; 7141 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 7142 CharSequence text = getIterableTextForAccessibility(); 7143 if (text != null && text.length() > 0) { 7144 event.setFromIndex(getAccessibilitySelectionStart()); 7145 event.setToIndex(getAccessibilitySelectionEnd()); 7146 event.setItemCount(text.length()); 7147 } 7148 } break; 7149 } 7150 } 7151 7152 /** 7153 * Returns an {@link AccessibilityNodeInfo} representing this view from the 7154 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 7155 * This method is responsible for obtaining an accessibility node info from a 7156 * pool of reusable instances and calling 7157 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 7158 * initialize the former. 7159 * <p> 7160 * Note: The client is responsible for recycling the obtained instance by calling 7161 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 7162 * </p> 7163 * 7164 * @return A populated {@link AccessibilityNodeInfo}. 7165 * 7166 * @see AccessibilityNodeInfo 7167 */ 7168 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 7169 if (mAccessibilityDelegate != null) { 7170 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 7171 } else { 7172 return createAccessibilityNodeInfoInternal(); 7173 } 7174 } 7175 7176 /** 7177 * @see #createAccessibilityNodeInfo() 7178 * 7179 * @hide 7180 */ 7181 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 7182 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7183 if (provider != null) { 7184 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 7185 } else { 7186 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 7187 onInitializeAccessibilityNodeInfo(info); 7188 return info; 7189 } 7190 } 7191 7192 /** 7193 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 7194 * The base implementation sets: 7195 * <ul> 7196 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 7197 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 7198 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 7199 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 7200 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 7201 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 7202 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 7203 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 7204 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 7205 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 7206 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 7207 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 7208 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 7209 * </ul> 7210 * <p> 7211 * Subclasses should override this method, call the super implementation, 7212 * and set additional attributes. 7213 * </p> 7214 * <p> 7215 * If an {@link AccessibilityDelegate} has been specified via calling 7216 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7217 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 7218 * is responsible for handling this call. 7219 * </p> 7220 * 7221 * @param info The instance to initialize. 7222 */ 7223 @CallSuper 7224 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 7225 if (mAccessibilityDelegate != null) { 7226 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 7227 } else { 7228 onInitializeAccessibilityNodeInfoInternal(info); 7229 } 7230 } 7231 7232 /** 7233 * Gets the location of this view in screen coordinates. 7234 * 7235 * @param outRect The output location 7236 * @hide 7237 */ 7238 public void getBoundsOnScreen(Rect outRect) { 7239 getBoundsOnScreen(outRect, false); 7240 } 7241 7242 /** 7243 * Gets the location of this view in screen coordinates. 7244 * 7245 * @param outRect The output location 7246 * @param clipToParent Whether to clip child bounds to the parent ones. 7247 * @hide 7248 */ 7249 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 7250 if (mAttachInfo == null) { 7251 return; 7252 } 7253 7254 RectF position = mAttachInfo.mTmpTransformRect; 7255 position.set(0, 0, mRight - mLeft, mBottom - mTop); 7256 mapRectFromViewToScreenCoords(position, clipToParent); 7257 outRect.set(Math.round(position.left), Math.round(position.top), 7258 Math.round(position.right), Math.round(position.bottom)); 7259 } 7260 7261 /** 7262 * Map a rectangle from view-relative coordinates to screen-relative coordinates 7263 * 7264 * @param rect The rectangle to be mapped 7265 * @param clipToParent Whether to clip child bounds to the parent ones. 7266 * @hide 7267 */ 7268 public void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) { 7269 if (!hasIdentityMatrix()) { 7270 getMatrix().mapRect(rect); 7271 } 7272 7273 rect.offset(mLeft, mTop); 7274 7275 ViewParent parent = mParent; 7276 while (parent instanceof View) { 7277 View parentView = (View) parent; 7278 7279 rect.offset(-parentView.mScrollX, -parentView.mScrollY); 7280 7281 if (clipToParent) { 7282 rect.left = Math.max(rect.left, 0); 7283 rect.top = Math.max(rect.top, 0); 7284 rect.right = Math.min(rect.right, parentView.getWidth()); 7285 rect.bottom = Math.min(rect.bottom, parentView.getHeight()); 7286 } 7287 7288 if (!parentView.hasIdentityMatrix()) { 7289 parentView.getMatrix().mapRect(rect); 7290 } 7291 7292 rect.offset(parentView.mLeft, parentView.mTop); 7293 7294 parent = parentView.mParent; 7295 } 7296 7297 if (parent instanceof ViewRootImpl) { 7298 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 7299 rect.offset(0, -viewRootImpl.mCurScrollY); 7300 } 7301 7302 rect.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 7303 } 7304 7305 /** 7306 * Return the class name of this object to be used for accessibility purposes. 7307 * Subclasses should only override this if they are implementing something that 7308 * should be seen as a completely new class of view when used by accessibility, 7309 * unrelated to the class it is deriving from. This is used to fill in 7310 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 7311 */ 7312 public CharSequence getAccessibilityClassName() { 7313 return View.class.getName(); 7314 } 7315 7316 /** 7317 * Called when assist structure is being retrieved from a view as part of 7318 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 7319 * @param structure Fill in with structured view data. The default implementation 7320 * fills in all data that can be inferred from the view itself. 7321 */ 7322 public void onProvideStructure(ViewStructure structure) { 7323 onProvideStructureForAssistOrAutofill(structure, false, 0); 7324 } 7325 7326 /** 7327 * Called when assist structure is being retrieved from a view as part of an autofill request. 7328 * 7329 * <p>This method already provides most of what's needed for autofill, but should be overridden 7330 * when: 7331 * <ul> 7332 * <li>The view contents does not include PII (Personally Identifiable Information), so it 7333 * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}. 7334 * <li>It must set fields such {@link ViewStructure#setText(CharSequence)}, 7335 * {@link ViewStructure#setAutofillOptions(CharSequence[])}, 7336 * or {@link ViewStructure#setWebDomain(String)}. 7337 * <li> The {@code left} and {@code top} values set in 7338 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} need to be relative to the next 7339 * {@link ViewGroup#isImportantForAutofill() included} parent in the structure. 7340 * </ul> 7341 * 7342 * @param structure Fill in with structured view data. The default implementation 7343 * fills in all data that can be inferred from the view itself. 7344 * @param flags optional flags. 7345 * 7346 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 7347 */ 7348 public void onProvideAutofillStructure(ViewStructure structure, @AutofillFlags int flags) { 7349 onProvideStructureForAssistOrAutofill(structure, true, flags); 7350 } 7351 7352 private void onProvideStructureForAssistOrAutofill(ViewStructure structure, 7353 boolean forAutofill, @AutofillFlags int flags) { 7354 final int id = mID; 7355 if (id != NO_ID && !isViewIdGenerated(id)) { 7356 String pkg, type, entry; 7357 try { 7358 final Resources res = getResources(); 7359 entry = res.getResourceEntryName(id); 7360 type = res.getResourceTypeName(id); 7361 pkg = res.getResourcePackageName(id); 7362 } catch (Resources.NotFoundException e) { 7363 entry = type = pkg = null; 7364 } 7365 structure.setId(id, pkg, type, entry); 7366 } else { 7367 structure.setId(id, null, null, null); 7368 } 7369 7370 if (forAutofill) { 7371 final @AutofillType int autofillType = getAutofillType(); 7372 // Don't need to fill autofill info if view does not support it. 7373 // For example, only TextViews that are editable support autofill 7374 if (autofillType != AUTOFILL_TYPE_NONE) { 7375 structure.setAutofillType(autofillType); 7376 structure.setAutofillHints(getAutofillHints()); 7377 structure.setAutofillValue(getAutofillValue()); 7378 } 7379 } 7380 7381 int ignoredParentLeft = 0; 7382 int ignoredParentTop = 0; 7383 if (forAutofill && (flags & AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) { 7384 View parentGroup = null; 7385 7386 ViewParent viewParent = getParent(); 7387 if (viewParent instanceof View) { 7388 parentGroup = (View) viewParent; 7389 } 7390 7391 while (parentGroup != null && !parentGroup.isImportantForAutofill()) { 7392 ignoredParentLeft += parentGroup.mLeft; 7393 ignoredParentTop += parentGroup.mTop; 7394 7395 viewParent = parentGroup.getParent(); 7396 if (viewParent instanceof View) { 7397 parentGroup = (View) viewParent; 7398 } else { 7399 break; 7400 } 7401 } 7402 } 7403 7404 structure.setDimens(ignoredParentLeft + mLeft, ignoredParentTop + mTop, mScrollX, mScrollY, 7405 mRight - mLeft, mBottom - mTop); 7406 if (!forAutofill) { 7407 if (!hasIdentityMatrix()) { 7408 structure.setTransformation(getMatrix()); 7409 } 7410 structure.setElevation(getZ()); 7411 } 7412 structure.setVisibility(getVisibility()); 7413 structure.setEnabled(isEnabled()); 7414 if (isClickable()) { 7415 structure.setClickable(true); 7416 } 7417 if (isFocusable()) { 7418 structure.setFocusable(true); 7419 } 7420 if (isFocused()) { 7421 structure.setFocused(true); 7422 } 7423 if (isAccessibilityFocused()) { 7424 structure.setAccessibilityFocused(true); 7425 } 7426 if (isSelected()) { 7427 structure.setSelected(true); 7428 } 7429 if (isActivated()) { 7430 structure.setActivated(true); 7431 } 7432 if (isLongClickable()) { 7433 structure.setLongClickable(true); 7434 } 7435 if (this instanceof Checkable) { 7436 structure.setCheckable(true); 7437 if (((Checkable)this).isChecked()) { 7438 structure.setChecked(true); 7439 } 7440 } 7441 if (isOpaque()) { 7442 structure.setOpaque(true); 7443 } 7444 if (isContextClickable()) { 7445 structure.setContextClickable(true); 7446 } 7447 structure.setClassName(getAccessibilityClassName().toString()); 7448 structure.setContentDescription(getContentDescription()); 7449 } 7450 7451 /** 7452 * Called when assist structure is being retrieved from a view as part of 7453 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 7454 * generate additional virtual structure under this view. The defaullt implementation 7455 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 7456 * view's virtual accessibility nodes, if any. You can override this for a more 7457 * optimal implementation providing this data. 7458 */ 7459 public void onProvideVirtualStructure(ViewStructure structure) { 7460 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7461 if (provider != null) { 7462 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 7463 structure.setChildCount(1); 7464 ViewStructure root = structure.newChild(0); 7465 populateVirtualStructure(root, provider, info); 7466 info.recycle(); 7467 } 7468 } 7469 7470 /** 7471 * Called when assist structure is being retrieved from a view as part of an autofill request 7472 * to generate additional virtual structure under this view. 7473 * 7474 * <p>When implementing this method, subclasses must follow the rules below: 7475 * 7476 * <ol> 7477 * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual 7478 * children. 7479 * <li>Call 7480 * {@link android.view.autofill.AutofillManager#notifyViewEntered} and 7481 * {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)} 7482 * when the focus inside the view changed. 7483 * <li>Call {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, 7484 * AutofillValue)} when the value of a child changed. 7485 * <li>Call {@link AutofillManager#commit()} when the autofill context 7486 * of the view structure changed and you want the current autofill interaction if such 7487 * to be commited. 7488 * <li>Call {@link AutofillManager#cancel()} ()} when the autofill context 7489 * of the view structure changed and you want the current autofill interaction if such 7490 * to be cancelled. 7491 * <li> The {@code left} and {@code top} values set in 7492 * {@link ViewStructure#setDimens(int, int, int, int, int, int)} need to be relative to the next 7493 * {@link ViewGroup#isImportantForAutofill() included} parent in the structure. 7494 * </ol> 7495 * 7496 * @param structure Fill in with structured view data. 7497 * @param flags optional flags. 7498 * 7499 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 7500 */ 7501 public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { 7502 } 7503 7504 /** 7505 * Automatically fills the content of this view with the {@code value}. 7506 * 7507 * <p>By default does nothing, but views should override it (and {@link #getAutofillType()}, 7508 * {@link #getAutofillValue()}, and {@link #onProvideAutofillStructure(ViewStructure, int)} 7509 * to support the Autofill Framework. 7510 * 7511 * <p>Typically, it is implemented by: 7512 * 7513 * <ol> 7514 * <li>Calling the proper getter method on {@link AutofillValue} to fetch the actual value. 7515 * <li>Passing the actual value to the equivalent setter in the view. 7516 * </ol> 7517 * 7518 * <p>For example, a text-field view would call: 7519 * <pre class="prettyprint"> 7520 * CharSequence text = value.getTextValue(); 7521 * if (text != null) { 7522 * setText(text); 7523 * } 7524 * </pre> 7525 * 7526 * <p>If the value is updated asyncronously the next call to 7527 * {@link AutofillManager#notifyValueChanged(View)} must happen <u>after</u> the value was 7528 * changed to the autofilled value. If not, the view will not be considered autofilled. 7529 * 7530 * @param value value to be autofilled. 7531 */ 7532 public void autofill(@SuppressWarnings("unused") AutofillValue value) { 7533 } 7534 7535 /** 7536 * Automatically fills the content of a virtual views. 7537 * 7538 * <p>See {@link #autofill(AutofillValue)} and 7539 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info. 7540 * <p>To indicate that a virtual view was autofilled 7541 * <code>?android:attr/autofilledHighlight</code> should be drawn over it until the data 7542 * changes. 7543 * 7544 * @param values map of values to be autofilled, keyed by virtual child id. 7545 * 7546 * @attr ref android.R.styleable#Theme_autofilledHighlight 7547 */ 7548 public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) { 7549 } 7550 7551 /** 7552 * Gets the unique identifier of this view on the screen for Autofill purposes. 7553 * 7554 * @return The View's Autofill id. 7555 */ 7556 public final AutofillId getAutofillId() { 7557 if (mAutofillId == null) { 7558 // The autofill id needs to be unique, but its value doesn't matter, 7559 // so it's better to reuse the accessibility id to save space. 7560 mAutofillId = new AutofillId(getAccessibilityViewId()); 7561 } 7562 return mAutofillId; 7563 } 7564 7565 /** 7566 * Describes the autofill type that should be used on calls to 7567 * {@link #autofill(AutofillValue)} and {@link #autofill(SparseArray)}. 7568 * 7569 * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it (and 7570 * {@link #autofill(AutofillValue)} to support the Autofill Framework. 7571 */ 7572 public @AutofillType int getAutofillType() { 7573 return AUTOFILL_TYPE_NONE; 7574 } 7575 7576 /** 7577 * Describes the content of a view so that a autofill service can fill in the appropriate data. 7578 * 7579 * @return The hints set via the attribute or {@code null} if no hint it set. 7580 * 7581 * @attr ref android.R.styleable#View_autofillHints 7582 */ 7583 @ViewDebug.ExportedProperty() 7584 @Nullable public String[] getAutofillHints() { 7585 return mAutofillHints; 7586 } 7587 7588 /** 7589 * @hide 7590 */ 7591 public boolean isAutofilled() { 7592 return (mPrivateFlags3 & PFLAG3_IS_AUTOFILLED) != 0; 7593 } 7594 7595 /** 7596 * Gets the {@link View}'s current autofill value. 7597 * 7598 * <p>By default returns {@code null}, but views should override it (and 7599 * {@link #autofill(AutofillValue)}, and {@link #getAutofillType()} to support the Autofill 7600 * Framework. 7601 */ 7602 @Nullable 7603 public AutofillValue getAutofillValue() { 7604 return null; 7605 } 7606 7607 /** 7608 * Gets the mode for determining whether this View is important for autofill. 7609 * 7610 * <p>See {@link #setImportantForAutofill(int)} for more info about this mode. 7611 * 7612 * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to 7613 * {@link #setImportantForAutofill(int)}. 7614 * 7615 * @attr ref android.R.styleable#View_importantForAutofill 7616 */ 7617 @ViewDebug.ExportedProperty(mapping = { 7618 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"), 7619 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"), 7620 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no"), 7621 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS, 7622 to = "yesExcludeDescendants"), 7623 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS, 7624 to = "noExcludeDescendants")}) 7625 public @AutofillImportance int getImportantForAutofill() { 7626 return (mPrivateFlags3 7627 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 7628 } 7629 7630 /** 7631 * Sets the mode for determining whether this View is important for autofill. 7632 * 7633 * <p>This property controls how this view is presented to the autofill components 7634 * which help users to fill credentials, addresses, etc. For example, views 7635 * that contain labels and input fields are useful for autofill components to 7636 * determine the user context and provide values for the inputs. Note that the 7637 * user can always override this by manually triggering autotill which would 7638 * expose the view to the autofill provider. 7639 * 7640 * <p>The platform determines the importance for autofill automatically but you 7641 * can use this method to customize the behavior. See the autofill modes below 7642 * for more details. 7643 * 7644 * <p>See {@link #setImportantForAutofill(int)} for more info about this mode. 7645 * 7646 * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES}, 7647 * {@link #IMPORTANT_FOR_AUTOFILL_NO}, {@link #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS}, 7648 * or {@link #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS}. 7649 * 7650 * @attr ref android.R.styleable#View_importantForAutofill 7651 */ 7652 public void setImportantForAutofill(@AutofillImportance int mode) { 7653 mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 7654 mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT) 7655 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 7656 } 7657 7658 /** 7659 * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode} 7660 * associated with this View should be included in a {@link ViewStructure} used for 7661 * autofill purposes. 7662 * 7663 * <p>Generally speaking, a view is important for autofill if: 7664 * <ol> 7665 * <li>The view can-be autofilled by an {@link android.service.autofill.AutofillService}. 7666 * <li>The view contents can help an {@link android.service.autofill.AutofillService} to 7667 * autofill other views. 7668 * <ol> 7669 * 7670 * <p>For example, view containers should typically return {@code false} for performance reasons 7671 * (since the important info is provided by their children), but if the container is actually 7672 * whose children are part of a compound view, it should return {@code true} (and then override 7673 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call 7674 * {@link #onProvideAutofillStructure(ViewStructure, int)} so its children are not included in 7675 * the structure). On the other hand, views representing labels or editable fields should 7676 * typically return {@code true}, but in some cases they could return {@code false} (for 7677 * example, if they're part of a "Captcha" mechanism). 7678 * 7679 * <p>By default, this method returns {@code true} if {@link #getImportantForAutofill()} returns 7680 * {@link #IMPORTANT_FOR_AUTOFILL_YES}, {@code false } if it returns 7681 * {@link #IMPORTANT_FOR_AUTOFILL_NO}, and use some heuristics to define the importance when it 7682 * returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}. Hence, it should rarely be overridden - Views 7683 * should use {@link #setImportantForAutofill(int)} instead. 7684 * 7685 * <p><strong>Note:</strong> returning {@code false} does not guarantee the view will be 7686 * excluded from the structure; for example, if the user explicitly requested autofill, the 7687 * View might be always included. 7688 * 7689 * <p>This decision applies just for the view, not its children - if the view children are not 7690 * important for autofill, the view should override 7691 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call 7692 * {@link #onProvideAutofillStructure(ViewStructure, int)} (instead of calling 7693 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} for each child). 7694 * 7695 * @return whether the view is considered important for autofill. 7696 * 7697 * @see #setImportantForAutofill(int) 7698 * @see #IMPORTANT_FOR_AUTOFILL_AUTO 7699 * @see #IMPORTANT_FOR_AUTOFILL_YES 7700 * @see #IMPORTANT_FOR_AUTOFILL_NO 7701 * @see #IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 7702 * @see #IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 7703 */ 7704 public final boolean isImportantForAutofill() { 7705 // Check parent mode to ensure we're not hidden. 7706 ViewParent parent = mParent; 7707 while (parent instanceof View) { 7708 final int parentImportance = ((View) parent).getImportantForAutofill(); 7709 if (parentImportance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 7710 || parentImportance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS) { 7711 return false; 7712 } 7713 parent = parent.getParent(); 7714 } 7715 7716 final int importance = getImportantForAutofill(); 7717 7718 // First, check the explicit states. 7719 if (importance == IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS 7720 || importance == IMPORTANT_FOR_AUTOFILL_YES) { 7721 return true; 7722 } 7723 if (importance == IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS 7724 || importance == IMPORTANT_FOR_AUTOFILL_NO) { 7725 return false; 7726 } 7727 7728 // Then use some heuristics to handle AUTO. 7729 7730 // Always include views that have an explicit resource id. 7731 final int id = mID; 7732 if (id != NO_ID && !isViewIdGenerated(id)) { 7733 final Resources res = getResources(); 7734 String entry = null; 7735 String pkg = null; 7736 try { 7737 entry = res.getResourceEntryName(id); 7738 pkg = res.getResourcePackageName(id); 7739 } catch (Resources.NotFoundException e) { 7740 // ignore 7741 } 7742 if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) { 7743 return true; 7744 } 7745 } 7746 7747 // Otherwise, assume it's not important... 7748 return false; 7749 } 7750 7751 @Nullable 7752 private AutofillManager getAutofillManager() { 7753 return mContext.getSystemService(AutofillManager.class); 7754 } 7755 7756 private boolean isAutofillable() { 7757 return getAutofillType() != AUTOFILL_TYPE_NONE && isImportantForAutofill() 7758 && getAccessibilityViewId() > LAST_APP_ACCESSIBILITY_ID; 7759 } 7760 7761 private void populateVirtualStructure(ViewStructure structure, 7762 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 7763 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 7764 null, null, null); 7765 Rect rect = structure.getTempRect(); 7766 info.getBoundsInParent(rect); 7767 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 7768 structure.setVisibility(VISIBLE); 7769 structure.setEnabled(info.isEnabled()); 7770 if (info.isClickable()) { 7771 structure.setClickable(true); 7772 } 7773 if (info.isFocusable()) { 7774 structure.setFocusable(true); 7775 } 7776 if (info.isFocused()) { 7777 structure.setFocused(true); 7778 } 7779 if (info.isAccessibilityFocused()) { 7780 structure.setAccessibilityFocused(true); 7781 } 7782 if (info.isSelected()) { 7783 structure.setSelected(true); 7784 } 7785 if (info.isLongClickable()) { 7786 structure.setLongClickable(true); 7787 } 7788 if (info.isCheckable()) { 7789 structure.setCheckable(true); 7790 if (info.isChecked()) { 7791 structure.setChecked(true); 7792 } 7793 } 7794 if (info.isContextClickable()) { 7795 structure.setContextClickable(true); 7796 } 7797 CharSequence cname = info.getClassName(); 7798 structure.setClassName(cname != null ? cname.toString() : null); 7799 structure.setContentDescription(info.getContentDescription()); 7800 if ((info.getText() != null || info.getError() != null)) { 7801 structure.setText(info.getText(), info.getTextSelectionStart(), 7802 info.getTextSelectionEnd()); 7803 } 7804 final int NCHILDREN = info.getChildCount(); 7805 if (NCHILDREN > 0) { 7806 structure.setChildCount(NCHILDREN); 7807 for (int i=0; i<NCHILDREN; i++) { 7808 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 7809 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 7810 ViewStructure child = structure.newChild(i); 7811 populateVirtualStructure(child, provider, cinfo); 7812 cinfo.recycle(); 7813 } 7814 } 7815 } 7816 7817 /** 7818 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 7819 * implementation calls {@link #onProvideStructure} and 7820 * {@link #onProvideVirtualStructure}. 7821 */ 7822 public void dispatchProvideStructure(ViewStructure structure) { 7823 dispatchProvideStructureForAssistOrAutofill(structure, false, 0); 7824 } 7825 7826 /** 7827 * Dispatch creation of {@link ViewStructure} down the hierarchy. 7828 * 7829 * <p>The default implementation does the following: 7830 * 7831 * <ul> 7832 * <li>Sets the {@link AutofillId} in the structure. 7833 * <li>Calls {@link #onProvideAutofillStructure(ViewStructure, int)}. 7834 * <li>Calls {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}. 7835 * </ul> 7836 * 7837 * <p>When overridden, it must either call 7838 * {@code super.dispatchProvideAutofillStructure(structure, flags)} or explicitly 7839 * set the {@link AutofillId} in the structure (for example, by calling 7840 * {@code structure.setAutofillId(getAutofillId())}). 7841 * 7842 * <p>When providing your implementation you need to decide how to handle 7843 * the {@link #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS} flag which instructs you 7844 * to report all views to the structure regardless if {@link #isImportantForAutofill()} 7845 * returns true. We encourage you respect the importance property for a better 7846 * user experience in your app. If the flag is not set then you should filter out 7847 * not important views to optimize autofill performance in your app. 7848 * 7849 * @param structure Fill in with structured view data. 7850 * @param flags optional flags. 7851 * 7852 * @see #AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 7853 */ 7854 public void dispatchProvideAutofillStructure(@NonNull ViewStructure structure, 7855 @AutofillFlags int flags) { 7856 dispatchProvideStructureForAssistOrAutofill(structure, true, flags); 7857 } 7858 7859 private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure, 7860 boolean forAutofill, @AutofillFlags int flags) { 7861 if (forAutofill) { 7862 structure.setAutofillId(getAutofillId()); 7863 onProvideAutofillStructure(structure, flags); 7864 onProvideAutofillVirtualStructure(structure, flags); 7865 } else if (!isAssistBlocked()) { 7866 onProvideStructure(structure); 7867 onProvideVirtualStructure(structure); 7868 } else { 7869 structure.setClassName(getAccessibilityClassName().toString()); 7870 structure.setAssistBlocked(true); 7871 } 7872 } 7873 7874 /** 7875 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 7876 * 7877 * Note: Called from the default {@link AccessibilityDelegate}. 7878 * 7879 * @hide 7880 */ 7881 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 7882 if (mAttachInfo == null) { 7883 return; 7884 } 7885 7886 Rect bounds = mAttachInfo.mTmpInvalRect; 7887 7888 getDrawingRect(bounds); 7889 info.setBoundsInParent(bounds); 7890 7891 getBoundsOnScreen(bounds, true); 7892 info.setBoundsInScreen(bounds); 7893 7894 ViewParent parent = getParentForAccessibility(); 7895 if (parent instanceof View) { 7896 info.setParent((View) parent); 7897 } 7898 7899 if (mID != View.NO_ID) { 7900 View rootView = getRootView(); 7901 if (rootView == null) { 7902 rootView = this; 7903 } 7904 7905 View label = rootView.findLabelForView(this, mID); 7906 if (label != null) { 7907 info.setLabeledBy(label); 7908 } 7909 7910 if ((mAttachInfo.mAccessibilityFetchFlags 7911 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 7912 && Resources.resourceHasPackage(mID)) { 7913 try { 7914 String viewId = getResources().getResourceName(mID); 7915 info.setViewIdResourceName(viewId); 7916 } catch (Resources.NotFoundException nfe) { 7917 /* ignore */ 7918 } 7919 } 7920 } 7921 7922 if (mLabelForId != View.NO_ID) { 7923 View rootView = getRootView(); 7924 if (rootView == null) { 7925 rootView = this; 7926 } 7927 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 7928 if (labeled != null) { 7929 info.setLabelFor(labeled); 7930 } 7931 } 7932 7933 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 7934 View rootView = getRootView(); 7935 if (rootView == null) { 7936 rootView = this; 7937 } 7938 View next = rootView.findViewInsideOutShouldExist(this, 7939 mAccessibilityTraversalBeforeId); 7940 if (next != null && next.includeForAccessibility()) { 7941 info.setTraversalBefore(next); 7942 } 7943 } 7944 7945 if (mAccessibilityTraversalAfterId != View.NO_ID) { 7946 View rootView = getRootView(); 7947 if (rootView == null) { 7948 rootView = this; 7949 } 7950 View next = rootView.findViewInsideOutShouldExist(this, 7951 mAccessibilityTraversalAfterId); 7952 if (next != null && next.includeForAccessibility()) { 7953 info.setTraversalAfter(next); 7954 } 7955 } 7956 7957 info.setVisibleToUser(isVisibleToUser()); 7958 7959 info.setImportantForAccessibility(isImportantForAccessibility()); 7960 info.setPackageName(mContext.getPackageName()); 7961 info.setClassName(getAccessibilityClassName()); 7962 info.setContentDescription(getContentDescription()); 7963 7964 info.setEnabled(isEnabled()); 7965 info.setClickable(isClickable()); 7966 info.setFocusable(isFocusable()); 7967 info.setFocused(isFocused()); 7968 info.setAccessibilityFocused(isAccessibilityFocused()); 7969 info.setSelected(isSelected()); 7970 info.setLongClickable(isLongClickable()); 7971 info.setContextClickable(isContextClickable()); 7972 info.setLiveRegion(getAccessibilityLiveRegion()); 7973 7974 // TODO: These make sense only if we are in an AdapterView but all 7975 // views can be selected. Maybe from accessibility perspective 7976 // we should report as selectable view in an AdapterView. 7977 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 7978 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 7979 7980 if (isFocusable()) { 7981 if (isFocused()) { 7982 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 7983 } else { 7984 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 7985 } 7986 } 7987 7988 if (!isAccessibilityFocused()) { 7989 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 7990 } else { 7991 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 7992 } 7993 7994 if (isClickable() && isEnabled()) { 7995 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 7996 } 7997 7998 if (isLongClickable() && isEnabled()) { 7999 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 8000 } 8001 8002 if (isContextClickable() && isEnabled()) { 8003 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 8004 } 8005 8006 CharSequence text = getIterableTextForAccessibility(); 8007 if (text != null && text.length() > 0) { 8008 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 8009 8010 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 8011 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 8012 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 8013 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 8014 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 8015 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 8016 } 8017 8018 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 8019 populateAccessibilityNodeInfoDrawingOrderInParent(info); 8020 } 8021 8022 /** 8023 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 8024 * additional data. 8025 * <p> 8026 * This method only needs overloading if the node is marked as having extra data available. 8027 * </p> 8028 * 8029 * @param info The info to which to add the extra data. Never {@code null}. 8030 * @param extraDataKey A key specifying the type of extra data to add to the info. The 8031 * extra data should be added to the {@link Bundle} returned by 8032 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 8033 * {@code null}. 8034 * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be 8035 * {@code null} if the service provided no arguments. 8036 * 8037 * @see AccessibilityNodeInfo#setAvailableExtraData(List) 8038 */ 8039 public void addExtraDataToAccessibilityNodeInfo( 8040 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 8041 @Nullable Bundle arguments) { 8042 } 8043 8044 /** 8045 * Determine the order in which this view will be drawn relative to its siblings for a11y 8046 * 8047 * @param info The info whose drawing order should be populated 8048 */ 8049 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 8050 /* 8051 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 8052 * drawing order may not be well-defined, and some Views with custom drawing order may 8053 * not be initialized sufficiently to respond properly getChildDrawingOrder. 8054 */ 8055 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 8056 info.setDrawingOrder(0); 8057 return; 8058 } 8059 int drawingOrderInParent = 1; 8060 // Iterate up the hierarchy if parents are not important for a11y 8061 View viewAtDrawingLevel = this; 8062 final ViewParent parent = getParentForAccessibility(); 8063 while (viewAtDrawingLevel != parent) { 8064 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 8065 if (!(currentParent instanceof ViewGroup)) { 8066 // Should only happen for the Decor 8067 drawingOrderInParent = 0; 8068 break; 8069 } else { 8070 final ViewGroup parentGroup = (ViewGroup) currentParent; 8071 final int childCount = parentGroup.getChildCount(); 8072 if (childCount > 1) { 8073 List<View> preorderedList = parentGroup.buildOrderedChildList(); 8074 if (preorderedList != null) { 8075 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 8076 for (int i = 0; i < childDrawIndex; i++) { 8077 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 8078 } 8079 } else { 8080 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 8081 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 8082 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 8083 .getChildDrawingOrder(childCount, childIndex) : childIndex; 8084 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 8085 if (childDrawIndex != 0) { 8086 for (int i = 0; i < numChildrenToIterate; i++) { 8087 final int otherDrawIndex = (customOrder ? 8088 parentGroup.getChildDrawingOrder(childCount, i) : i); 8089 if (otherDrawIndex < childDrawIndex) { 8090 drawingOrderInParent += 8091 numViewsForAccessibility(parentGroup.getChildAt(i)); 8092 } 8093 } 8094 } 8095 } 8096 } 8097 } 8098 viewAtDrawingLevel = (View) currentParent; 8099 } 8100 info.setDrawingOrder(drawingOrderInParent); 8101 } 8102 8103 private static int numViewsForAccessibility(View view) { 8104 if (view != null) { 8105 if (view.includeForAccessibility()) { 8106 return 1; 8107 } else if (view instanceof ViewGroup) { 8108 return ((ViewGroup) view).getNumChildrenForAccessibility(); 8109 } 8110 } 8111 return 0; 8112 } 8113 8114 private View findLabelForView(View view, int labeledId) { 8115 if (mMatchLabelForPredicate == null) { 8116 mMatchLabelForPredicate = new MatchLabelForPredicate(); 8117 } 8118 mMatchLabelForPredicate.mLabeledId = labeledId; 8119 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 8120 } 8121 8122 /** 8123 * Computes whether this view is visible to the user. Such a view is 8124 * attached, visible, all its predecessors are visible, it is not clipped 8125 * entirely by its predecessors, and has an alpha greater than zero. 8126 * 8127 * @return Whether the view is visible on the screen. 8128 * 8129 * @hide 8130 */ 8131 protected boolean isVisibleToUser() { 8132 return isVisibleToUser(null); 8133 } 8134 8135 /** 8136 * Computes whether the given portion of this view is visible to the user. 8137 * Such a view is attached, visible, all its predecessors are visible, 8138 * has an alpha greater than zero, and the specified portion is not 8139 * clipped entirely by its predecessors. 8140 * 8141 * @param boundInView the portion of the view to test; coordinates should be relative; may be 8142 * <code>null</code>, and the entire view will be tested in this case. 8143 * When <code>true</code> is returned by the function, the actual visible 8144 * region will be stored in this parameter; that is, if boundInView is fully 8145 * contained within the view, no modification will be made, otherwise regions 8146 * outside of the visible area of the view will be clipped. 8147 * 8148 * @return Whether the specified portion of the view is visible on the screen. 8149 * 8150 * @hide 8151 */ 8152 protected boolean isVisibleToUser(Rect boundInView) { 8153 if (mAttachInfo != null) { 8154 // Attached to invisible window means this view is not visible. 8155 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 8156 return false; 8157 } 8158 // An invisible predecessor or one with alpha zero means 8159 // that this view is not visible to the user. 8160 Object current = this; 8161 while (current instanceof View) { 8162 View view = (View) current; 8163 // We have attach info so this view is attached and there is no 8164 // need to check whether we reach to ViewRootImpl on the way up. 8165 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 8166 view.getVisibility() != VISIBLE) { 8167 return false; 8168 } 8169 current = view.mParent; 8170 } 8171 // Check if the view is entirely covered by its predecessors. 8172 Rect visibleRect = mAttachInfo.mTmpInvalRect; 8173 Point offset = mAttachInfo.mPoint; 8174 if (!getGlobalVisibleRect(visibleRect, offset)) { 8175 return false; 8176 } 8177 // Check if the visible portion intersects the rectangle of interest. 8178 if (boundInView != null) { 8179 visibleRect.offset(-offset.x, -offset.y); 8180 return boundInView.intersect(visibleRect); 8181 } 8182 return true; 8183 } 8184 return false; 8185 } 8186 8187 /** 8188 * Returns the delegate for implementing accessibility support via 8189 * composition. For more details see {@link AccessibilityDelegate}. 8190 * 8191 * @return The delegate, or null if none set. 8192 * 8193 * @hide 8194 */ 8195 public AccessibilityDelegate getAccessibilityDelegate() { 8196 return mAccessibilityDelegate; 8197 } 8198 8199 /** 8200 * Sets a delegate for implementing accessibility support via composition 8201 * (as opposed to inheritance). For more details, see 8202 * {@link AccessibilityDelegate}. 8203 * <p> 8204 * <strong>Note:</strong> On platform versions prior to 8205 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 8206 * views in the {@code android.widget.*} package are called <i>before</i> 8207 * host methods. This prevents certain properties such as class name from 8208 * being modified by overriding 8209 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 8210 * as any changes will be overwritten by the host class. 8211 * <p> 8212 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 8213 * methods are called <i>after</i> host methods, which all properties to be 8214 * modified without being overwritten by the host class. 8215 * 8216 * @param delegate the object to which accessibility method calls should be 8217 * delegated 8218 * @see AccessibilityDelegate 8219 */ 8220 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 8221 mAccessibilityDelegate = delegate; 8222 } 8223 8224 /** 8225 * Gets the provider for managing a virtual view hierarchy rooted at this View 8226 * and reported to {@link android.accessibilityservice.AccessibilityService}s 8227 * that explore the window content. 8228 * <p> 8229 * If this method returns an instance, this instance is responsible for managing 8230 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 8231 * View including the one representing the View itself. Similarly the returned 8232 * instance is responsible for performing accessibility actions on any virtual 8233 * view or the root view itself. 8234 * </p> 8235 * <p> 8236 * If an {@link AccessibilityDelegate} has been specified via calling 8237 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8238 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 8239 * is responsible for handling this call. 8240 * </p> 8241 * 8242 * @return The provider. 8243 * 8244 * @see AccessibilityNodeProvider 8245 */ 8246 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 8247 if (mAccessibilityDelegate != null) { 8248 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 8249 } else { 8250 return null; 8251 } 8252 } 8253 8254 /** 8255 * Gets the unique identifier of this view on the screen for accessibility purposes. 8256 * 8257 * @return The view accessibility id. 8258 * 8259 * @hide 8260 */ 8261 public int getAccessibilityViewId() { 8262 if (mAccessibilityViewId == NO_ID) { 8263 mAccessibilityViewId = mContext.getNextAccessibilityId(); 8264 } 8265 return mAccessibilityViewId; 8266 } 8267 8268 /** 8269 * Gets the unique identifier of the window in which this View reseides. 8270 * 8271 * @return The window accessibility id. 8272 * 8273 * @hide 8274 */ 8275 public int getAccessibilityWindowId() { 8276 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 8277 : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 8278 } 8279 8280 /** 8281 * Returns the {@link View}'s content description. 8282 * <p> 8283 * <strong>Note:</strong> Do not override this method, as it will have no 8284 * effect on the content description presented to accessibility services. 8285 * You must call {@link #setContentDescription(CharSequence)} to modify the 8286 * content description. 8287 * 8288 * @return the content description 8289 * @see #setContentDescription(CharSequence) 8290 * @attr ref android.R.styleable#View_contentDescription 8291 */ 8292 @ViewDebug.ExportedProperty(category = "accessibility") 8293 public CharSequence getContentDescription() { 8294 return mContentDescription; 8295 } 8296 8297 /** 8298 * Sets the {@link View}'s content description. 8299 * <p> 8300 * A content description briefly describes the view and is primarily used 8301 * for accessibility support to determine how a view should be presented to 8302 * the user. In the case of a view with no textual representation, such as 8303 * {@link android.widget.ImageButton}, a useful content description 8304 * explains what the view does. For example, an image button with a phone 8305 * icon that is used to place a call may use "Call" as its content 8306 * description. An image of a floppy disk that is used to save a file may 8307 * use "Save". 8308 * 8309 * @param contentDescription The content description. 8310 * @see #getContentDescription() 8311 * @attr ref android.R.styleable#View_contentDescription 8312 */ 8313 @RemotableViewMethod 8314 public void setContentDescription(CharSequence contentDescription) { 8315 if (mContentDescription == null) { 8316 if (contentDescription == null) { 8317 return; 8318 } 8319 } else if (mContentDescription.equals(contentDescription)) { 8320 return; 8321 } 8322 mContentDescription = contentDescription; 8323 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 8324 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 8325 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 8326 notifySubtreeAccessibilityStateChangedIfNeeded(); 8327 } else { 8328 notifyViewAccessibilityStateChangedIfNeeded( 8329 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 8330 } 8331 } 8332 8333 /** 8334 * Sets the id of a view before which this one is visited in accessibility traversal. 8335 * A screen-reader must visit the content of this view before the content of the one 8336 * it precedes. For example, if view B is set to be before view A, then a screen-reader 8337 * will traverse the entire content of B before traversing the entire content of A, 8338 * regardles of what traversal strategy it is using. 8339 * <p> 8340 * Views that do not have specified before/after relationships are traversed in order 8341 * determined by the screen-reader. 8342 * </p> 8343 * <p> 8344 * Setting that this view is before a view that is not important for accessibility 8345 * or if this view is not important for accessibility will have no effect as the 8346 * screen-reader is not aware of unimportant views. 8347 * </p> 8348 * 8349 * @param beforeId The id of a view this one precedes in accessibility traversal. 8350 * 8351 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 8352 * 8353 * @see #setImportantForAccessibility(int) 8354 */ 8355 @RemotableViewMethod 8356 public void setAccessibilityTraversalBefore(int beforeId) { 8357 if (mAccessibilityTraversalBeforeId == beforeId) { 8358 return; 8359 } 8360 mAccessibilityTraversalBeforeId = beforeId; 8361 notifyViewAccessibilityStateChangedIfNeeded( 8362 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8363 } 8364 8365 /** 8366 * Gets the id of a view before which this one is visited in accessibility traversal. 8367 * 8368 * @return The id of a view this one precedes in accessibility traversal if 8369 * specified, otherwise {@link #NO_ID}. 8370 * 8371 * @see #setAccessibilityTraversalBefore(int) 8372 */ 8373 public int getAccessibilityTraversalBefore() { 8374 return mAccessibilityTraversalBeforeId; 8375 } 8376 8377 /** 8378 * Sets the id of a view after which this one is visited in accessibility traversal. 8379 * A screen-reader must visit the content of the other view before the content of this 8380 * one. For example, if view B is set to be after view A, then a screen-reader 8381 * will traverse the entire content of A before traversing the entire content of B, 8382 * regardles of what traversal strategy it is using. 8383 * <p> 8384 * Views that do not have specified before/after relationships are traversed in order 8385 * determined by the screen-reader. 8386 * </p> 8387 * <p> 8388 * Setting that this view is after a view that is not important for accessibility 8389 * or if this view is not important for accessibility will have no effect as the 8390 * screen-reader is not aware of unimportant views. 8391 * </p> 8392 * 8393 * @param afterId The id of a view this one succedees in accessibility traversal. 8394 * 8395 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 8396 * 8397 * @see #setImportantForAccessibility(int) 8398 */ 8399 @RemotableViewMethod 8400 public void setAccessibilityTraversalAfter(int afterId) { 8401 if (mAccessibilityTraversalAfterId == afterId) { 8402 return; 8403 } 8404 mAccessibilityTraversalAfterId = afterId; 8405 notifyViewAccessibilityStateChangedIfNeeded( 8406 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8407 } 8408 8409 /** 8410 * Gets the id of a view after which this one is visited in accessibility traversal. 8411 * 8412 * @return The id of a view this one succeedes in accessibility traversal if 8413 * specified, otherwise {@link #NO_ID}. 8414 * 8415 * @see #setAccessibilityTraversalAfter(int) 8416 */ 8417 public int getAccessibilityTraversalAfter() { 8418 return mAccessibilityTraversalAfterId; 8419 } 8420 8421 /** 8422 * Gets the id of a view for which this view serves as a label for 8423 * accessibility purposes. 8424 * 8425 * @return The labeled view id. 8426 */ 8427 @ViewDebug.ExportedProperty(category = "accessibility") 8428 public int getLabelFor() { 8429 return mLabelForId; 8430 } 8431 8432 /** 8433 * Sets the id of a view for which this view serves as a label for 8434 * accessibility purposes. 8435 * 8436 * @param id The labeled view id. 8437 */ 8438 @RemotableViewMethod 8439 public void setLabelFor(@IdRes int id) { 8440 if (mLabelForId == id) { 8441 return; 8442 } 8443 mLabelForId = id; 8444 if (mLabelForId != View.NO_ID 8445 && mID == View.NO_ID) { 8446 mID = generateViewId(); 8447 } 8448 notifyViewAccessibilityStateChangedIfNeeded( 8449 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8450 } 8451 8452 /** 8453 * Invoked whenever this view loses focus, either by losing window focus or by losing 8454 * focus within its window. This method can be used to clear any state tied to the 8455 * focus. For instance, if a button is held pressed with the trackball and the window 8456 * loses focus, this method can be used to cancel the press. 8457 * 8458 * Subclasses of View overriding this method should always call super.onFocusLost(). 8459 * 8460 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 8461 * @see #onWindowFocusChanged(boolean) 8462 * 8463 * @hide pending API council approval 8464 */ 8465 @CallSuper 8466 protected void onFocusLost() { 8467 resetPressedState(); 8468 } 8469 8470 private void resetPressedState() { 8471 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8472 return; 8473 } 8474 8475 if (isPressed()) { 8476 setPressed(false); 8477 8478 if (!mHasPerformedLongPress) { 8479 removeLongPressCallback(); 8480 } 8481 } 8482 } 8483 8484 /** 8485 * Returns true if this view has focus 8486 * 8487 * @return True if this view has focus, false otherwise. 8488 */ 8489 @ViewDebug.ExportedProperty(category = "focus") 8490 public boolean isFocused() { 8491 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 8492 } 8493 8494 /** 8495 * Find the view in the hierarchy rooted at this view that currently has 8496 * focus. 8497 * 8498 * @return The view that currently has focus, or null if no focused view can 8499 * be found. 8500 */ 8501 public View findFocus() { 8502 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 8503 } 8504 8505 /** 8506 * Indicates whether this view is one of the set of scrollable containers in 8507 * its window. 8508 * 8509 * @return whether this view is one of the set of scrollable containers in 8510 * its window 8511 * 8512 * @attr ref android.R.styleable#View_isScrollContainer 8513 */ 8514 public boolean isScrollContainer() { 8515 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 8516 } 8517 8518 /** 8519 * Change whether this view is one of the set of scrollable containers in 8520 * its window. This will be used to determine whether the window can 8521 * resize or must pan when a soft input area is open -- scrollable 8522 * containers allow the window to use resize mode since the container 8523 * will appropriately shrink. 8524 * 8525 * @attr ref android.R.styleable#View_isScrollContainer 8526 */ 8527 public void setScrollContainer(boolean isScrollContainer) { 8528 if (isScrollContainer) { 8529 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 8530 mAttachInfo.mScrollContainers.add(this); 8531 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 8532 } 8533 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 8534 } else { 8535 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 8536 mAttachInfo.mScrollContainers.remove(this); 8537 } 8538 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 8539 } 8540 } 8541 8542 /** 8543 * Returns the quality of the drawing cache. 8544 * 8545 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 8546 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 8547 * 8548 * @see #setDrawingCacheQuality(int) 8549 * @see #setDrawingCacheEnabled(boolean) 8550 * @see #isDrawingCacheEnabled() 8551 * 8552 * @attr ref android.R.styleable#View_drawingCacheQuality 8553 */ 8554 @DrawingCacheQuality 8555 public int getDrawingCacheQuality() { 8556 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 8557 } 8558 8559 /** 8560 * Set the drawing cache quality of this view. This value is used only when the 8561 * drawing cache is enabled 8562 * 8563 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 8564 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 8565 * 8566 * @see #getDrawingCacheQuality() 8567 * @see #setDrawingCacheEnabled(boolean) 8568 * @see #isDrawingCacheEnabled() 8569 * 8570 * @attr ref android.R.styleable#View_drawingCacheQuality 8571 */ 8572 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 8573 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 8574 } 8575 8576 /** 8577 * Returns whether the screen should remain on, corresponding to the current 8578 * value of {@link #KEEP_SCREEN_ON}. 8579 * 8580 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 8581 * 8582 * @see #setKeepScreenOn(boolean) 8583 * 8584 * @attr ref android.R.styleable#View_keepScreenOn 8585 */ 8586 public boolean getKeepScreenOn() { 8587 return (mViewFlags & KEEP_SCREEN_ON) != 0; 8588 } 8589 8590 /** 8591 * Controls whether the screen should remain on, modifying the 8592 * value of {@link #KEEP_SCREEN_ON}. 8593 * 8594 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 8595 * 8596 * @see #getKeepScreenOn() 8597 * 8598 * @attr ref android.R.styleable#View_keepScreenOn 8599 */ 8600 public void setKeepScreenOn(boolean keepScreenOn) { 8601 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 8602 } 8603 8604 /** 8605 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 8606 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8607 * 8608 * @attr ref android.R.styleable#View_nextFocusLeft 8609 */ 8610 public int getNextFocusLeftId() { 8611 return mNextFocusLeftId; 8612 } 8613 8614 /** 8615 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 8616 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 8617 * decide automatically. 8618 * 8619 * @attr ref android.R.styleable#View_nextFocusLeft 8620 */ 8621 public void setNextFocusLeftId(int nextFocusLeftId) { 8622 mNextFocusLeftId = nextFocusLeftId; 8623 } 8624 8625 /** 8626 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 8627 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8628 * 8629 * @attr ref android.R.styleable#View_nextFocusRight 8630 */ 8631 public int getNextFocusRightId() { 8632 return mNextFocusRightId; 8633 } 8634 8635 /** 8636 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 8637 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 8638 * decide automatically. 8639 * 8640 * @attr ref android.R.styleable#View_nextFocusRight 8641 */ 8642 public void setNextFocusRightId(int nextFocusRightId) { 8643 mNextFocusRightId = nextFocusRightId; 8644 } 8645 8646 /** 8647 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 8648 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8649 * 8650 * @attr ref android.R.styleable#View_nextFocusUp 8651 */ 8652 public int getNextFocusUpId() { 8653 return mNextFocusUpId; 8654 } 8655 8656 /** 8657 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 8658 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 8659 * decide automatically. 8660 * 8661 * @attr ref android.R.styleable#View_nextFocusUp 8662 */ 8663 public void setNextFocusUpId(int nextFocusUpId) { 8664 mNextFocusUpId = nextFocusUpId; 8665 } 8666 8667 /** 8668 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 8669 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8670 * 8671 * @attr ref android.R.styleable#View_nextFocusDown 8672 */ 8673 public int getNextFocusDownId() { 8674 return mNextFocusDownId; 8675 } 8676 8677 /** 8678 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 8679 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 8680 * decide automatically. 8681 * 8682 * @attr ref android.R.styleable#View_nextFocusDown 8683 */ 8684 public void setNextFocusDownId(int nextFocusDownId) { 8685 mNextFocusDownId = nextFocusDownId; 8686 } 8687 8688 /** 8689 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 8690 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8691 * 8692 * @attr ref android.R.styleable#View_nextFocusForward 8693 */ 8694 public int getNextFocusForwardId() { 8695 return mNextFocusForwardId; 8696 } 8697 8698 /** 8699 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 8700 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 8701 * decide automatically. 8702 * 8703 * @attr ref android.R.styleable#View_nextFocusForward 8704 */ 8705 public void setNextFocusForwardId(int nextFocusForwardId) { 8706 mNextFocusForwardId = nextFocusForwardId; 8707 } 8708 8709 /** 8710 * Gets the id of the root of the next keyboard navigation cluster. 8711 * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should 8712 * decide automatically. 8713 * 8714 * @attr ref android.R.styleable#View_nextClusterForward 8715 */ 8716 public int getNextClusterForwardId() { 8717 return mNextClusterForwardId; 8718 } 8719 8720 /** 8721 * Sets the id of the view to use as the root of the next keyboard navigation cluster. 8722 * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should 8723 * decide automatically. 8724 * 8725 * @attr ref android.R.styleable#View_nextClusterForward 8726 */ 8727 public void setNextClusterForwardId(int nextClusterForwardId) { 8728 mNextClusterForwardId = nextClusterForwardId; 8729 } 8730 8731 /** 8732 * Returns the visibility of this view and all of its ancestors 8733 * 8734 * @return True if this view and all of its ancestors are {@link #VISIBLE} 8735 */ 8736 public boolean isShown() { 8737 View current = this; 8738 //noinspection ConstantConditions 8739 do { 8740 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8741 return false; 8742 } 8743 ViewParent parent = current.mParent; 8744 if (parent == null) { 8745 return false; // We are not attached to the view root 8746 } 8747 if (!(parent instanceof View)) { 8748 return true; 8749 } 8750 current = (View) parent; 8751 } while (current != null); 8752 8753 return false; 8754 } 8755 8756 /** 8757 * Called by the view hierarchy when the content insets for a window have 8758 * changed, to allow it to adjust its content to fit within those windows. 8759 * The content insets tell you the space that the status bar, input method, 8760 * and other system windows infringe on the application's window. 8761 * 8762 * <p>You do not normally need to deal with this function, since the default 8763 * window decoration given to applications takes care of applying it to the 8764 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 8765 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 8766 * and your content can be placed under those system elements. You can then 8767 * use this method within your view hierarchy if you have parts of your UI 8768 * which you would like to ensure are not being covered. 8769 * 8770 * <p>The default implementation of this method simply applies the content 8771 * insets to the view's padding, consuming that content (modifying the 8772 * insets to be 0), and returning true. This behavior is off by default, but can 8773 * be enabled through {@link #setFitsSystemWindows(boolean)}. 8774 * 8775 * <p>This function's traversal down the hierarchy is depth-first. The same content 8776 * insets object is propagated down the hierarchy, so any changes made to it will 8777 * be seen by all following views (including potentially ones above in 8778 * the hierarchy since this is a depth-first traversal). The first view 8779 * that returns true will abort the entire traversal. 8780 * 8781 * <p>The default implementation works well for a situation where it is 8782 * used with a container that covers the entire window, allowing it to 8783 * apply the appropriate insets to its content on all edges. If you need 8784 * a more complicated layout (such as two different views fitting system 8785 * windows, one on the top of the window, and one on the bottom), 8786 * you can override the method and handle the insets however you would like. 8787 * Note that the insets provided by the framework are always relative to the 8788 * far edges of the window, not accounting for the location of the called view 8789 * within that window. (In fact when this method is called you do not yet know 8790 * where the layout will place the view, as it is done before layout happens.) 8791 * 8792 * <p>Note: unlike many View methods, there is no dispatch phase to this 8793 * call. If you are overriding it in a ViewGroup and want to allow the 8794 * call to continue to your children, you must be sure to call the super 8795 * implementation. 8796 * 8797 * <p>Here is a sample layout that makes use of fitting system windows 8798 * to have controls for a video view placed inside of the window decorations 8799 * that it hides and shows. This can be used with code like the second 8800 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 8801 * 8802 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 8803 * 8804 * @param insets Current content insets of the window. Prior to 8805 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 8806 * the insets or else you and Android will be unhappy. 8807 * 8808 * @return {@code true} if this view applied the insets and it should not 8809 * continue propagating further down the hierarchy, {@code false} otherwise. 8810 * @see #getFitsSystemWindows() 8811 * @see #setFitsSystemWindows(boolean) 8812 * @see #setSystemUiVisibility(int) 8813 * 8814 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 8815 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 8816 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 8817 * to implement handling their own insets. 8818 */ 8819 @Deprecated 8820 protected boolean fitSystemWindows(Rect insets) { 8821 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 8822 if (insets == null) { 8823 // Null insets by definition have already been consumed. 8824 // This call cannot apply insets since there are none to apply, 8825 // so return false. 8826 return false; 8827 } 8828 // If we're not in the process of dispatching the newer apply insets call, 8829 // that means we're not in the compatibility path. Dispatch into the newer 8830 // apply insets path and take things from there. 8831 try { 8832 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 8833 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 8834 } finally { 8835 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 8836 } 8837 } else { 8838 // We're being called from the newer apply insets path. 8839 // Perform the standard fallback behavior. 8840 return fitSystemWindowsInt(insets); 8841 } 8842 } 8843 8844 private boolean fitSystemWindowsInt(Rect insets) { 8845 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 8846 mUserPaddingStart = UNDEFINED_PADDING; 8847 mUserPaddingEnd = UNDEFINED_PADDING; 8848 Rect localInsets = sThreadLocal.get(); 8849 if (localInsets == null) { 8850 localInsets = new Rect(); 8851 sThreadLocal.set(localInsets); 8852 } 8853 boolean res = computeFitSystemWindows(insets, localInsets); 8854 mUserPaddingLeftInitial = localInsets.left; 8855 mUserPaddingRightInitial = localInsets.right; 8856 internalSetPadding(localInsets.left, localInsets.top, 8857 localInsets.right, localInsets.bottom); 8858 return res; 8859 } 8860 return false; 8861 } 8862 8863 /** 8864 * Called when the view should apply {@link WindowInsets} according to its internal policy. 8865 * 8866 * <p>This method should be overridden by views that wish to apply a policy different from or 8867 * in addition to the default behavior. Clients that wish to force a view subtree 8868 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 8869 * 8870 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 8871 * it will be called during dispatch instead of this method. The listener may optionally 8872 * call this method from its own implementation if it wishes to apply the view's default 8873 * insets policy in addition to its own.</p> 8874 * 8875 * <p>Implementations of this method should either return the insets parameter unchanged 8876 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 8877 * that this view applied itself. This allows new inset types added in future platform 8878 * versions to pass through existing implementations unchanged without being erroneously 8879 * consumed.</p> 8880 * 8881 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 8882 * property is set then the view will consume the system window insets and apply them 8883 * as padding for the view.</p> 8884 * 8885 * @param insets Insets to apply 8886 * @return The supplied insets with any applied insets consumed 8887 */ 8888 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 8889 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 8890 // We weren't called from within a direct call to fitSystemWindows, 8891 // call into it as a fallback in case we're in a class that overrides it 8892 // and has logic to perform. 8893 if (fitSystemWindows(insets.getSystemWindowInsets())) { 8894 return insets.consumeSystemWindowInsets(); 8895 } 8896 } else { 8897 // We were called from within a direct call to fitSystemWindows. 8898 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 8899 return insets.consumeSystemWindowInsets(); 8900 } 8901 } 8902 return insets; 8903 } 8904 8905 /** 8906 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 8907 * window insets to this view. The listener's 8908 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 8909 * method will be called instead of the view's 8910 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 8911 * 8912 * @param listener Listener to set 8913 * 8914 * @see #onApplyWindowInsets(WindowInsets) 8915 */ 8916 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 8917 getListenerInfo().mOnApplyWindowInsetsListener = listener; 8918 } 8919 8920 /** 8921 * Request to apply the given window insets to this view or another view in its subtree. 8922 * 8923 * <p>This method should be called by clients wishing to apply insets corresponding to areas 8924 * obscured by window decorations or overlays. This can include the status and navigation bars, 8925 * action bars, input methods and more. New inset categories may be added in the future. 8926 * The method returns the insets provided minus any that were applied by this view or its 8927 * children.</p> 8928 * 8929 * <p>Clients wishing to provide custom behavior should override the 8930 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 8931 * {@link OnApplyWindowInsetsListener} via the 8932 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 8933 * method.</p> 8934 * 8935 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 8936 * </p> 8937 * 8938 * @param insets Insets to apply 8939 * @return The provided insets minus the insets that were consumed 8940 */ 8941 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 8942 try { 8943 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 8944 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 8945 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 8946 } else { 8947 return onApplyWindowInsets(insets); 8948 } 8949 } finally { 8950 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 8951 } 8952 } 8953 8954 /** 8955 * Compute the view's coordinate within the surface. 8956 * 8957 * <p>Computes the coordinates of this view in its surface. The argument 8958 * must be an array of two integers. After the method returns, the array 8959 * contains the x and y location in that order.</p> 8960 * @hide 8961 * @param location an array of two integers in which to hold the coordinates 8962 */ 8963 public void getLocationInSurface(@Size(2) int[] location) { 8964 getLocationInWindow(location); 8965 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 8966 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 8967 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 8968 } 8969 } 8970 8971 /** 8972 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 8973 * only available if the view is attached. 8974 * 8975 * @return WindowInsets from the top of the view hierarchy or null if View is detached 8976 */ 8977 public WindowInsets getRootWindowInsets() { 8978 if (mAttachInfo != null) { 8979 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 8980 } 8981 return null; 8982 } 8983 8984 /** 8985 * @hide Compute the insets that should be consumed by this view and the ones 8986 * that should propagate to those under it. 8987 */ 8988 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 8989 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 8990 || mAttachInfo == null 8991 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 8992 && !mAttachInfo.mOverscanRequested)) { 8993 outLocalInsets.set(inoutInsets); 8994 inoutInsets.set(0, 0, 0, 0); 8995 return true; 8996 } else { 8997 // The application wants to take care of fitting system window for 8998 // the content... however we still need to take care of any overscan here. 8999 final Rect overscan = mAttachInfo.mOverscanInsets; 9000 outLocalInsets.set(overscan); 9001 inoutInsets.left -= overscan.left; 9002 inoutInsets.top -= overscan.top; 9003 inoutInsets.right -= overscan.right; 9004 inoutInsets.bottom -= overscan.bottom; 9005 return false; 9006 } 9007 } 9008 9009 /** 9010 * Compute insets that should be consumed by this view and the ones that should propagate 9011 * to those under it. 9012 * 9013 * @param in Insets currently being processed by this View, likely received as a parameter 9014 * to {@link #onApplyWindowInsets(WindowInsets)}. 9015 * @param outLocalInsets A Rect that will receive the insets that should be consumed 9016 * by this view 9017 * @return Insets that should be passed along to views under this one 9018 */ 9019 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 9020 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 9021 || mAttachInfo == null 9022 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 9023 outLocalInsets.set(in.getSystemWindowInsets()); 9024 return in.consumeSystemWindowInsets(); 9025 } else { 9026 outLocalInsets.set(0, 0, 0, 0); 9027 return in; 9028 } 9029 } 9030 9031 /** 9032 * Sets whether or not this view should account for system screen decorations 9033 * such as the status bar and inset its content; that is, controlling whether 9034 * the default implementation of {@link #fitSystemWindows(Rect)} will be 9035 * executed. See that method for more details. 9036 * 9037 * <p>Note that if you are providing your own implementation of 9038 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 9039 * flag to true -- your implementation will be overriding the default 9040 * implementation that checks this flag. 9041 * 9042 * @param fitSystemWindows If true, then the default implementation of 9043 * {@link #fitSystemWindows(Rect)} will be executed. 9044 * 9045 * @attr ref android.R.styleable#View_fitsSystemWindows 9046 * @see #getFitsSystemWindows() 9047 * @see #fitSystemWindows(Rect) 9048 * @see #setSystemUiVisibility(int) 9049 */ 9050 public void setFitsSystemWindows(boolean fitSystemWindows) { 9051 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 9052 } 9053 9054 /** 9055 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 9056 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 9057 * will be executed. 9058 * 9059 * @return {@code true} if the default implementation of 9060 * {@link #fitSystemWindows(Rect)} will be executed. 9061 * 9062 * @attr ref android.R.styleable#View_fitsSystemWindows 9063 * @see #setFitsSystemWindows(boolean) 9064 * @see #fitSystemWindows(Rect) 9065 * @see #setSystemUiVisibility(int) 9066 */ 9067 @ViewDebug.ExportedProperty 9068 public boolean getFitsSystemWindows() { 9069 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 9070 } 9071 9072 /** @hide */ 9073 public boolean fitsSystemWindows() { 9074 return getFitsSystemWindows(); 9075 } 9076 9077 /** 9078 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 9079 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 9080 */ 9081 @Deprecated 9082 public void requestFitSystemWindows() { 9083 if (mParent != null) { 9084 mParent.requestFitSystemWindows(); 9085 } 9086 } 9087 9088 /** 9089 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 9090 */ 9091 public void requestApplyInsets() { 9092 requestFitSystemWindows(); 9093 } 9094 9095 /** 9096 * For use by PhoneWindow to make its own system window fitting optional. 9097 * @hide 9098 */ 9099 public void makeOptionalFitsSystemWindows() { 9100 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 9101 } 9102 9103 /** 9104 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 9105 * treat them as such. 9106 * @hide 9107 */ 9108 public void getOutsets(Rect outOutsetRect) { 9109 if (mAttachInfo != null) { 9110 outOutsetRect.set(mAttachInfo.mOutsets); 9111 } else { 9112 outOutsetRect.setEmpty(); 9113 } 9114 } 9115 9116 /** 9117 * Returns the visibility status for this view. 9118 * 9119 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9120 * @attr ref android.R.styleable#View_visibility 9121 */ 9122 @ViewDebug.ExportedProperty(mapping = { 9123 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 9124 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 9125 @ViewDebug.IntToString(from = GONE, to = "GONE") 9126 }) 9127 @Visibility 9128 public int getVisibility() { 9129 return mViewFlags & VISIBILITY_MASK; 9130 } 9131 9132 /** 9133 * Set the visibility state of this view. 9134 * 9135 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9136 * @attr ref android.R.styleable#View_visibility 9137 */ 9138 @RemotableViewMethod 9139 public void setVisibility(@Visibility int visibility) { 9140 setFlags(visibility, VISIBILITY_MASK); 9141 } 9142 9143 /** 9144 * Returns the enabled status for this view. The interpretation of the 9145 * enabled state varies by subclass. 9146 * 9147 * @return True if this view is enabled, false otherwise. 9148 */ 9149 @ViewDebug.ExportedProperty 9150 public boolean isEnabled() { 9151 return (mViewFlags & ENABLED_MASK) == ENABLED; 9152 } 9153 9154 /** 9155 * Set the enabled state of this view. The interpretation of the enabled 9156 * state varies by subclass. 9157 * 9158 * @param enabled True if this view is enabled, false otherwise. 9159 */ 9160 @RemotableViewMethod 9161 public void setEnabled(boolean enabled) { 9162 if (enabled == isEnabled()) return; 9163 9164 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 9165 9166 /* 9167 * The View most likely has to change its appearance, so refresh 9168 * the drawable state. 9169 */ 9170 refreshDrawableState(); 9171 9172 // Invalidate too, since the default behavior for views is to be 9173 // be drawn at 50% alpha rather than to change the drawable. 9174 invalidate(true); 9175 9176 if (!enabled) { 9177 cancelPendingInputEvents(); 9178 } 9179 } 9180 9181 /** 9182 * Set whether this view can receive the focus. 9183 * <p> 9184 * Setting this to false will also ensure that this view is not focusable 9185 * in touch mode. 9186 * 9187 * @param focusable If true, this view can receive the focus. 9188 * 9189 * @see #setFocusableInTouchMode(boolean) 9190 * @see #setFocusable(int) 9191 * @attr ref android.R.styleable#View_focusable 9192 */ 9193 public void setFocusable(boolean focusable) { 9194 setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE); 9195 } 9196 9197 /** 9198 * Sets whether this view can receive focus. 9199 * <p> 9200 * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability 9201 * automatically based on the view's interactivity. This is the default. 9202 * <p> 9203 * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable 9204 * in touch mode. 9205 * 9206 * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, 9207 * or {@link #FOCUSABLE_AUTO}. 9208 * @see #setFocusableInTouchMode(boolean) 9209 * @attr ref android.R.styleable#View_focusable 9210 */ 9211 public void setFocusable(@Focusable int focusable) { 9212 if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) { 9213 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 9214 } 9215 setFlags(focusable, FOCUSABLE_MASK); 9216 } 9217 9218 /** 9219 * Set whether this view can receive focus while in touch mode. 9220 * 9221 * Setting this to true will also ensure that this view is focusable. 9222 * 9223 * @param focusableInTouchMode If true, this view can receive the focus while 9224 * in touch mode. 9225 * 9226 * @see #setFocusable(boolean) 9227 * @attr ref android.R.styleable#View_focusableInTouchMode 9228 */ 9229 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 9230 // Focusable in touch mode should always be set before the focusable flag 9231 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 9232 // which, in touch mode, will not successfully request focus on this view 9233 // because the focusable in touch mode flag is not set 9234 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 9235 9236 // Clear FOCUSABLE_AUTO if set. 9237 if (focusableInTouchMode) { 9238 // Clears FOCUSABLE_AUTO if set. 9239 setFlags(FOCUSABLE, FOCUSABLE_MASK); 9240 } 9241 } 9242 9243 /** 9244 * Sets the hints that helps the autofill service to select the appropriate data to fill the 9245 * view. 9246 * 9247 * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set. 9248 * @attr ref android.R.styleable#View_autofillHints 9249 */ 9250 public void setAutofillHints(@Nullable String... autofillHints) { 9251 if (autofillHints == null || autofillHints.length == 0) { 9252 mAutofillHints = null; 9253 } else { 9254 mAutofillHints = autofillHints; 9255 } 9256 } 9257 9258 /** 9259 * @hide 9260 */ 9261 @TestApi 9262 public void setAutofilled(boolean isAutofilled) { 9263 boolean wasChanged = isAutofilled != isAutofilled(); 9264 9265 if (wasChanged) { 9266 if (isAutofilled) { 9267 mPrivateFlags3 |= PFLAG3_IS_AUTOFILLED; 9268 } else { 9269 mPrivateFlags3 &= ~PFLAG3_IS_AUTOFILLED; 9270 } 9271 9272 invalidate(); 9273 } 9274 } 9275 9276 /** 9277 * Set whether this view should have sound effects enabled for events such as 9278 * clicking and touching. 9279 * 9280 * <p>You may wish to disable sound effects for a view if you already play sounds, 9281 * for instance, a dial key that plays dtmf tones. 9282 * 9283 * @param soundEffectsEnabled whether sound effects are enabled for this view. 9284 * @see #isSoundEffectsEnabled() 9285 * @see #playSoundEffect(int) 9286 * @attr ref android.R.styleable#View_soundEffectsEnabled 9287 */ 9288 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 9289 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 9290 } 9291 9292 /** 9293 * @return whether this view should have sound effects enabled for events such as 9294 * clicking and touching. 9295 * 9296 * @see #setSoundEffectsEnabled(boolean) 9297 * @see #playSoundEffect(int) 9298 * @attr ref android.R.styleable#View_soundEffectsEnabled 9299 */ 9300 @ViewDebug.ExportedProperty 9301 public boolean isSoundEffectsEnabled() { 9302 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 9303 } 9304 9305 /** 9306 * Set whether this view should have haptic feedback for events such as 9307 * long presses. 9308 * 9309 * <p>You may wish to disable haptic feedback if your view already controls 9310 * its own haptic feedback. 9311 * 9312 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 9313 * @see #isHapticFeedbackEnabled() 9314 * @see #performHapticFeedback(int) 9315 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 9316 */ 9317 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 9318 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 9319 } 9320 9321 /** 9322 * @return whether this view should have haptic feedback enabled for events 9323 * long presses. 9324 * 9325 * @see #setHapticFeedbackEnabled(boolean) 9326 * @see #performHapticFeedback(int) 9327 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 9328 */ 9329 @ViewDebug.ExportedProperty 9330 public boolean isHapticFeedbackEnabled() { 9331 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 9332 } 9333 9334 /** 9335 * Returns the layout direction for this view. 9336 * 9337 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 9338 * {@link #LAYOUT_DIRECTION_RTL}, 9339 * {@link #LAYOUT_DIRECTION_INHERIT} or 9340 * {@link #LAYOUT_DIRECTION_LOCALE}. 9341 * 9342 * @attr ref android.R.styleable#View_layoutDirection 9343 * 9344 * @hide 9345 */ 9346 @ViewDebug.ExportedProperty(category = "layout", mapping = { 9347 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 9348 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 9349 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 9350 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 9351 }) 9352 @LayoutDir 9353 public int getRawLayoutDirection() { 9354 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 9355 } 9356 9357 /** 9358 * Set the layout direction for this view. This will propagate a reset of layout direction 9359 * resolution to the view's children and resolve layout direction for this view. 9360 * 9361 * @param layoutDirection the layout direction to set. Should be one of: 9362 * 9363 * {@link #LAYOUT_DIRECTION_LTR}, 9364 * {@link #LAYOUT_DIRECTION_RTL}, 9365 * {@link #LAYOUT_DIRECTION_INHERIT}, 9366 * {@link #LAYOUT_DIRECTION_LOCALE}. 9367 * 9368 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 9369 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 9370 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 9371 * 9372 * @attr ref android.R.styleable#View_layoutDirection 9373 */ 9374 @RemotableViewMethod 9375 public void setLayoutDirection(@LayoutDir int layoutDirection) { 9376 if (getRawLayoutDirection() != layoutDirection) { 9377 // Reset the current layout direction and the resolved one 9378 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 9379 resetRtlProperties(); 9380 // Set the new layout direction (filtered) 9381 mPrivateFlags2 |= 9382 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 9383 // We need to resolve all RTL properties as they all depend on layout direction 9384 resolveRtlPropertiesIfNeeded(); 9385 requestLayout(); 9386 invalidate(true); 9387 } 9388 } 9389 9390 /** 9391 * Returns the resolved layout direction for this view. 9392 * 9393 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 9394 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 9395 * 9396 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 9397 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 9398 * 9399 * @attr ref android.R.styleable#View_layoutDirection 9400 */ 9401 @ViewDebug.ExportedProperty(category = "layout", mapping = { 9402 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 9403 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 9404 }) 9405 @ResolvedLayoutDir 9406 public int getLayoutDirection() { 9407 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 9408 if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) { 9409 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 9410 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 9411 } 9412 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 9413 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 9414 } 9415 9416 /** 9417 * Indicates whether or not this view's layout is right-to-left. This is resolved from 9418 * layout attribute and/or the inherited value from the parent 9419 * 9420 * @return true if the layout is right-to-left. 9421 * 9422 * @hide 9423 */ 9424 @ViewDebug.ExportedProperty(category = "layout") 9425 public boolean isLayoutRtl() { 9426 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 9427 } 9428 9429 /** 9430 * Indicates whether the view is currently tracking transient state that the 9431 * app should not need to concern itself with saving and restoring, but that 9432 * the framework should take special note to preserve when possible. 9433 * 9434 * <p>A view with transient state cannot be trivially rebound from an external 9435 * data source, such as an adapter binding item views in a list. This may be 9436 * because the view is performing an animation, tracking user selection 9437 * of content, or similar.</p> 9438 * 9439 * @return true if the view has transient state 9440 */ 9441 @ViewDebug.ExportedProperty(category = "layout") 9442 public boolean hasTransientState() { 9443 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 9444 } 9445 9446 /** 9447 * Set whether this view is currently tracking transient state that the 9448 * framework should attempt to preserve when possible. This flag is reference counted, 9449 * so every call to setHasTransientState(true) should be paired with a later call 9450 * to setHasTransientState(false). 9451 * 9452 * <p>A view with transient state cannot be trivially rebound from an external 9453 * data source, such as an adapter binding item views in a list. This may be 9454 * because the view is performing an animation, tracking user selection 9455 * of content, or similar.</p> 9456 * 9457 * @param hasTransientState true if this view has transient state 9458 */ 9459 public void setHasTransientState(boolean hasTransientState) { 9460 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 9461 mTransientStateCount - 1; 9462 if (mTransientStateCount < 0) { 9463 mTransientStateCount = 0; 9464 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 9465 "unmatched pair of setHasTransientState calls"); 9466 } else if ((hasTransientState && mTransientStateCount == 1) || 9467 (!hasTransientState && mTransientStateCount == 0)) { 9468 // update flag if we've just incremented up from 0 or decremented down to 0 9469 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 9470 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 9471 if (mParent != null) { 9472 try { 9473 mParent.childHasTransientStateChanged(this, hasTransientState); 9474 } catch (AbstractMethodError e) { 9475 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9476 " does not fully implement ViewParent", e); 9477 } 9478 } 9479 } 9480 } 9481 9482 /** 9483 * Returns true if this view is currently attached to a window. 9484 */ 9485 public boolean isAttachedToWindow() { 9486 return mAttachInfo != null; 9487 } 9488 9489 /** 9490 * Returns true if this view has been through at least one layout since it 9491 * was last attached to or detached from a window. 9492 */ 9493 public boolean isLaidOut() { 9494 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 9495 } 9496 9497 /** 9498 * If this view doesn't do any drawing on its own, set this flag to 9499 * allow further optimizations. By default, this flag is not set on 9500 * View, but could be set on some View subclasses such as ViewGroup. 9501 * 9502 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 9503 * you should clear this flag. 9504 * 9505 * @param willNotDraw whether or not this View draw on its own 9506 */ 9507 public void setWillNotDraw(boolean willNotDraw) { 9508 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 9509 } 9510 9511 /** 9512 * Returns whether or not this View draws on its own. 9513 * 9514 * @return true if this view has nothing to draw, false otherwise 9515 */ 9516 @ViewDebug.ExportedProperty(category = "drawing") 9517 public boolean willNotDraw() { 9518 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 9519 } 9520 9521 /** 9522 * When a View's drawing cache is enabled, drawing is redirected to an 9523 * offscreen bitmap. Some views, like an ImageView, must be able to 9524 * bypass this mechanism if they already draw a single bitmap, to avoid 9525 * unnecessary usage of the memory. 9526 * 9527 * @param willNotCacheDrawing true if this view does not cache its 9528 * drawing, false otherwise 9529 */ 9530 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 9531 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 9532 } 9533 9534 /** 9535 * Returns whether or not this View can cache its drawing or not. 9536 * 9537 * @return true if this view does not cache its drawing, false otherwise 9538 */ 9539 @ViewDebug.ExportedProperty(category = "drawing") 9540 public boolean willNotCacheDrawing() { 9541 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 9542 } 9543 9544 /** 9545 * Indicates whether this view reacts to click events or not. 9546 * 9547 * @return true if the view is clickable, false otherwise 9548 * 9549 * @see #setClickable(boolean) 9550 * @attr ref android.R.styleable#View_clickable 9551 */ 9552 @ViewDebug.ExportedProperty 9553 public boolean isClickable() { 9554 return (mViewFlags & CLICKABLE) == CLICKABLE; 9555 } 9556 9557 /** 9558 * Enables or disables click events for this view. When a view 9559 * is clickable it will change its state to "pressed" on every click. 9560 * Subclasses should set the view clickable to visually react to 9561 * user's clicks. 9562 * 9563 * @param clickable true to make the view clickable, false otherwise 9564 * 9565 * @see #isClickable() 9566 * @attr ref android.R.styleable#View_clickable 9567 */ 9568 public void setClickable(boolean clickable) { 9569 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 9570 } 9571 9572 /** 9573 * Indicates whether this view reacts to long click events or not. 9574 * 9575 * @return true if the view is long clickable, false otherwise 9576 * 9577 * @see #setLongClickable(boolean) 9578 * @attr ref android.R.styleable#View_longClickable 9579 */ 9580 public boolean isLongClickable() { 9581 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9582 } 9583 9584 /** 9585 * Enables or disables long click events for this view. When a view is long 9586 * clickable it reacts to the user holding down the button for a longer 9587 * duration than a tap. This event can either launch the listener or a 9588 * context menu. 9589 * 9590 * @param longClickable true to make the view long clickable, false otherwise 9591 * @see #isLongClickable() 9592 * @attr ref android.R.styleable#View_longClickable 9593 */ 9594 public void setLongClickable(boolean longClickable) { 9595 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 9596 } 9597 9598 /** 9599 * Indicates whether this view reacts to context clicks or not. 9600 * 9601 * @return true if the view is context clickable, false otherwise 9602 * @see #setContextClickable(boolean) 9603 * @attr ref android.R.styleable#View_contextClickable 9604 */ 9605 public boolean isContextClickable() { 9606 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 9607 } 9608 9609 /** 9610 * Enables or disables context clicking for this view. This event can launch the listener. 9611 * 9612 * @param contextClickable true to make the view react to a context click, false otherwise 9613 * @see #isContextClickable() 9614 * @attr ref android.R.styleable#View_contextClickable 9615 */ 9616 public void setContextClickable(boolean contextClickable) { 9617 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 9618 } 9619 9620 /** 9621 * Sets the pressed state for this view and provides a touch coordinate for 9622 * animation hinting. 9623 * 9624 * @param pressed Pass true to set the View's internal state to "pressed", 9625 * or false to reverts the View's internal state from a 9626 * previously set "pressed" state. 9627 * @param x The x coordinate of the touch that caused the press 9628 * @param y The y coordinate of the touch that caused the press 9629 */ 9630 private void setPressed(boolean pressed, float x, float y) { 9631 if (pressed) { 9632 drawableHotspotChanged(x, y); 9633 } 9634 9635 setPressed(pressed); 9636 } 9637 9638 /** 9639 * Sets the pressed state for this view. 9640 * 9641 * @see #isClickable() 9642 * @see #setClickable(boolean) 9643 * 9644 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 9645 * the View's internal state from a previously set "pressed" state. 9646 */ 9647 public void setPressed(boolean pressed) { 9648 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 9649 9650 if (pressed) { 9651 mPrivateFlags |= PFLAG_PRESSED; 9652 } else { 9653 mPrivateFlags &= ~PFLAG_PRESSED; 9654 } 9655 9656 if (needsRefresh) { 9657 refreshDrawableState(); 9658 } 9659 dispatchSetPressed(pressed); 9660 } 9661 9662 /** 9663 * Dispatch setPressed to all of this View's children. 9664 * 9665 * @see #setPressed(boolean) 9666 * 9667 * @param pressed The new pressed state 9668 */ 9669 protected void dispatchSetPressed(boolean pressed) { 9670 } 9671 9672 /** 9673 * Indicates whether the view is currently in pressed state. Unless 9674 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 9675 * the pressed state. 9676 * 9677 * @see #setPressed(boolean) 9678 * @see #isClickable() 9679 * @see #setClickable(boolean) 9680 * 9681 * @return true if the view is currently pressed, false otherwise 9682 */ 9683 @ViewDebug.ExportedProperty 9684 public boolean isPressed() { 9685 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 9686 } 9687 9688 /** 9689 * @hide 9690 * Indicates whether this view will participate in data collection through 9691 * {@link ViewStructure}. If true, it will not provide any data 9692 * for itself or its children. If false, the normal data collection will be allowed. 9693 * 9694 * @return Returns false if assist data collection is not blocked, else true. 9695 * 9696 * @see #setAssistBlocked(boolean) 9697 * @attr ref android.R.styleable#View_assistBlocked 9698 */ 9699 public boolean isAssistBlocked() { 9700 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 9701 } 9702 9703 /** 9704 * @hide 9705 * Controls whether assist data collection from this view and its children is enabled 9706 * (that is, whether {@link #onProvideStructure} and 9707 * {@link #onProvideVirtualStructure} will be called). The default value is false, 9708 * allowing normal assist collection. Setting this to false will disable assist collection. 9709 * 9710 * @param enabled Set to true to <em>disable</em> assist data collection, or false 9711 * (the default) to allow it. 9712 * 9713 * @see #isAssistBlocked() 9714 * @see #onProvideStructure 9715 * @see #onProvideVirtualStructure 9716 * @attr ref android.R.styleable#View_assistBlocked 9717 */ 9718 public void setAssistBlocked(boolean enabled) { 9719 if (enabled) { 9720 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 9721 } else { 9722 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 9723 } 9724 } 9725 9726 /** 9727 * Indicates whether this view will save its state (that is, 9728 * whether its {@link #onSaveInstanceState} method will be called). 9729 * 9730 * @return Returns true if the view state saving is enabled, else false. 9731 * 9732 * @see #setSaveEnabled(boolean) 9733 * @attr ref android.R.styleable#View_saveEnabled 9734 */ 9735 public boolean isSaveEnabled() { 9736 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 9737 } 9738 9739 /** 9740 * Controls whether the saving of this view's state is 9741 * enabled (that is, whether its {@link #onSaveInstanceState} method 9742 * will be called). Note that even if freezing is enabled, the 9743 * view still must have an id assigned to it (via {@link #setId(int)}) 9744 * for its state to be saved. This flag can only disable the 9745 * saving of this view; any child views may still have their state saved. 9746 * 9747 * @param enabled Set to false to <em>disable</em> state saving, or true 9748 * (the default) to allow it. 9749 * 9750 * @see #isSaveEnabled() 9751 * @see #setId(int) 9752 * @see #onSaveInstanceState() 9753 * @attr ref android.R.styleable#View_saveEnabled 9754 */ 9755 public void setSaveEnabled(boolean enabled) { 9756 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 9757 } 9758 9759 /** 9760 * Gets whether the framework should discard touches when the view's 9761 * window is obscured by another visible window. 9762 * Refer to the {@link View} security documentation for more details. 9763 * 9764 * @return True if touch filtering is enabled. 9765 * 9766 * @see #setFilterTouchesWhenObscured(boolean) 9767 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9768 */ 9769 @ViewDebug.ExportedProperty 9770 public boolean getFilterTouchesWhenObscured() { 9771 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 9772 } 9773 9774 /** 9775 * Sets whether the framework should discard touches when the view's 9776 * window is obscured by another visible window. 9777 * Refer to the {@link View} security documentation for more details. 9778 * 9779 * @param enabled True if touch filtering should be enabled. 9780 * 9781 * @see #getFilterTouchesWhenObscured 9782 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9783 */ 9784 public void setFilterTouchesWhenObscured(boolean enabled) { 9785 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 9786 FILTER_TOUCHES_WHEN_OBSCURED); 9787 } 9788 9789 /** 9790 * Indicates whether the entire hierarchy under this view will save its 9791 * state when a state saving traversal occurs from its parent. The default 9792 * is true; if false, these views will not be saved unless 9793 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9794 * 9795 * @return Returns true if the view state saving from parent is enabled, else false. 9796 * 9797 * @see #setSaveFromParentEnabled(boolean) 9798 */ 9799 public boolean isSaveFromParentEnabled() { 9800 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 9801 } 9802 9803 /** 9804 * Controls whether the entire hierarchy under this view will save its 9805 * state when a state saving traversal occurs from its parent. The default 9806 * is true; if false, these views will not be saved unless 9807 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9808 * 9809 * @param enabled Set to false to <em>disable</em> state saving, or true 9810 * (the default) to allow it. 9811 * 9812 * @see #isSaveFromParentEnabled() 9813 * @see #setId(int) 9814 * @see #onSaveInstanceState() 9815 */ 9816 public void setSaveFromParentEnabled(boolean enabled) { 9817 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 9818 } 9819 9820 9821 /** 9822 * Returns whether this View is currently able to take focus. 9823 * 9824 * @return True if this view can take focus, or false otherwise. 9825 */ 9826 @ViewDebug.ExportedProperty(category = "focus") 9827 public final boolean isFocusable() { 9828 return FOCUSABLE == (mViewFlags & FOCUSABLE); 9829 } 9830 9831 /** 9832 * Returns the focusable setting for this view. 9833 * 9834 * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}. 9835 * @attr ref android.R.styleable#View_focusable 9836 */ 9837 @ViewDebug.ExportedProperty(mapping = { 9838 @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"), 9839 @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"), 9840 @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO") 9841 }, category = "focus") 9842 @Focusable 9843 public int getFocusable() { 9844 return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE; 9845 } 9846 9847 /** 9848 * When a view is focusable, it may not want to take focus when in touch mode. 9849 * For example, a button would like focus when the user is navigating via a D-pad 9850 * so that the user can click on it, but once the user starts touching the screen, 9851 * the button shouldn't take focus 9852 * @return Whether the view is focusable in touch mode. 9853 * @attr ref android.R.styleable#View_focusableInTouchMode 9854 */ 9855 @ViewDebug.ExportedProperty(category = "focus") 9856 public final boolean isFocusableInTouchMode() { 9857 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 9858 } 9859 9860 /** 9861 * Find the nearest view in the specified direction that can take focus. 9862 * This does not actually give focus to that view. 9863 * 9864 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9865 * 9866 * @return The nearest focusable in the specified direction, or null if none 9867 * can be found. 9868 */ 9869 public View focusSearch(@FocusRealDirection int direction) { 9870 if (mParent != null) { 9871 return mParent.focusSearch(this, direction); 9872 } else { 9873 return null; 9874 } 9875 } 9876 9877 /** 9878 * Returns whether this View is a root of a keyboard navigation cluster. 9879 * 9880 * @return True if this view is a root of a cluster, or false otherwise. 9881 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9882 */ 9883 @ViewDebug.ExportedProperty(category = "focus") 9884 public final boolean isKeyboardNavigationCluster() { 9885 return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0; 9886 } 9887 9888 /** 9889 * Searches up the view hierarchy to find the top-most cluster. All deeper/nested clusters 9890 * will be ignored. 9891 * 9892 * @return the keyboard navigation cluster that this view is in (can be this view) 9893 * or {@code null} if not in one 9894 */ 9895 View findKeyboardNavigationCluster() { 9896 if (mParent instanceof View) { 9897 View cluster = ((View) mParent).findKeyboardNavigationCluster(); 9898 if (cluster != null) { 9899 return cluster; 9900 } else if (isKeyboardNavigationCluster()) { 9901 return this; 9902 } 9903 } 9904 return null; 9905 } 9906 9907 /** 9908 * Set whether this view is a root of a keyboard navigation cluster. 9909 * 9910 * @param isCluster If true, this view is a root of a cluster. 9911 * 9912 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9913 */ 9914 public void setKeyboardNavigationCluster(boolean isCluster) { 9915 if (isCluster) { 9916 mPrivateFlags3 |= PFLAG3_CLUSTER; 9917 } else { 9918 mPrivateFlags3 &= ~PFLAG3_CLUSTER; 9919 } 9920 } 9921 9922 /** 9923 * Sets this View as the one which receives focus the next time cluster navigation jumps 9924 * to the cluster containing this View. This does NOT change focus even if the cluster 9925 * containing this view is current. 9926 * 9927 * @hide 9928 */ 9929 public final void setFocusedInCluster() { 9930 setFocusedInCluster(findKeyboardNavigationCluster()); 9931 } 9932 9933 private void setFocusedInCluster(View cluster) { 9934 if (this instanceof ViewGroup) { 9935 ((ViewGroup) this).mFocusedInCluster = null; 9936 } 9937 if (cluster == this) { 9938 return; 9939 } 9940 ViewParent parent = mParent; 9941 View child = this; 9942 while (parent instanceof ViewGroup) { 9943 ((ViewGroup) parent).mFocusedInCluster = child; 9944 if (parent == cluster) { 9945 break; 9946 } 9947 child = (View) parent; 9948 parent = parent.getParent(); 9949 } 9950 } 9951 9952 private void updateFocusedInCluster(View oldFocus, @FocusDirection int direction) { 9953 if (oldFocus != null) { 9954 View oldCluster = oldFocus.findKeyboardNavigationCluster(); 9955 View cluster = findKeyboardNavigationCluster(); 9956 if (oldCluster != cluster) { 9957 // Going from one cluster to another, so save last-focused. 9958 // This covers cluster jumps because they are always FOCUS_DOWN 9959 oldFocus.setFocusedInCluster(oldCluster); 9960 if (direction == FOCUS_FORWARD || direction == FOCUS_BACKWARD) { 9961 // This is a result of ordered navigation so consider navigation through 9962 // the previous cluster "complete" and clear its last-focused memory. 9963 if (oldFocus.mParent instanceof ViewGroup) { 9964 ((ViewGroup) oldFocus.mParent).clearFocusedInCluster(oldFocus); 9965 } 9966 } 9967 } 9968 } 9969 } 9970 9971 /** 9972 * Returns whether this View should receive focus when the focus is restored for the view 9973 * hierarchy containing this view. 9974 * <p> 9975 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9976 * window or serves as a target of cluster navigation. 9977 * 9978 * @see #restoreDefaultFocus() 9979 * 9980 * @return {@code true} if this view is the default-focus view, {@code false} otherwise 9981 * @attr ref android.R.styleable#View_focusedByDefault 9982 */ 9983 @ViewDebug.ExportedProperty(category = "focus") 9984 public final boolean isFocusedByDefault() { 9985 return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0; 9986 } 9987 9988 /** 9989 * Sets whether this View should receive focus when the focus is restored for the view 9990 * hierarchy containing this view. 9991 * <p> 9992 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9993 * window or serves as a target of cluster navigation. 9994 * 9995 * @param isFocusedByDefault {@code true} to set this view as the default-focus view, 9996 * {@code false} otherwise. 9997 * 9998 * @see #restoreDefaultFocus() 9999 * 10000 * @attr ref android.R.styleable#View_focusedByDefault 10001 */ 10002 public void setFocusedByDefault(boolean isFocusedByDefault) { 10003 if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) { 10004 return; 10005 } 10006 10007 if (isFocusedByDefault) { 10008 mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT; 10009 } else { 10010 mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT; 10011 } 10012 10013 if (mParent instanceof ViewGroup) { 10014 if (isFocusedByDefault) { 10015 ((ViewGroup) mParent).setDefaultFocus(this); 10016 } else { 10017 ((ViewGroup) mParent).clearDefaultFocus(this); 10018 } 10019 } 10020 } 10021 10022 /** 10023 * Returns whether the view hierarchy with this view as a root contain a default-focus view. 10024 * 10025 * @return {@code true} if this view has default focus, {@code false} otherwise 10026 */ 10027 boolean hasDefaultFocus() { 10028 return isFocusedByDefault(); 10029 } 10030 10031 /** 10032 * Find the nearest keyboard navigation cluster in the specified direction. 10033 * This does not actually give focus to that cluster. 10034 * 10035 * @param currentCluster The starting point of the search. Null means the current cluster is not 10036 * found yet 10037 * @param direction Direction to look 10038 * 10039 * @return The nearest keyboard navigation cluster in the specified direction, or null if none 10040 * can be found 10041 */ 10042 public View keyboardNavigationClusterSearch(View currentCluster, 10043 @FocusDirection int direction) { 10044 if (isKeyboardNavigationCluster()) { 10045 currentCluster = this; 10046 } 10047 if (isRootNamespace()) { 10048 // Root namespace means we should consider ourselves the top of the 10049 // tree for group searching; otherwise we could be group searching 10050 // into other tabs. see LocalActivityManager and TabHost for more info. 10051 return FocusFinder.getInstance().findNextKeyboardNavigationCluster( 10052 this, currentCluster, direction); 10053 } else if (mParent != null) { 10054 return mParent.keyboardNavigationClusterSearch(currentCluster, direction); 10055 } 10056 return null; 10057 } 10058 10059 /** 10060 * This method is the last chance for the focused view and its ancestors to 10061 * respond to an arrow key. This is called when the focused view did not 10062 * consume the key internally, nor could the view system find a new view in 10063 * the requested direction to give focus to. 10064 * 10065 * @param focused The currently focused view. 10066 * @param direction The direction focus wants to move. One of FOCUS_UP, 10067 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 10068 * @return True if the this view consumed this unhandled move. 10069 */ 10070 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 10071 return false; 10072 } 10073 10074 /** 10075 * Sets whether this View should use a default focus highlight when it gets focused but doesn't 10076 * have {@link android.R.attr#state_focused} defined in its background. 10077 * 10078 * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus 10079 * highlight, {@code false} otherwise. 10080 * 10081 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 10082 */ 10083 public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) { 10084 mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled; 10085 } 10086 10087 /** 10088 10089 /** 10090 * Returns whether this View should use a default focus highlight when it gets focused but 10091 * doesn't have {@link android.R.attr#state_focused} defined in its background. 10092 * 10093 * @return True if this View should use a default focus highlight. 10094 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 10095 */ 10096 @ViewDebug.ExportedProperty(category = "focus") 10097 public final boolean getDefaultFocusHighlightEnabled() { 10098 return mDefaultFocusHighlightEnabled; 10099 } 10100 10101 /** 10102 * If a user manually specified the next view id for a particular direction, 10103 * use the root to look up the view. 10104 * @param root The root view of the hierarchy containing this view. 10105 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 10106 * or FOCUS_BACKWARD. 10107 * @return The user specified next view, or null if there is none. 10108 */ 10109 View findUserSetNextFocus(View root, @FocusDirection int direction) { 10110 switch (direction) { 10111 case FOCUS_LEFT: 10112 if (mNextFocusLeftId == View.NO_ID) return null; 10113 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 10114 case FOCUS_RIGHT: 10115 if (mNextFocusRightId == View.NO_ID) return null; 10116 return findViewInsideOutShouldExist(root, mNextFocusRightId); 10117 case FOCUS_UP: 10118 if (mNextFocusUpId == View.NO_ID) return null; 10119 return findViewInsideOutShouldExist(root, mNextFocusUpId); 10120 case FOCUS_DOWN: 10121 if (mNextFocusDownId == View.NO_ID) return null; 10122 return findViewInsideOutShouldExist(root, mNextFocusDownId); 10123 case FOCUS_FORWARD: 10124 if (mNextFocusForwardId == View.NO_ID) return null; 10125 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 10126 case FOCUS_BACKWARD: { 10127 if (mID == View.NO_ID) return null; 10128 final int id = mID; 10129 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 10130 @Override 10131 public boolean test(View t) { 10132 return t.mNextFocusForwardId == id; 10133 } 10134 }); 10135 } 10136 } 10137 return null; 10138 } 10139 10140 /** 10141 * If a user manually specified the next keyboard-navigation cluster for a particular direction, 10142 * use the root to look up the view. 10143 * 10144 * @param root the root view of the hierarchy containing this view 10145 * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD} 10146 * @return the user-specified next cluster, or {@code null} if there is none 10147 */ 10148 View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) { 10149 switch (direction) { 10150 case FOCUS_FORWARD: 10151 if (mNextClusterForwardId == View.NO_ID) return null; 10152 return findViewInsideOutShouldExist(root, mNextClusterForwardId); 10153 case FOCUS_BACKWARD: { 10154 if (mID == View.NO_ID) return null; 10155 final int id = mID; 10156 return root.findViewByPredicateInsideOut(this, 10157 (Predicate<View>) t -> t.mNextClusterForwardId == id); 10158 } 10159 } 10160 return null; 10161 } 10162 10163 private View findViewInsideOutShouldExist(View root, int id) { 10164 if (mMatchIdPredicate == null) { 10165 mMatchIdPredicate = new MatchIdPredicate(); 10166 } 10167 mMatchIdPredicate.mId = id; 10168 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 10169 if (result == null) { 10170 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 10171 } 10172 return result; 10173 } 10174 10175 /** 10176 * Find and return all focusable views that are descendants of this view, 10177 * possibly including this view if it is focusable itself. 10178 * 10179 * @param direction The direction of the focus 10180 * @return A list of focusable views 10181 */ 10182 public ArrayList<View> getFocusables(@FocusDirection int direction) { 10183 ArrayList<View> result = new ArrayList<View>(24); 10184 addFocusables(result, direction); 10185 return result; 10186 } 10187 10188 /** 10189 * Add any focusable views that are descendants of this view (possibly 10190 * including this view if it is focusable itself) to views. If we are in touch mode, 10191 * only add views that are also focusable in touch mode. 10192 * 10193 * @param views Focusable views found so far 10194 * @param direction The direction of the focus 10195 */ 10196 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 10197 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 10198 } 10199 10200 /** 10201 * Adds any focusable views that are descendants of this view (possibly 10202 * including this view if it is focusable itself) to views. This method 10203 * adds all focusable views regardless if we are in touch mode or 10204 * only views focusable in touch mode if we are in touch mode or 10205 * only views that can take accessibility focus if accessibility is enabled 10206 * depending on the focusable mode parameter. 10207 * 10208 * @param views Focusable views found so far or null if all we are interested is 10209 * the number of focusables. 10210 * @param direction The direction of the focus. 10211 * @param focusableMode The type of focusables to be added. 10212 * 10213 * @see #FOCUSABLES_ALL 10214 * @see #FOCUSABLES_TOUCH_MODE 10215 */ 10216 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 10217 @FocusableMode int focusableMode) { 10218 if (views == null) { 10219 return; 10220 } 10221 if (!isFocusable()) { 10222 return; 10223 } 10224 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 10225 && !isFocusableInTouchMode()) { 10226 return; 10227 } 10228 views.add(this); 10229 } 10230 10231 /** 10232 * Adds any keyboard navigation cluster roots that are descendants of this view (possibly 10233 * including this view if it is a cluster root itself) to views. 10234 * 10235 * @param views Keyboard navigation cluster roots found so far 10236 * @param direction Direction to look 10237 */ 10238 public void addKeyboardNavigationClusters( 10239 @NonNull Collection<View> views, 10240 int direction) { 10241 if (!isKeyboardNavigationCluster()) { 10242 return; 10243 } 10244 if (!hasFocusable()) { 10245 return; 10246 } 10247 views.add(this); 10248 } 10249 10250 /** 10251 * Finds the Views that contain given text. The containment is case insensitive. 10252 * The search is performed by either the text that the View renders or the content 10253 * description that describes the view for accessibility purposes and the view does 10254 * not render or both. Clients can specify how the search is to be performed via 10255 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 10256 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 10257 * 10258 * @param outViews The output list of matching Views. 10259 * @param searched The text to match against. 10260 * 10261 * @see #FIND_VIEWS_WITH_TEXT 10262 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 10263 * @see #setContentDescription(CharSequence) 10264 */ 10265 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 10266 @FindViewFlags int flags) { 10267 if (getAccessibilityNodeProvider() != null) { 10268 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 10269 outViews.add(this); 10270 } 10271 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 10272 && (searched != null && searched.length() > 0) 10273 && (mContentDescription != null && mContentDescription.length() > 0)) { 10274 String searchedLowerCase = searched.toString().toLowerCase(); 10275 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 10276 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 10277 outViews.add(this); 10278 } 10279 } 10280 } 10281 10282 /** 10283 * Find and return all touchable views that are descendants of this view, 10284 * possibly including this view if it is touchable itself. 10285 * 10286 * @return A list of touchable views 10287 */ 10288 public ArrayList<View> getTouchables() { 10289 ArrayList<View> result = new ArrayList<View>(); 10290 addTouchables(result); 10291 return result; 10292 } 10293 10294 /** 10295 * Add any touchable views that are descendants of this view (possibly 10296 * including this view if it is touchable itself) to views. 10297 * 10298 * @param views Touchable views found so far 10299 */ 10300 public void addTouchables(ArrayList<View> views) { 10301 final int viewFlags = mViewFlags; 10302 10303 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10304 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 10305 && (viewFlags & ENABLED_MASK) == ENABLED) { 10306 views.add(this); 10307 } 10308 } 10309 10310 /** 10311 * Returns whether this View is accessibility focused. 10312 * 10313 * @return True if this View is accessibility focused. 10314 */ 10315 public boolean isAccessibilityFocused() { 10316 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 10317 } 10318 10319 /** 10320 * Call this to try to give accessibility focus to this view. 10321 * 10322 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 10323 * returns false or the view is no visible or the view already has accessibility 10324 * focus. 10325 * 10326 * See also {@link #focusSearch(int)}, which is what you call to say that you 10327 * have focus, and you want your parent to look for the next one. 10328 * 10329 * @return Whether this view actually took accessibility focus. 10330 * 10331 * @hide 10332 */ 10333 public boolean requestAccessibilityFocus() { 10334 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 10335 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 10336 return false; 10337 } 10338 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 10339 return false; 10340 } 10341 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 10342 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 10343 ViewRootImpl viewRootImpl = getViewRootImpl(); 10344 if (viewRootImpl != null) { 10345 viewRootImpl.setAccessibilityFocus(this, null); 10346 } 10347 invalidate(); 10348 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 10349 return true; 10350 } 10351 return false; 10352 } 10353 10354 /** 10355 * Call this to try to clear accessibility focus of this view. 10356 * 10357 * See also {@link #focusSearch(int)}, which is what you call to say that you 10358 * have focus, and you want your parent to look for the next one. 10359 * 10360 * @hide 10361 */ 10362 public void clearAccessibilityFocus() { 10363 clearAccessibilityFocusNoCallbacks(0); 10364 10365 // Clear the global reference of accessibility focus if this view or 10366 // any of its descendants had accessibility focus. This will NOT send 10367 // an event or update internal state if focus is cleared from a 10368 // descendant view, which may leave views in inconsistent states. 10369 final ViewRootImpl viewRootImpl = getViewRootImpl(); 10370 if (viewRootImpl != null) { 10371 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 10372 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 10373 viewRootImpl.setAccessibilityFocus(null, null); 10374 } 10375 } 10376 } 10377 10378 private void sendAccessibilityHoverEvent(int eventType) { 10379 // Since we are not delivering to a client accessibility events from not 10380 // important views (unless the clinet request that) we need to fire the 10381 // event from the deepest view exposed to the client. As a consequence if 10382 // the user crosses a not exposed view the client will see enter and exit 10383 // of the exposed predecessor followed by and enter and exit of that same 10384 // predecessor when entering and exiting the not exposed descendant. This 10385 // is fine since the client has a clear idea which view is hovered at the 10386 // price of a couple more events being sent. This is a simple and 10387 // working solution. 10388 View source = this; 10389 while (true) { 10390 if (source.includeForAccessibility()) { 10391 source.sendAccessibilityEvent(eventType); 10392 return; 10393 } 10394 ViewParent parent = source.getParent(); 10395 if (parent instanceof View) { 10396 source = (View) parent; 10397 } else { 10398 return; 10399 } 10400 } 10401 } 10402 10403 /** 10404 * Clears accessibility focus without calling any callback methods 10405 * normally invoked in {@link #clearAccessibilityFocus()}. This method 10406 * is used separately from that one for clearing accessibility focus when 10407 * giving this focus to another view. 10408 * 10409 * @param action The action, if any, that led to focus being cleared. Set to 10410 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 10411 * the window. 10412 */ 10413 void clearAccessibilityFocusNoCallbacks(int action) { 10414 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 10415 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 10416 invalidate(); 10417 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 10418 AccessibilityEvent event = AccessibilityEvent.obtain( 10419 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 10420 event.setAction(action); 10421 if (mAccessibilityDelegate != null) { 10422 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 10423 } else { 10424 sendAccessibilityEventUnchecked(event); 10425 } 10426 } 10427 } 10428 } 10429 10430 /** 10431 * Call this to try to give focus to a specific view or to one of its 10432 * descendants. 10433 * 10434 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10435 * false), or if it is focusable and it is not focusable in touch mode 10436 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10437 * 10438 * See also {@link #focusSearch(int)}, which is what you call to say that you 10439 * have focus, and you want your parent to look for the next one. 10440 * 10441 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 10442 * {@link #FOCUS_DOWN} and <code>null</code>. 10443 * 10444 * @return Whether this view or one of its descendants actually took focus. 10445 */ 10446 public final boolean requestFocus() { 10447 return requestFocus(View.FOCUS_DOWN); 10448 } 10449 10450 /** 10451 * This will request focus for whichever View was last focused within this 10452 * cluster before a focus-jump out of it. 10453 * 10454 * @hide 10455 */ 10456 @TestApi 10457 public boolean restoreFocusInCluster(@FocusRealDirection int direction) { 10458 // Prioritize focusableByDefault over algorithmic focus selection. 10459 if (restoreDefaultFocus()) { 10460 return true; 10461 } 10462 return requestFocus(direction); 10463 } 10464 10465 /** 10466 * This will request focus for whichever View not in a cluster was last focused before a 10467 * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus 10468 * the "first" focusable view it finds. 10469 * 10470 * @hide 10471 */ 10472 @TestApi 10473 public boolean restoreFocusNotInCluster() { 10474 return requestFocus(View.FOCUS_DOWN); 10475 } 10476 10477 /** 10478 * Gives focus to the default-focus view in the view hierarchy that has this view as a root. 10479 * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}. 10480 * 10481 * @return Whether this view or one of its descendants actually took focus 10482 */ 10483 public boolean restoreDefaultFocus() { 10484 return requestFocus(View.FOCUS_DOWN); 10485 } 10486 10487 /** 10488 * Call this to try to give focus to a specific view or to one of its 10489 * descendants and give it a hint about what direction focus is heading. 10490 * 10491 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10492 * false), or if it is focusable and it is not focusable in touch mode 10493 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10494 * 10495 * See also {@link #focusSearch(int)}, which is what you call to say that you 10496 * have focus, and you want your parent to look for the next one. 10497 * 10498 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 10499 * <code>null</code> set for the previously focused rectangle. 10500 * 10501 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 10502 * @return Whether this view or one of its descendants actually took focus. 10503 */ 10504 public final boolean requestFocus(int direction) { 10505 return requestFocus(direction, null); 10506 } 10507 10508 /** 10509 * Call this to try to give focus to a specific view or to one of its descendants 10510 * and give it hints about the direction and a specific rectangle that the focus 10511 * is coming from. The rectangle can help give larger views a finer grained hint 10512 * about where focus is coming from, and therefore, where to show selection, or 10513 * forward focus change internally. 10514 * 10515 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10516 * false), or if it is focusable and it is not focusable in touch mode 10517 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10518 * 10519 * A View will not take focus if it is not visible. 10520 * 10521 * A View will not take focus if one of its parents has 10522 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 10523 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 10524 * 10525 * See also {@link #focusSearch(int)}, which is what you call to say that you 10526 * have focus, and you want your parent to look for the next one. 10527 * 10528 * You may wish to override this method if your custom {@link View} has an internal 10529 * {@link View} that it wishes to forward the request to. 10530 * 10531 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 10532 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 10533 * to give a finer grained hint about where focus is coming from. May be null 10534 * if there is no hint. 10535 * @return Whether this view or one of its descendants actually took focus. 10536 */ 10537 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 10538 return requestFocusNoSearch(direction, previouslyFocusedRect); 10539 } 10540 10541 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 10542 // need to be focusable 10543 if ((mViewFlags & FOCUSABLE) != FOCUSABLE 10544 || (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 10545 return false; 10546 } 10547 10548 // need to be focusable in touch mode if in touch mode 10549 if (isInTouchMode() && 10550 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 10551 return false; 10552 } 10553 10554 // need to not have any parents blocking us 10555 if (hasAncestorThatBlocksDescendantFocus()) { 10556 return false; 10557 } 10558 10559 handleFocusGainInternal(direction, previouslyFocusedRect); 10560 return true; 10561 } 10562 10563 /** 10564 * Call this to try to give focus to a specific view or to one of its descendants. This is a 10565 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 10566 * touch mode to request focus when they are touched. 10567 * 10568 * @return Whether this view or one of its descendants actually took focus. 10569 * 10570 * @see #isInTouchMode() 10571 * 10572 */ 10573 public final boolean requestFocusFromTouch() { 10574 // Leave touch mode if we need to 10575 if (isInTouchMode()) { 10576 ViewRootImpl viewRoot = getViewRootImpl(); 10577 if (viewRoot != null) { 10578 viewRoot.ensureTouchMode(false); 10579 } 10580 } 10581 return requestFocus(View.FOCUS_DOWN); 10582 } 10583 10584 /** 10585 * @return Whether any ancestor of this view blocks descendant focus. 10586 */ 10587 private boolean hasAncestorThatBlocksDescendantFocus() { 10588 final boolean focusableInTouchMode = isFocusableInTouchMode(); 10589 ViewParent ancestor = mParent; 10590 while (ancestor instanceof ViewGroup) { 10591 final ViewGroup vgAncestor = (ViewGroup) ancestor; 10592 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 10593 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 10594 return true; 10595 } else { 10596 ancestor = vgAncestor.getParent(); 10597 } 10598 } 10599 return false; 10600 } 10601 10602 /** 10603 * Gets the mode for determining whether this View is important for accessibility. 10604 * A view is important for accessibility if it fires accessibility events and if it 10605 * is reported to accessibility services that query the screen. 10606 * 10607 * @return The mode for determining whether a view is important for accessibility, one 10608 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 10609 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 10610 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 10611 * 10612 * @attr ref android.R.styleable#View_importantForAccessibility 10613 * 10614 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 10615 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 10616 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 10617 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 10618 */ 10619 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 10620 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 10621 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 10622 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 10623 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 10624 to = "noHideDescendants") 10625 }) 10626 public int getImportantForAccessibility() { 10627 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 10628 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 10629 } 10630 10631 /** 10632 * Sets the live region mode for this view. This indicates to accessibility 10633 * services whether they should automatically notify the user about changes 10634 * to the view's content description or text, or to the content descriptions 10635 * or text of the view's children (where applicable). 10636 * <p> 10637 * For example, in a login screen with a TextView that displays an "incorrect 10638 * password" notification, that view should be marked as a live region with 10639 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 10640 * <p> 10641 * To disable change notifications for this view, use 10642 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 10643 * mode for most views. 10644 * <p> 10645 * To indicate that the user should be notified of changes, use 10646 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 10647 * <p> 10648 * If the view's changes should interrupt ongoing speech and notify the user 10649 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 10650 * 10651 * @param mode The live region mode for this view, one of: 10652 * <ul> 10653 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 10654 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 10655 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 10656 * </ul> 10657 * @attr ref android.R.styleable#View_accessibilityLiveRegion 10658 */ 10659 public void setAccessibilityLiveRegion(int mode) { 10660 if (mode != getAccessibilityLiveRegion()) { 10661 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 10662 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 10663 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 10664 notifyViewAccessibilityStateChangedIfNeeded( 10665 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10666 } 10667 } 10668 10669 /** 10670 * Gets the live region mode for this View. 10671 * 10672 * @return The live region mode for the view. 10673 * 10674 * @attr ref android.R.styleable#View_accessibilityLiveRegion 10675 * 10676 * @see #setAccessibilityLiveRegion(int) 10677 */ 10678 public int getAccessibilityLiveRegion() { 10679 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 10680 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 10681 } 10682 10683 /** 10684 * Sets how to determine whether this view is important for accessibility 10685 * which is if it fires accessibility events and if it is reported to 10686 * accessibility services that query the screen. 10687 * 10688 * @param mode How to determine whether this view is important for accessibility. 10689 * 10690 * @attr ref android.R.styleable#View_importantForAccessibility 10691 * 10692 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 10693 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 10694 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 10695 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 10696 */ 10697 public void setImportantForAccessibility(int mode) { 10698 final int oldMode = getImportantForAccessibility(); 10699 if (mode != oldMode) { 10700 final boolean hideDescendants = 10701 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 10702 10703 // If this node or its descendants are no longer important, try to 10704 // clear accessibility focus. 10705 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 10706 final View focusHost = findAccessibilityFocusHost(hideDescendants); 10707 if (focusHost != null) { 10708 focusHost.clearAccessibilityFocus(); 10709 } 10710 } 10711 10712 // If we're moving between AUTO and another state, we might not need 10713 // to send a subtree changed notification. We'll store the computed 10714 // importance, since we'll need to check it later to make sure. 10715 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 10716 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 10717 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 10718 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 10719 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 10720 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 10721 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 10722 notifySubtreeAccessibilityStateChangedIfNeeded(); 10723 } else { 10724 notifyViewAccessibilityStateChangedIfNeeded( 10725 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10726 } 10727 } 10728 } 10729 10730 /** 10731 * Returns the view within this view's hierarchy that is hosting 10732 * accessibility focus. 10733 * 10734 * @param searchDescendants whether to search for focus in descendant views 10735 * @return the view hosting accessibility focus, or {@code null} 10736 */ 10737 private View findAccessibilityFocusHost(boolean searchDescendants) { 10738 if (isAccessibilityFocusedViewOrHost()) { 10739 return this; 10740 } 10741 10742 if (searchDescendants) { 10743 final ViewRootImpl viewRoot = getViewRootImpl(); 10744 if (viewRoot != null) { 10745 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 10746 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 10747 return focusHost; 10748 } 10749 } 10750 } 10751 10752 return null; 10753 } 10754 10755 /** 10756 * Computes whether this view should be exposed for accessibility. In 10757 * general, views that are interactive or provide information are exposed 10758 * while views that serve only as containers are hidden. 10759 * <p> 10760 * If an ancestor of this view has importance 10761 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 10762 * returns <code>false</code>. 10763 * <p> 10764 * Otherwise, the value is computed according to the view's 10765 * {@link #getImportantForAccessibility()} value: 10766 * <ol> 10767 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 10768 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 10769 * </code> 10770 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 10771 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 10772 * view satisfies any of the following: 10773 * <ul> 10774 * <li>Is actionable, e.g. {@link #isClickable()}, 10775 * {@link #isLongClickable()}, or {@link #isFocusable()} 10776 * <li>Has an {@link AccessibilityDelegate} 10777 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 10778 * {@link OnKeyListener}, etc. 10779 * <li>Is an accessibility live region, e.g. 10780 * {@link #getAccessibilityLiveRegion()} is not 10781 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 10782 * </ul> 10783 * </ol> 10784 * 10785 * @return Whether the view is exposed for accessibility. 10786 * @see #setImportantForAccessibility(int) 10787 * @see #getImportantForAccessibility() 10788 */ 10789 public boolean isImportantForAccessibility() { 10790 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 10791 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 10792 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 10793 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 10794 return false; 10795 } 10796 10797 // Check parent mode to ensure we're not hidden. 10798 ViewParent parent = mParent; 10799 while (parent instanceof View) { 10800 if (((View) parent).getImportantForAccessibility() 10801 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 10802 return false; 10803 } 10804 parent = parent.getParent(); 10805 } 10806 10807 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 10808 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 10809 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 10810 } 10811 10812 /** 10813 * Gets the parent for accessibility purposes. Note that the parent for 10814 * accessibility is not necessary the immediate parent. It is the first 10815 * predecessor that is important for accessibility. 10816 * 10817 * @return The parent for accessibility purposes. 10818 */ 10819 public ViewParent getParentForAccessibility() { 10820 if (mParent instanceof View) { 10821 View parentView = (View) mParent; 10822 if (parentView.includeForAccessibility()) { 10823 return mParent; 10824 } else { 10825 return mParent.getParentForAccessibility(); 10826 } 10827 } 10828 return null; 10829 } 10830 10831 /** 10832 * Adds the children of this View relevant for accessibility to the given list 10833 * as output. Since some Views are not important for accessibility the added 10834 * child views are not necessarily direct children of this view, rather they are 10835 * the first level of descendants important for accessibility. 10836 * 10837 * @param outChildren The output list that will receive children for accessibility. 10838 */ 10839 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 10840 10841 } 10842 10843 /** 10844 * Whether to regard this view for accessibility. A view is regarded for 10845 * accessibility if it is important for accessibility or the querying 10846 * accessibility service has explicitly requested that view not 10847 * important for accessibility are regarded. 10848 * 10849 * @return Whether to regard the view for accessibility. 10850 * 10851 * @hide 10852 */ 10853 public boolean includeForAccessibility() { 10854 if (mAttachInfo != null) { 10855 return (mAttachInfo.mAccessibilityFetchFlags 10856 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 10857 || isImportantForAccessibility(); 10858 } 10859 return false; 10860 } 10861 10862 /** 10863 * Returns whether the View is considered actionable from 10864 * accessibility perspective. Such view are important for 10865 * accessibility. 10866 * 10867 * @return True if the view is actionable for accessibility. 10868 * 10869 * @hide 10870 */ 10871 public boolean isActionableForAccessibility() { 10872 return (isClickable() || isLongClickable() || isFocusable()); 10873 } 10874 10875 /** 10876 * Returns whether the View has registered callbacks which makes it 10877 * important for accessibility. 10878 * 10879 * @return True if the view is actionable for accessibility. 10880 */ 10881 private boolean hasListenersForAccessibility() { 10882 ListenerInfo info = getListenerInfo(); 10883 return mTouchDelegate != null || info.mOnKeyListener != null 10884 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 10885 || info.mOnHoverListener != null || info.mOnDragListener != null; 10886 } 10887 10888 /** 10889 * Notifies that the accessibility state of this view changed. The change 10890 * is local to this view and does not represent structural changes such 10891 * as children and parent. For example, the view became focusable. The 10892 * notification is at at most once every 10893 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 10894 * to avoid unnecessary load to the system. Also once a view has a pending 10895 * notification this method is a NOP until the notification has been sent. 10896 * 10897 * @hide 10898 */ 10899 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 10900 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 10901 return; 10902 } 10903 if (mSendViewStateChangedAccessibilityEvent == null) { 10904 mSendViewStateChangedAccessibilityEvent = 10905 new SendViewStateChangedAccessibilityEvent(); 10906 } 10907 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 10908 } 10909 10910 /** 10911 * Notifies that the accessibility state of this view changed. The change 10912 * is *not* local to this view and does represent structural changes such 10913 * as children and parent. For example, the view size changed. The 10914 * notification is at at most once every 10915 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 10916 * to avoid unnecessary load to the system. Also once a view has a pending 10917 * notification this method is a NOP until the notification has been sent. 10918 * 10919 * @hide 10920 */ 10921 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 10922 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 10923 return; 10924 } 10925 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 10926 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10927 if (mParent != null) { 10928 try { 10929 mParent.notifySubtreeAccessibilityStateChanged( 10930 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 10931 } catch (AbstractMethodError e) { 10932 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 10933 " does not fully implement ViewParent", e); 10934 } 10935 } 10936 } 10937 } 10938 10939 /** 10940 * Change the visibility of the View without triggering any other changes. This is 10941 * important for transitions, where visibility changes should not adjust focus or 10942 * trigger a new layout. This is only used when the visibility has already been changed 10943 * and we need a transient value during an animation. When the animation completes, 10944 * the original visibility value is always restored. 10945 * 10946 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 10947 * @hide 10948 */ 10949 public void setTransitionVisibility(@Visibility int visibility) { 10950 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 10951 } 10952 10953 /** 10954 * Reset the flag indicating the accessibility state of the subtree rooted 10955 * at this view changed. 10956 */ 10957 void resetSubtreeAccessibilityStateChanged() { 10958 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10959 } 10960 10961 /** 10962 * Report an accessibility action to this view's parents for delegated processing. 10963 * 10964 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 10965 * call this method to delegate an accessibility action to a supporting parent. If the parent 10966 * returns true from its 10967 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 10968 * method this method will return true to signify that the action was consumed.</p> 10969 * 10970 * <p>This method is useful for implementing nested scrolling child views. If 10971 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 10972 * a custom view implementation may invoke this method to allow a parent to consume the 10973 * scroll first. If this method returns true the custom view should skip its own scrolling 10974 * behavior.</p> 10975 * 10976 * @param action Accessibility action to delegate 10977 * @param arguments Optional action arguments 10978 * @return true if the action was consumed by a parent 10979 */ 10980 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 10981 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 10982 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 10983 return true; 10984 } 10985 } 10986 return false; 10987 } 10988 10989 /** 10990 * Performs the specified accessibility action on the view. For 10991 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 10992 * <p> 10993 * If an {@link AccessibilityDelegate} has been specified via calling 10994 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 10995 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 10996 * is responsible for handling this call. 10997 * </p> 10998 * 10999 * <p>The default implementation will delegate 11000 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 11001 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 11002 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 11003 * 11004 * @param action The action to perform. 11005 * @param arguments Optional action arguments. 11006 * @return Whether the action was performed. 11007 */ 11008 public boolean performAccessibilityAction(int action, Bundle arguments) { 11009 if (mAccessibilityDelegate != null) { 11010 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 11011 } else { 11012 return performAccessibilityActionInternal(action, arguments); 11013 } 11014 } 11015 11016 /** 11017 * @see #performAccessibilityAction(int, Bundle) 11018 * 11019 * Note: Called from the default {@link AccessibilityDelegate}. 11020 * 11021 * @hide 11022 */ 11023 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 11024 if (isNestedScrollingEnabled() 11025 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 11026 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 11027 || action == R.id.accessibilityActionScrollUp 11028 || action == R.id.accessibilityActionScrollLeft 11029 || action == R.id.accessibilityActionScrollDown 11030 || action == R.id.accessibilityActionScrollRight)) { 11031 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 11032 return true; 11033 } 11034 } 11035 11036 switch (action) { 11037 case AccessibilityNodeInfo.ACTION_CLICK: { 11038 if (isClickable()) { 11039 performClick(); 11040 return true; 11041 } 11042 } break; 11043 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 11044 if (isLongClickable()) { 11045 performLongClick(); 11046 return true; 11047 } 11048 } break; 11049 case AccessibilityNodeInfo.ACTION_FOCUS: { 11050 if (!hasFocus()) { 11051 // Get out of touch mode since accessibility 11052 // wants to move focus around. 11053 getViewRootImpl().ensureTouchMode(false); 11054 return requestFocus(); 11055 } 11056 } break; 11057 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 11058 if (hasFocus()) { 11059 clearFocus(); 11060 return !isFocused(); 11061 } 11062 } break; 11063 case AccessibilityNodeInfo.ACTION_SELECT: { 11064 if (!isSelected()) { 11065 setSelected(true); 11066 return isSelected(); 11067 } 11068 } break; 11069 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 11070 if (isSelected()) { 11071 setSelected(false); 11072 return !isSelected(); 11073 } 11074 } break; 11075 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 11076 if (!isAccessibilityFocused()) { 11077 return requestAccessibilityFocus(); 11078 } 11079 } break; 11080 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 11081 if (isAccessibilityFocused()) { 11082 clearAccessibilityFocus(); 11083 return true; 11084 } 11085 } break; 11086 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 11087 if (arguments != null) { 11088 final int granularity = arguments.getInt( 11089 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 11090 final boolean extendSelection = arguments.getBoolean( 11091 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 11092 return traverseAtGranularity(granularity, true, extendSelection); 11093 } 11094 } break; 11095 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 11096 if (arguments != null) { 11097 final int granularity = arguments.getInt( 11098 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 11099 final boolean extendSelection = arguments.getBoolean( 11100 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 11101 return traverseAtGranularity(granularity, false, extendSelection); 11102 } 11103 } break; 11104 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 11105 CharSequence text = getIterableTextForAccessibility(); 11106 if (text == null) { 11107 return false; 11108 } 11109 final int start = (arguments != null) ? arguments.getInt( 11110 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 11111 final int end = (arguments != null) ? arguments.getInt( 11112 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 11113 // Only cursor position can be specified (selection length == 0) 11114 if ((getAccessibilitySelectionStart() != start 11115 || getAccessibilitySelectionEnd() != end) 11116 && (start == end)) { 11117 setAccessibilitySelection(start, end); 11118 notifyViewAccessibilityStateChangedIfNeeded( 11119 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11120 return true; 11121 } 11122 } break; 11123 case R.id.accessibilityActionShowOnScreen: { 11124 if (mAttachInfo != null) { 11125 final Rect r = mAttachInfo.mTmpInvalRect; 11126 getDrawingRect(r); 11127 return requestRectangleOnScreen(r, true); 11128 } 11129 } break; 11130 case R.id.accessibilityActionContextClick: { 11131 if (isContextClickable()) { 11132 performContextClick(); 11133 return true; 11134 } 11135 } break; 11136 } 11137 return false; 11138 } 11139 11140 private boolean traverseAtGranularity(int granularity, boolean forward, 11141 boolean extendSelection) { 11142 CharSequence text = getIterableTextForAccessibility(); 11143 if (text == null || text.length() == 0) { 11144 return false; 11145 } 11146 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 11147 if (iterator == null) { 11148 return false; 11149 } 11150 int current = getAccessibilitySelectionEnd(); 11151 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 11152 current = forward ? 0 : text.length(); 11153 } 11154 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 11155 if (range == null) { 11156 return false; 11157 } 11158 final int segmentStart = range[0]; 11159 final int segmentEnd = range[1]; 11160 int selectionStart; 11161 int selectionEnd; 11162 if (extendSelection && isAccessibilitySelectionExtendable()) { 11163 selectionStart = getAccessibilitySelectionStart(); 11164 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 11165 selectionStart = forward ? segmentStart : segmentEnd; 11166 } 11167 selectionEnd = forward ? segmentEnd : segmentStart; 11168 } else { 11169 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 11170 } 11171 setAccessibilitySelection(selectionStart, selectionEnd); 11172 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 11173 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 11174 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 11175 return true; 11176 } 11177 11178 /** 11179 * Gets the text reported for accessibility purposes. 11180 * 11181 * @return The accessibility text. 11182 * 11183 * @hide 11184 */ 11185 public CharSequence getIterableTextForAccessibility() { 11186 return getContentDescription(); 11187 } 11188 11189 /** 11190 * Gets whether accessibility selection can be extended. 11191 * 11192 * @return If selection is extensible. 11193 * 11194 * @hide 11195 */ 11196 public boolean isAccessibilitySelectionExtendable() { 11197 return false; 11198 } 11199 11200 /** 11201 * @hide 11202 */ 11203 public int getAccessibilitySelectionStart() { 11204 return mAccessibilityCursorPosition; 11205 } 11206 11207 /** 11208 * @hide 11209 */ 11210 public int getAccessibilitySelectionEnd() { 11211 return getAccessibilitySelectionStart(); 11212 } 11213 11214 /** 11215 * @hide 11216 */ 11217 public void setAccessibilitySelection(int start, int end) { 11218 if (start == end && end == mAccessibilityCursorPosition) { 11219 return; 11220 } 11221 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 11222 mAccessibilityCursorPosition = start; 11223 } else { 11224 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 11225 } 11226 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 11227 } 11228 11229 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 11230 int fromIndex, int toIndex) { 11231 if (mParent == null) { 11232 return; 11233 } 11234 AccessibilityEvent event = AccessibilityEvent.obtain( 11235 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 11236 onInitializeAccessibilityEvent(event); 11237 onPopulateAccessibilityEvent(event); 11238 event.setFromIndex(fromIndex); 11239 event.setToIndex(toIndex); 11240 event.setAction(action); 11241 event.setMovementGranularity(granularity); 11242 mParent.requestSendAccessibilityEvent(this, event); 11243 } 11244 11245 /** 11246 * @hide 11247 */ 11248 public TextSegmentIterator getIteratorForGranularity(int granularity) { 11249 switch (granularity) { 11250 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 11251 CharSequence text = getIterableTextForAccessibility(); 11252 if (text != null && text.length() > 0) { 11253 CharacterTextSegmentIterator iterator = 11254 CharacterTextSegmentIterator.getInstance( 11255 mContext.getResources().getConfiguration().locale); 11256 iterator.initialize(text.toString()); 11257 return iterator; 11258 } 11259 } break; 11260 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 11261 CharSequence text = getIterableTextForAccessibility(); 11262 if (text != null && text.length() > 0) { 11263 WordTextSegmentIterator iterator = 11264 WordTextSegmentIterator.getInstance( 11265 mContext.getResources().getConfiguration().locale); 11266 iterator.initialize(text.toString()); 11267 return iterator; 11268 } 11269 } break; 11270 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 11271 CharSequence text = getIterableTextForAccessibility(); 11272 if (text != null && text.length() > 0) { 11273 ParagraphTextSegmentIterator iterator = 11274 ParagraphTextSegmentIterator.getInstance(); 11275 iterator.initialize(text.toString()); 11276 return iterator; 11277 } 11278 } break; 11279 } 11280 return null; 11281 } 11282 11283 /** 11284 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 11285 * and {@link #onFinishTemporaryDetach()}. 11286 * 11287 * <p>This method always returns {@code true} when called directly or indirectly from 11288 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 11289 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 11290 * <ul> 11291 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 11292 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 11293 * </ul> 11294 * </p> 11295 * 11296 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 11297 * and {@link #onFinishTemporaryDetach()}. 11298 */ 11299 public final boolean isTemporarilyDetached() { 11300 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 11301 } 11302 11303 /** 11304 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 11305 * a container View. 11306 */ 11307 @CallSuper 11308 public void dispatchStartTemporaryDetach() { 11309 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 11310 notifyEnterOrExitForAutoFillIfNeeded(false); 11311 onStartTemporaryDetach(); 11312 } 11313 11314 /** 11315 * This is called when a container is going to temporarily detach a child, with 11316 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 11317 * It will either be followed by {@link #onFinishTemporaryDetach()} or 11318 * {@link #onDetachedFromWindow()} when the container is done. 11319 */ 11320 public void onStartTemporaryDetach() { 11321 removeUnsetPressCallback(); 11322 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 11323 } 11324 11325 /** 11326 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 11327 * a container View. 11328 */ 11329 @CallSuper 11330 public void dispatchFinishTemporaryDetach() { 11331 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 11332 onFinishTemporaryDetach(); 11333 if (hasWindowFocus() && hasFocus()) { 11334 InputMethodManager.getInstance().focusIn(this); 11335 } 11336 notifyEnterOrExitForAutoFillIfNeeded(true); 11337 } 11338 11339 /** 11340 * Called after {@link #onStartTemporaryDetach} when the container is done 11341 * changing the view. 11342 */ 11343 public void onFinishTemporaryDetach() { 11344 } 11345 11346 /** 11347 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 11348 * for this view's window. Returns null if the view is not currently attached 11349 * to the window. Normally you will not need to use this directly, but 11350 * just use the standard high-level event callbacks like 11351 * {@link #onKeyDown(int, KeyEvent)}. 11352 */ 11353 public KeyEvent.DispatcherState getKeyDispatcherState() { 11354 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 11355 } 11356 11357 /** 11358 * Dispatch a key event before it is processed by any input method 11359 * associated with the view hierarchy. This can be used to intercept 11360 * key events in special situations before the IME consumes them; a 11361 * typical example would be handling the BACK key to update the application's 11362 * UI instead of allowing the IME to see it and close itself. 11363 * 11364 * @param event The key event to be dispatched. 11365 * @return True if the event was handled, false otherwise. 11366 */ 11367 public boolean dispatchKeyEventPreIme(KeyEvent event) { 11368 return onKeyPreIme(event.getKeyCode(), event); 11369 } 11370 11371 /** 11372 * Dispatch a key event to the next view on the focus path. This path runs 11373 * from the top of the view tree down to the currently focused view. If this 11374 * view has focus, it will dispatch to itself. Otherwise it will dispatch 11375 * the next node down the focus path. This method also fires any key 11376 * listeners. 11377 * 11378 * @param event The key event to be dispatched. 11379 * @return True if the event was handled, false otherwise. 11380 */ 11381 public boolean dispatchKeyEvent(KeyEvent event) { 11382 if (mInputEventConsistencyVerifier != null) { 11383 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 11384 } 11385 11386 // Give any attached key listener a first crack at the event. 11387 //noinspection SimplifiableIfStatement 11388 ListenerInfo li = mListenerInfo; 11389 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 11390 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 11391 return true; 11392 } 11393 11394 if (event.dispatch(this, mAttachInfo != null 11395 ? mAttachInfo.mKeyDispatchState : null, this)) { 11396 return true; 11397 } 11398 11399 if (mInputEventConsistencyVerifier != null) { 11400 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11401 } 11402 return false; 11403 } 11404 11405 /** 11406 * Dispatches a key shortcut event. 11407 * 11408 * @param event The key event to be dispatched. 11409 * @return True if the event was handled by the view, false otherwise. 11410 */ 11411 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 11412 return onKeyShortcut(event.getKeyCode(), event); 11413 } 11414 11415 /** 11416 * Pass the touch screen motion event down to the target view, or this 11417 * view if it is the target. 11418 * 11419 * @param event The motion event to be dispatched. 11420 * @return True if the event was handled by the view, false otherwise. 11421 */ 11422 public boolean dispatchTouchEvent(MotionEvent event) { 11423 // If the event should be handled by accessibility focus first. 11424 if (event.isTargetAccessibilityFocus()) { 11425 // We don't have focus or no virtual descendant has it, do not handle the event. 11426 if (!isAccessibilityFocusedViewOrHost()) { 11427 return false; 11428 } 11429 // We have focus and got the event, then use normal event dispatch. 11430 event.setTargetAccessibilityFocus(false); 11431 } 11432 11433 boolean result = false; 11434 11435 if (mInputEventConsistencyVerifier != null) { 11436 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 11437 } 11438 11439 final int actionMasked = event.getActionMasked(); 11440 if (actionMasked == MotionEvent.ACTION_DOWN) { 11441 // Defensive cleanup for new gesture 11442 stopNestedScroll(); 11443 } 11444 11445 if (onFilterTouchEventForSecurity(event)) { 11446 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 11447 result = true; 11448 } 11449 //noinspection SimplifiableIfStatement 11450 ListenerInfo li = mListenerInfo; 11451 if (li != null && li.mOnTouchListener != null 11452 && (mViewFlags & ENABLED_MASK) == ENABLED 11453 && li.mOnTouchListener.onTouch(this, event)) { 11454 result = true; 11455 } 11456 11457 if (!result && onTouchEvent(event)) { 11458 result = true; 11459 } 11460 } 11461 11462 if (!result && mInputEventConsistencyVerifier != null) { 11463 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11464 } 11465 11466 // Clean up after nested scrolls if this is the end of a gesture; 11467 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 11468 // of the gesture. 11469 if (actionMasked == MotionEvent.ACTION_UP || 11470 actionMasked == MotionEvent.ACTION_CANCEL || 11471 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 11472 stopNestedScroll(); 11473 } 11474 11475 return result; 11476 } 11477 11478 boolean isAccessibilityFocusedViewOrHost() { 11479 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 11480 .getAccessibilityFocusedHost() == this); 11481 } 11482 11483 /** 11484 * Filter the touch event to apply security policies. 11485 * 11486 * @param event The motion event to be filtered. 11487 * @return True if the event should be dispatched, false if the event should be dropped. 11488 * 11489 * @see #getFilterTouchesWhenObscured 11490 */ 11491 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 11492 //noinspection RedundantIfStatement 11493 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 11494 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 11495 // Window is obscured, drop this touch. 11496 return false; 11497 } 11498 return true; 11499 } 11500 11501 /** 11502 * Pass a trackball motion event down to the focused view. 11503 * 11504 * @param event The motion event to be dispatched. 11505 * @return True if the event was handled by the view, false otherwise. 11506 */ 11507 public boolean dispatchTrackballEvent(MotionEvent event) { 11508 if (mInputEventConsistencyVerifier != null) { 11509 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 11510 } 11511 11512 return onTrackballEvent(event); 11513 } 11514 11515 /** 11516 * Pass a captured pointer event down to the focused view. 11517 * 11518 * @param event The motion event to be dispatched. 11519 * @return True if the event was handled by the view, false otherwise. 11520 */ 11521 public boolean dispatchCapturedPointerEvent(MotionEvent event) { 11522 if (!hasPointerCapture()) { 11523 return false; 11524 } 11525 //noinspection SimplifiableIfStatement 11526 ListenerInfo li = mListenerInfo; 11527 if (li != null && li.mOnCapturedPointerListener != null 11528 && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) { 11529 return true; 11530 } 11531 return onCapturedPointerEvent(event); 11532 } 11533 11534 /** 11535 * Dispatch a generic motion event. 11536 * <p> 11537 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 11538 * are delivered to the view under the pointer. All other generic motion events are 11539 * delivered to the focused view. Hover events are handled specially and are delivered 11540 * to {@link #onHoverEvent(MotionEvent)}. 11541 * </p> 11542 * 11543 * @param event The motion event to be dispatched. 11544 * @return True if the event was handled by the view, false otherwise. 11545 */ 11546 public boolean dispatchGenericMotionEvent(MotionEvent event) { 11547 if (mInputEventConsistencyVerifier != null) { 11548 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 11549 } 11550 11551 final int source = event.getSource(); 11552 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 11553 final int action = event.getAction(); 11554 if (action == MotionEvent.ACTION_HOVER_ENTER 11555 || action == MotionEvent.ACTION_HOVER_MOVE 11556 || action == MotionEvent.ACTION_HOVER_EXIT) { 11557 if (dispatchHoverEvent(event)) { 11558 return true; 11559 } 11560 } else if (dispatchGenericPointerEvent(event)) { 11561 return true; 11562 } 11563 } else if (dispatchGenericFocusedEvent(event)) { 11564 return true; 11565 } 11566 11567 if (dispatchGenericMotionEventInternal(event)) { 11568 return true; 11569 } 11570 11571 if (mInputEventConsistencyVerifier != null) { 11572 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11573 } 11574 return false; 11575 } 11576 11577 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 11578 //noinspection SimplifiableIfStatement 11579 ListenerInfo li = mListenerInfo; 11580 if (li != null && li.mOnGenericMotionListener != null 11581 && (mViewFlags & ENABLED_MASK) == ENABLED 11582 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 11583 return true; 11584 } 11585 11586 if (onGenericMotionEvent(event)) { 11587 return true; 11588 } 11589 11590 final int actionButton = event.getActionButton(); 11591 switch (event.getActionMasked()) { 11592 case MotionEvent.ACTION_BUTTON_PRESS: 11593 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 11594 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 11595 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 11596 if (performContextClick(event.getX(), event.getY())) { 11597 mInContextButtonPress = true; 11598 setPressed(true, event.getX(), event.getY()); 11599 removeTapCallback(); 11600 removeLongPressCallback(); 11601 return true; 11602 } 11603 } 11604 break; 11605 11606 case MotionEvent.ACTION_BUTTON_RELEASE: 11607 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 11608 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 11609 mInContextButtonPress = false; 11610 mIgnoreNextUpEvent = true; 11611 } 11612 break; 11613 } 11614 11615 if (mInputEventConsistencyVerifier != null) { 11616 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11617 } 11618 return false; 11619 } 11620 11621 /** 11622 * Dispatch a hover event. 11623 * <p> 11624 * Do not call this method directly. 11625 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11626 * </p> 11627 * 11628 * @param event The motion event to be dispatched. 11629 * @return True if the event was handled by the view, false otherwise. 11630 */ 11631 protected boolean dispatchHoverEvent(MotionEvent event) { 11632 ListenerInfo li = mListenerInfo; 11633 //noinspection SimplifiableIfStatement 11634 if (li != null && li.mOnHoverListener != null 11635 && (mViewFlags & ENABLED_MASK) == ENABLED 11636 && li.mOnHoverListener.onHover(this, event)) { 11637 return true; 11638 } 11639 11640 return onHoverEvent(event); 11641 } 11642 11643 /** 11644 * Returns true if the view has a child to which it has recently sent 11645 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 11646 * it does not have a hovered child, then it must be the innermost hovered view. 11647 * @hide 11648 */ 11649 protected boolean hasHoveredChild() { 11650 return false; 11651 } 11652 11653 /** 11654 * Dispatch a generic motion event to the view under the first pointer. 11655 * <p> 11656 * Do not call this method directly. 11657 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11658 * </p> 11659 * 11660 * @param event The motion event to be dispatched. 11661 * @return True if the event was handled by the view, false otherwise. 11662 */ 11663 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 11664 return false; 11665 } 11666 11667 /** 11668 * Dispatch a generic motion event to the currently focused view. 11669 * <p> 11670 * Do not call this method directly. 11671 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11672 * </p> 11673 * 11674 * @param event The motion event to be dispatched. 11675 * @return True if the event was handled by the view, false otherwise. 11676 */ 11677 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 11678 return false; 11679 } 11680 11681 /** 11682 * Dispatch a pointer event. 11683 * <p> 11684 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 11685 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 11686 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 11687 * and should not be expected to handle other pointing device features. 11688 * </p> 11689 * 11690 * @param event The motion event to be dispatched. 11691 * @return True if the event was handled by the view, false otherwise. 11692 * @hide 11693 */ 11694 public final boolean dispatchPointerEvent(MotionEvent event) { 11695 if (event.isTouchEvent()) { 11696 return dispatchTouchEvent(event); 11697 } else { 11698 return dispatchGenericMotionEvent(event); 11699 } 11700 } 11701 11702 /** 11703 * Called when the window containing this view gains or loses window focus. 11704 * ViewGroups should override to route to their children. 11705 * 11706 * @param hasFocus True if the window containing this view now has focus, 11707 * false otherwise. 11708 */ 11709 public void dispatchWindowFocusChanged(boolean hasFocus) { 11710 onWindowFocusChanged(hasFocus); 11711 } 11712 11713 /** 11714 * Called when the window containing this view gains or loses focus. Note 11715 * that this is separate from view focus: to receive key events, both 11716 * your view and its window must have focus. If a window is displayed 11717 * on top of yours that takes input focus, then your own window will lose 11718 * focus but the view focus will remain unchanged. 11719 * 11720 * @param hasWindowFocus True if the window containing this view now has 11721 * focus, false otherwise. 11722 */ 11723 public void onWindowFocusChanged(boolean hasWindowFocus) { 11724 InputMethodManager imm = InputMethodManager.peekInstance(); 11725 if (!hasWindowFocus) { 11726 if (isPressed()) { 11727 setPressed(false); 11728 } 11729 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11730 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 11731 imm.focusOut(this); 11732 } 11733 removeLongPressCallback(); 11734 removeTapCallback(); 11735 onFocusLost(); 11736 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 11737 imm.focusIn(this); 11738 } 11739 11740 notifyEnterOrExitForAutoFillIfNeeded(hasWindowFocus); 11741 11742 refreshDrawableState(); 11743 } 11744 11745 /** 11746 * Returns true if this view is in a window that currently has window focus. 11747 * Note that this is not the same as the view itself having focus. 11748 * 11749 * @return True if this view is in a window that currently has window focus. 11750 */ 11751 public boolean hasWindowFocus() { 11752 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 11753 } 11754 11755 /** 11756 * Dispatch a view visibility change down the view hierarchy. 11757 * ViewGroups should override to route to their children. 11758 * @param changedView The view whose visibility changed. Could be 'this' or 11759 * an ancestor view. 11760 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 11761 * {@link #INVISIBLE} or {@link #GONE}. 11762 */ 11763 protected void dispatchVisibilityChanged(@NonNull View changedView, 11764 @Visibility int visibility) { 11765 onVisibilityChanged(changedView, visibility); 11766 } 11767 11768 /** 11769 * Called when the visibility of the view or an ancestor of the view has 11770 * changed. 11771 * 11772 * @param changedView The view whose visibility changed. May be 11773 * {@code this} or an ancestor view. 11774 * @param visibility The new visibility, one of {@link #VISIBLE}, 11775 * {@link #INVISIBLE} or {@link #GONE}. 11776 */ 11777 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 11778 } 11779 11780 /** 11781 * Dispatch a hint about whether this view is displayed. For instance, when 11782 * a View moves out of the screen, it might receives a display hint indicating 11783 * the view is not displayed. Applications should not <em>rely</em> on this hint 11784 * as there is no guarantee that they will receive one. 11785 * 11786 * @param hint A hint about whether or not this view is displayed: 11787 * {@link #VISIBLE} or {@link #INVISIBLE}. 11788 */ 11789 public void dispatchDisplayHint(@Visibility int hint) { 11790 onDisplayHint(hint); 11791 } 11792 11793 /** 11794 * Gives this view a hint about whether is displayed or not. For instance, when 11795 * a View moves out of the screen, it might receives a display hint indicating 11796 * the view is not displayed. Applications should not <em>rely</em> on this hint 11797 * as there is no guarantee that they will receive one. 11798 * 11799 * @param hint A hint about whether or not this view is displayed: 11800 * {@link #VISIBLE} or {@link #INVISIBLE}. 11801 */ 11802 protected void onDisplayHint(@Visibility int hint) { 11803 } 11804 11805 /** 11806 * Dispatch a window visibility change down the view hierarchy. 11807 * ViewGroups should override to route to their children. 11808 * 11809 * @param visibility The new visibility of the window. 11810 * 11811 * @see #onWindowVisibilityChanged(int) 11812 */ 11813 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 11814 onWindowVisibilityChanged(visibility); 11815 } 11816 11817 /** 11818 * Called when the window containing has change its visibility 11819 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 11820 * that this tells you whether or not your window is being made visible 11821 * to the window manager; this does <em>not</em> tell you whether or not 11822 * your window is obscured by other windows on the screen, even if it 11823 * is itself visible. 11824 * 11825 * @param visibility The new visibility of the window. 11826 */ 11827 protected void onWindowVisibilityChanged(@Visibility int visibility) { 11828 if (visibility == VISIBLE) { 11829 initialAwakenScrollBars(); 11830 } 11831 } 11832 11833 /** 11834 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 11835 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 11836 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 11837 * 11838 * @param isVisible true if this view's visibility to the user is uninterrupted by its 11839 * ancestors or by window visibility 11840 * @return true if this view is visible to the user, not counting clipping or overlapping 11841 */ 11842 boolean dispatchVisibilityAggregated(boolean isVisible) { 11843 final boolean thisVisible = getVisibility() == VISIBLE; 11844 // If we're not visible but something is telling us we are, ignore it. 11845 if (thisVisible || !isVisible) { 11846 onVisibilityAggregated(isVisible); 11847 } 11848 return thisVisible && isVisible; 11849 } 11850 11851 /** 11852 * Called when the user-visibility of this View is potentially affected by a change 11853 * to this view itself, an ancestor view or the window this view is attached to. 11854 * 11855 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 11856 * and this view's window is also visible 11857 */ 11858 @CallSuper 11859 public void onVisibilityAggregated(boolean isVisible) { 11860 if (isVisible && mAttachInfo != null) { 11861 initialAwakenScrollBars(); 11862 } 11863 11864 final Drawable dr = mBackground; 11865 if (dr != null && isVisible != dr.isVisible()) { 11866 dr.setVisible(isVisible, false); 11867 } 11868 final Drawable hl = mDefaultFocusHighlight; 11869 if (hl != null && isVisible != hl.isVisible()) { 11870 hl.setVisible(isVisible, false); 11871 } 11872 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 11873 if (fg != null && isVisible != fg.isVisible()) { 11874 fg.setVisible(isVisible, false); 11875 } 11876 11877 if (isAutofillable()) { 11878 AutofillManager afm = getAutofillManager(); 11879 11880 if (afm != null && getAccessibilityViewId() > LAST_APP_ACCESSIBILITY_ID) { 11881 if (mVisibilityChangeForAutofillHandler != null) { 11882 mVisibilityChangeForAutofillHandler.removeMessages(0); 11883 } 11884 11885 // If the view is in the background but still part of the hierarchy this is called 11886 // with isVisible=false. Hence visibility==false requires further checks 11887 if (isVisible) { 11888 afm.notifyViewVisibilityChange(this, true); 11889 } else { 11890 if (mVisibilityChangeForAutofillHandler == null) { 11891 mVisibilityChangeForAutofillHandler = 11892 new VisibilityChangeForAutofillHandler(afm, this); 11893 } 11894 // Let current operation (e.g. removal of the view from the hierarchy) 11895 // finish before checking state 11896 mVisibilityChangeForAutofillHandler.obtainMessage(0, this).sendToTarget(); 11897 } 11898 } 11899 } 11900 } 11901 11902 /** 11903 * Returns the current visibility of the window this view is attached to 11904 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 11905 * 11906 * @return Returns the current visibility of the view's window. 11907 */ 11908 @Visibility 11909 public int getWindowVisibility() { 11910 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 11911 } 11912 11913 /** 11914 * Retrieve the overall visible display size in which the window this view is 11915 * attached to has been positioned in. This takes into account screen 11916 * decorations above the window, for both cases where the window itself 11917 * is being position inside of them or the window is being placed under 11918 * then and covered insets are used for the window to position its content 11919 * inside. In effect, this tells you the available area where content can 11920 * be placed and remain visible to users. 11921 * 11922 * <p>This function requires an IPC back to the window manager to retrieve 11923 * the requested information, so should not be used in performance critical 11924 * code like drawing. 11925 * 11926 * @param outRect Filled in with the visible display frame. If the view 11927 * is not attached to a window, this is simply the raw display size. 11928 */ 11929 public void getWindowVisibleDisplayFrame(Rect outRect) { 11930 if (mAttachInfo != null) { 11931 try { 11932 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 11933 } catch (RemoteException e) { 11934 return; 11935 } 11936 // XXX This is really broken, and probably all needs to be done 11937 // in the window manager, and we need to know more about whether 11938 // we want the area behind or in front of the IME. 11939 final Rect insets = mAttachInfo.mVisibleInsets; 11940 outRect.left += insets.left; 11941 outRect.top += insets.top; 11942 outRect.right -= insets.right; 11943 outRect.bottom -= insets.bottom; 11944 return; 11945 } 11946 // The view is not attached to a display so we don't have a context. 11947 // Make a best guess about the display size. 11948 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 11949 d.getRectSize(outRect); 11950 } 11951 11952 /** 11953 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 11954 * is currently in without any insets. 11955 * 11956 * @hide 11957 */ 11958 public void getWindowDisplayFrame(Rect outRect) { 11959 if (mAttachInfo != null) { 11960 try { 11961 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 11962 } catch (RemoteException e) { 11963 return; 11964 } 11965 return; 11966 } 11967 // The view is not attached to a display so we don't have a context. 11968 // Make a best guess about the display size. 11969 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 11970 d.getRectSize(outRect); 11971 } 11972 11973 /** 11974 * Dispatch a notification about a resource configuration change down 11975 * the view hierarchy. 11976 * ViewGroups should override to route to their children. 11977 * 11978 * @param newConfig The new resource configuration. 11979 * 11980 * @see #onConfigurationChanged(android.content.res.Configuration) 11981 */ 11982 public void dispatchConfigurationChanged(Configuration newConfig) { 11983 onConfigurationChanged(newConfig); 11984 } 11985 11986 /** 11987 * Called when the current configuration of the resources being used 11988 * by the application have changed. You can use this to decide when 11989 * to reload resources that can changed based on orientation and other 11990 * configuration characteristics. You only need to use this if you are 11991 * not relying on the normal {@link android.app.Activity} mechanism of 11992 * recreating the activity instance upon a configuration change. 11993 * 11994 * @param newConfig The new resource configuration. 11995 */ 11996 protected void onConfigurationChanged(Configuration newConfig) { 11997 } 11998 11999 /** 12000 * Private function to aggregate all per-view attributes in to the view 12001 * root. 12002 */ 12003 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 12004 performCollectViewAttributes(attachInfo, visibility); 12005 } 12006 12007 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 12008 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 12009 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 12010 attachInfo.mKeepScreenOn = true; 12011 } 12012 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 12013 ListenerInfo li = mListenerInfo; 12014 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 12015 attachInfo.mHasSystemUiListeners = true; 12016 } 12017 } 12018 } 12019 12020 void needGlobalAttributesUpdate(boolean force) { 12021 final AttachInfo ai = mAttachInfo; 12022 if (ai != null && !ai.mRecomputeGlobalAttributes) { 12023 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 12024 || ai.mHasSystemUiListeners) { 12025 ai.mRecomputeGlobalAttributes = true; 12026 } 12027 } 12028 } 12029 12030 /** 12031 * Returns whether the device is currently in touch mode. Touch mode is entered 12032 * once the user begins interacting with the device by touch, and affects various 12033 * things like whether focus is always visible to the user. 12034 * 12035 * @return Whether the device is in touch mode. 12036 */ 12037 @ViewDebug.ExportedProperty 12038 public boolean isInTouchMode() { 12039 if (mAttachInfo != null) { 12040 return mAttachInfo.mInTouchMode; 12041 } else { 12042 return ViewRootImpl.isInTouchMode(); 12043 } 12044 } 12045 12046 /** 12047 * Returns the context the view is running in, through which it can 12048 * access the current theme, resources, etc. 12049 * 12050 * @return The view's Context. 12051 */ 12052 @ViewDebug.CapturedViewProperty 12053 public final Context getContext() { 12054 return mContext; 12055 } 12056 12057 /** 12058 * Handle a key event before it is processed by any input method 12059 * associated with the view hierarchy. This can be used to intercept 12060 * key events in special situations before the IME consumes them; a 12061 * typical example would be handling the BACK key to update the application's 12062 * UI instead of allowing the IME to see it and close itself. 12063 * 12064 * @param keyCode The value in event.getKeyCode(). 12065 * @param event Description of the key event. 12066 * @return If you handled the event, return true. If you want to allow the 12067 * event to be handled by the next receiver, return false. 12068 */ 12069 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 12070 return false; 12071 } 12072 12073 /** 12074 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 12075 * KeyEvent.Callback.onKeyDown()}: perform press of the view 12076 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 12077 * is released, if the view is enabled and clickable. 12078 * <p> 12079 * Key presses in software keyboards will generally NOT trigger this 12080 * listener, although some may elect to do so in some situations. Do not 12081 * rely on this to catch software key presses. 12082 * 12083 * @param keyCode a key code that represents the button pressed, from 12084 * {@link android.view.KeyEvent} 12085 * @param event the KeyEvent object that defines the button action 12086 */ 12087 public boolean onKeyDown(int keyCode, KeyEvent event) { 12088 if (KeyEvent.isConfirmKey(keyCode)) { 12089 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 12090 return true; 12091 } 12092 12093 if (event.getRepeatCount() == 0) { 12094 // Long clickable items don't necessarily have to be clickable. 12095 final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE 12096 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 12097 if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) { 12098 // For the purposes of menu anchoring and drawable hotspots, 12099 // key events are considered to be at the center of the view. 12100 final float x = getWidth() / 2f; 12101 final float y = getHeight() / 2f; 12102 if (clickable) { 12103 setPressed(true, x, y); 12104 } 12105 checkForLongClick(0, x, y); 12106 return true; 12107 } 12108 } 12109 } 12110 12111 return false; 12112 } 12113 12114 /** 12115 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 12116 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 12117 * the event). 12118 * <p>Key presses in software keyboards will generally NOT trigger this listener, 12119 * although some may elect to do so in some situations. Do not rely on this to 12120 * catch software key presses. 12121 */ 12122 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 12123 return false; 12124 } 12125 12126 /** 12127 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 12128 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 12129 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 12130 * or {@link KeyEvent#KEYCODE_SPACE} is released. 12131 * <p>Key presses in software keyboards will generally NOT trigger this listener, 12132 * although some may elect to do so in some situations. Do not rely on this to 12133 * catch software key presses. 12134 * 12135 * @param keyCode A key code that represents the button pressed, from 12136 * {@link android.view.KeyEvent}. 12137 * @param event The KeyEvent object that defines the button action. 12138 */ 12139 public boolean onKeyUp(int keyCode, KeyEvent event) { 12140 if (KeyEvent.isConfirmKey(keyCode)) { 12141 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 12142 return true; 12143 } 12144 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 12145 setPressed(false); 12146 12147 if (!mHasPerformedLongPress) { 12148 // This is a tap, so remove the longpress check 12149 removeLongPressCallback(); 12150 if (!event.isCanceled()) { 12151 return performClick(); 12152 } 12153 } 12154 } 12155 } 12156 return false; 12157 } 12158 12159 /** 12160 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 12161 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 12162 * the event). 12163 * <p>Key presses in software keyboards will generally NOT trigger this listener, 12164 * although some may elect to do so in some situations. Do not rely on this to 12165 * catch software key presses. 12166 * 12167 * @param keyCode A key code that represents the button pressed, from 12168 * {@link android.view.KeyEvent}. 12169 * @param repeatCount The number of times the action was made. 12170 * @param event The KeyEvent object that defines the button action. 12171 */ 12172 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 12173 return false; 12174 } 12175 12176 /** 12177 * Called on the focused view when a key shortcut event is not handled. 12178 * Override this method to implement local key shortcuts for the View. 12179 * Key shortcuts can also be implemented by setting the 12180 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 12181 * 12182 * @param keyCode The value in event.getKeyCode(). 12183 * @param event Description of the key event. 12184 * @return If you handled the event, return true. If you want to allow the 12185 * event to be handled by the next receiver, return false. 12186 */ 12187 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 12188 return false; 12189 } 12190 12191 /** 12192 * Check whether the called view is a text editor, in which case it 12193 * would make sense to automatically display a soft input window for 12194 * it. Subclasses should override this if they implement 12195 * {@link #onCreateInputConnection(EditorInfo)} to return true if 12196 * a call on that method would return a non-null InputConnection, and 12197 * they are really a first-class editor that the user would normally 12198 * start typing on when the go into a window containing your view. 12199 * 12200 * <p>The default implementation always returns false. This does 12201 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 12202 * will not be called or the user can not otherwise perform edits on your 12203 * view; it is just a hint to the system that this is not the primary 12204 * purpose of this view. 12205 * 12206 * @return Returns true if this view is a text editor, else false. 12207 */ 12208 public boolean onCheckIsTextEditor() { 12209 return false; 12210 } 12211 12212 /** 12213 * Create a new InputConnection for an InputMethod to interact 12214 * with the view. The default implementation returns null, since it doesn't 12215 * support input methods. You can override this to implement such support. 12216 * This is only needed for views that take focus and text input. 12217 * 12218 * <p>When implementing this, you probably also want to implement 12219 * {@link #onCheckIsTextEditor()} to indicate you will return a 12220 * non-null InputConnection.</p> 12221 * 12222 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 12223 * object correctly and in its entirety, so that the connected IME can rely 12224 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 12225 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 12226 * must be filled in with the correct cursor position for IMEs to work correctly 12227 * with your application.</p> 12228 * 12229 * @param outAttrs Fill in with attribute information about the connection. 12230 */ 12231 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 12232 return null; 12233 } 12234 12235 /** 12236 * Called by the {@link android.view.inputmethod.InputMethodManager} 12237 * when a view who is not the current 12238 * input connection target is trying to make a call on the manager. The 12239 * default implementation returns false; you can override this to return 12240 * true for certain views if you are performing InputConnection proxying 12241 * to them. 12242 * @param view The View that is making the InputMethodManager call. 12243 * @return Return true to allow the call, false to reject. 12244 */ 12245 public boolean checkInputConnectionProxy(View view) { 12246 return false; 12247 } 12248 12249 /** 12250 * Show the context menu for this view. It is not safe to hold on to the 12251 * menu after returning from this method. 12252 * 12253 * You should normally not overload this method. Overload 12254 * {@link #onCreateContextMenu(ContextMenu)} or define an 12255 * {@link OnCreateContextMenuListener} to add items to the context menu. 12256 * 12257 * @param menu The context menu to populate 12258 */ 12259 public void createContextMenu(ContextMenu menu) { 12260 ContextMenuInfo menuInfo = getContextMenuInfo(); 12261 12262 // Sets the current menu info so all items added to menu will have 12263 // my extra info set. 12264 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 12265 12266 onCreateContextMenu(menu); 12267 ListenerInfo li = mListenerInfo; 12268 if (li != null && li.mOnCreateContextMenuListener != null) { 12269 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 12270 } 12271 12272 // Clear the extra information so subsequent items that aren't mine don't 12273 // have my extra info. 12274 ((MenuBuilder)menu).setCurrentMenuInfo(null); 12275 12276 if (mParent != null) { 12277 mParent.createContextMenu(menu); 12278 } 12279 } 12280 12281 /** 12282 * Views should implement this if they have extra information to associate 12283 * with the context menu. The return result is supplied as a parameter to 12284 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 12285 * callback. 12286 * 12287 * @return Extra information about the item for which the context menu 12288 * should be shown. This information will vary across different 12289 * subclasses of View. 12290 */ 12291 protected ContextMenuInfo getContextMenuInfo() { 12292 return null; 12293 } 12294 12295 /** 12296 * Views should implement this if the view itself is going to add items to 12297 * the context menu. 12298 * 12299 * @param menu the context menu to populate 12300 */ 12301 protected void onCreateContextMenu(ContextMenu menu) { 12302 } 12303 12304 /** 12305 * Implement this method to handle trackball motion events. The 12306 * <em>relative</em> movement of the trackball since the last event 12307 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 12308 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 12309 * that a movement of 1 corresponds to the user pressing one DPAD key (so 12310 * they will often be fractional values, representing the more fine-grained 12311 * movement information available from a trackball). 12312 * 12313 * @param event The motion event. 12314 * @return True if the event was handled, false otherwise. 12315 */ 12316 public boolean onTrackballEvent(MotionEvent event) { 12317 return false; 12318 } 12319 12320 /** 12321 * Implement this method to handle generic motion events. 12322 * <p> 12323 * Generic motion events describe joystick movements, mouse hovers, track pad 12324 * touches, scroll wheel movements and other input events. The 12325 * {@link MotionEvent#getSource() source} of the motion event specifies 12326 * the class of input that was received. Implementations of this method 12327 * must examine the bits in the source before processing the event. 12328 * The following code example shows how this is done. 12329 * </p><p> 12330 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 12331 * are delivered to the view under the pointer. All other generic motion events are 12332 * delivered to the focused view. 12333 * </p> 12334 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 12335 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 12336 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 12337 * // process the joystick movement... 12338 * return true; 12339 * } 12340 * } 12341 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 12342 * switch (event.getAction()) { 12343 * case MotionEvent.ACTION_HOVER_MOVE: 12344 * // process the mouse hover movement... 12345 * return true; 12346 * case MotionEvent.ACTION_SCROLL: 12347 * // process the scroll wheel movement... 12348 * return true; 12349 * } 12350 * } 12351 * return super.onGenericMotionEvent(event); 12352 * }</pre> 12353 * 12354 * @param event The generic motion event being processed. 12355 * @return True if the event was handled, false otherwise. 12356 */ 12357 public boolean onGenericMotionEvent(MotionEvent event) { 12358 return false; 12359 } 12360 12361 /** 12362 * Implement this method to handle hover events. 12363 * <p> 12364 * This method is called whenever a pointer is hovering into, over, or out of the 12365 * bounds of a view and the view is not currently being touched. 12366 * Hover events are represented as pointer events with action 12367 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 12368 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 12369 * </p> 12370 * <ul> 12371 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 12372 * when the pointer enters the bounds of the view.</li> 12373 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 12374 * when the pointer has already entered the bounds of the view and has moved.</li> 12375 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 12376 * when the pointer has exited the bounds of the view or when the pointer is 12377 * about to go down due to a button click, tap, or similar user action that 12378 * causes the view to be touched.</li> 12379 * </ul> 12380 * <p> 12381 * The view should implement this method to return true to indicate that it is 12382 * handling the hover event, such as by changing its drawable state. 12383 * </p><p> 12384 * The default implementation calls {@link #setHovered} to update the hovered state 12385 * of the view when a hover enter or hover exit event is received, if the view 12386 * is enabled and is clickable. The default implementation also sends hover 12387 * accessibility events. 12388 * </p> 12389 * 12390 * @param event The motion event that describes the hover. 12391 * @return True if the view handled the hover event. 12392 * 12393 * @see #isHovered 12394 * @see #setHovered 12395 * @see #onHoverChanged 12396 */ 12397 public boolean onHoverEvent(MotionEvent event) { 12398 // The root view may receive hover (or touch) events that are outside the bounds of 12399 // the window. This code ensures that we only send accessibility events for 12400 // hovers that are actually within the bounds of the root view. 12401 final int action = event.getActionMasked(); 12402 if (!mSendingHoverAccessibilityEvents) { 12403 if ((action == MotionEvent.ACTION_HOVER_ENTER 12404 || action == MotionEvent.ACTION_HOVER_MOVE) 12405 && !hasHoveredChild() 12406 && pointInView(event.getX(), event.getY())) { 12407 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 12408 mSendingHoverAccessibilityEvents = true; 12409 } 12410 } else { 12411 if (action == MotionEvent.ACTION_HOVER_EXIT 12412 || (action == MotionEvent.ACTION_MOVE 12413 && !pointInView(event.getX(), event.getY()))) { 12414 mSendingHoverAccessibilityEvents = false; 12415 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 12416 } 12417 } 12418 12419 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 12420 && event.isFromSource(InputDevice.SOURCE_MOUSE) 12421 && isOnScrollbar(event.getX(), event.getY())) { 12422 awakenScrollBars(); 12423 } 12424 12425 // If we consider ourself hoverable, or if we we're already hovered, 12426 // handle changing state in response to ENTER and EXIT events. 12427 if (isHoverable() || isHovered()) { 12428 switch (action) { 12429 case MotionEvent.ACTION_HOVER_ENTER: 12430 setHovered(true); 12431 break; 12432 case MotionEvent.ACTION_HOVER_EXIT: 12433 setHovered(false); 12434 break; 12435 } 12436 12437 // Dispatch the event to onGenericMotionEvent before returning true. 12438 // This is to provide compatibility with existing applications that 12439 // handled HOVER_MOVE events in onGenericMotionEvent and that would 12440 // break because of the new default handling for hoverable views 12441 // in onHoverEvent. 12442 // Note that onGenericMotionEvent will be called by default when 12443 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 12444 dispatchGenericMotionEventInternal(event); 12445 // The event was already handled by calling setHovered(), so always 12446 // return true. 12447 return true; 12448 } 12449 12450 return false; 12451 } 12452 12453 /** 12454 * Returns true if the view should handle {@link #onHoverEvent} 12455 * by calling {@link #setHovered} to change its hovered state. 12456 * 12457 * @return True if the view is hoverable. 12458 */ 12459 private boolean isHoverable() { 12460 final int viewFlags = mViewFlags; 12461 if ((viewFlags & ENABLED_MASK) == DISABLED) { 12462 return false; 12463 } 12464 12465 return (viewFlags & CLICKABLE) == CLICKABLE 12466 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 12467 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 12468 } 12469 12470 /** 12471 * Returns true if the view is currently hovered. 12472 * 12473 * @return True if the view is currently hovered. 12474 * 12475 * @see #setHovered 12476 * @see #onHoverChanged 12477 */ 12478 @ViewDebug.ExportedProperty 12479 public boolean isHovered() { 12480 return (mPrivateFlags & PFLAG_HOVERED) != 0; 12481 } 12482 12483 /** 12484 * Sets whether the view is currently hovered. 12485 * <p> 12486 * Calling this method also changes the drawable state of the view. This 12487 * enables the view to react to hover by using different drawable resources 12488 * to change its appearance. 12489 * </p><p> 12490 * The {@link #onHoverChanged} method is called when the hovered state changes. 12491 * </p> 12492 * 12493 * @param hovered True if the view is hovered. 12494 * 12495 * @see #isHovered 12496 * @see #onHoverChanged 12497 */ 12498 public void setHovered(boolean hovered) { 12499 if (hovered) { 12500 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 12501 mPrivateFlags |= PFLAG_HOVERED; 12502 refreshDrawableState(); 12503 onHoverChanged(true); 12504 } 12505 } else { 12506 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 12507 mPrivateFlags &= ~PFLAG_HOVERED; 12508 refreshDrawableState(); 12509 onHoverChanged(false); 12510 } 12511 } 12512 } 12513 12514 /** 12515 * Implement this method to handle hover state changes. 12516 * <p> 12517 * This method is called whenever the hover state changes as a result of a 12518 * call to {@link #setHovered}. 12519 * </p> 12520 * 12521 * @param hovered The current hover state, as returned by {@link #isHovered}. 12522 * 12523 * @see #isHovered 12524 * @see #setHovered 12525 */ 12526 public void onHoverChanged(boolean hovered) { 12527 } 12528 12529 /** 12530 * Handles scroll bar dragging by mouse input. 12531 * 12532 * @hide 12533 * @param event The motion event. 12534 * 12535 * @return true if the event was handled as a scroll bar dragging, false otherwise. 12536 */ 12537 protected boolean handleScrollBarDragging(MotionEvent event) { 12538 if (mScrollCache == null) { 12539 return false; 12540 } 12541 final float x = event.getX(); 12542 final float y = event.getY(); 12543 final int action = event.getAction(); 12544 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 12545 && action != MotionEvent.ACTION_DOWN) 12546 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 12547 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 12548 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 12549 return false; 12550 } 12551 12552 switch (action) { 12553 case MotionEvent.ACTION_MOVE: 12554 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 12555 return false; 12556 } 12557 if (mScrollCache.mScrollBarDraggingState 12558 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 12559 final Rect bounds = mScrollCache.mScrollBarBounds; 12560 getVerticalScrollBarBounds(bounds, null); 12561 final int range = computeVerticalScrollRange(); 12562 final int offset = computeVerticalScrollOffset(); 12563 final int extent = computeVerticalScrollExtent(); 12564 12565 final int thumbLength = ScrollBarUtils.getThumbLength( 12566 bounds.height(), bounds.width(), extent, range); 12567 final int thumbOffset = ScrollBarUtils.getThumbOffset( 12568 bounds.height(), thumbLength, extent, range, offset); 12569 12570 final float diff = y - mScrollCache.mScrollBarDraggingPos; 12571 final float maxThumbOffset = bounds.height() - thumbLength; 12572 final float newThumbOffset = 12573 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 12574 final int height = getHeight(); 12575 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 12576 && height > 0 && extent > 0) { 12577 final int newY = Math.round((range - extent) 12578 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 12579 if (newY != getScrollY()) { 12580 mScrollCache.mScrollBarDraggingPos = y; 12581 setScrollY(newY); 12582 } 12583 } 12584 return true; 12585 } 12586 if (mScrollCache.mScrollBarDraggingState 12587 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 12588 final Rect bounds = mScrollCache.mScrollBarBounds; 12589 getHorizontalScrollBarBounds(bounds, null); 12590 final int range = computeHorizontalScrollRange(); 12591 final int offset = computeHorizontalScrollOffset(); 12592 final int extent = computeHorizontalScrollExtent(); 12593 12594 final int thumbLength = ScrollBarUtils.getThumbLength( 12595 bounds.width(), bounds.height(), extent, range); 12596 final int thumbOffset = ScrollBarUtils.getThumbOffset( 12597 bounds.width(), thumbLength, extent, range, offset); 12598 12599 final float diff = x - mScrollCache.mScrollBarDraggingPos; 12600 final float maxThumbOffset = bounds.width() - thumbLength; 12601 final float newThumbOffset = 12602 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 12603 final int width = getWidth(); 12604 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 12605 && width > 0 && extent > 0) { 12606 final int newX = Math.round((range - extent) 12607 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 12608 if (newX != getScrollX()) { 12609 mScrollCache.mScrollBarDraggingPos = x; 12610 setScrollX(newX); 12611 } 12612 } 12613 return true; 12614 } 12615 case MotionEvent.ACTION_DOWN: 12616 if (mScrollCache.state == ScrollabilityCache.OFF) { 12617 return false; 12618 } 12619 if (isOnVerticalScrollbarThumb(x, y)) { 12620 mScrollCache.mScrollBarDraggingState = 12621 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 12622 mScrollCache.mScrollBarDraggingPos = y; 12623 return true; 12624 } 12625 if (isOnHorizontalScrollbarThumb(x, y)) { 12626 mScrollCache.mScrollBarDraggingState = 12627 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 12628 mScrollCache.mScrollBarDraggingPos = x; 12629 return true; 12630 } 12631 } 12632 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 12633 return false; 12634 } 12635 12636 /** 12637 * Implement this method to handle touch screen motion events. 12638 * <p> 12639 * If this method is used to detect click actions, it is recommended that 12640 * the actions be performed by implementing and calling 12641 * {@link #performClick()}. This will ensure consistent system behavior, 12642 * including: 12643 * <ul> 12644 * <li>obeying click sound preferences 12645 * <li>dispatching OnClickListener calls 12646 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 12647 * accessibility features are enabled 12648 * </ul> 12649 * 12650 * @param event The motion event. 12651 * @return True if the event was handled, false otherwise. 12652 */ 12653 public boolean onTouchEvent(MotionEvent event) { 12654 final float x = event.getX(); 12655 final float y = event.getY(); 12656 final int viewFlags = mViewFlags; 12657 final int action = event.getAction(); 12658 12659 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE 12660 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 12661 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 12662 12663 if ((viewFlags & ENABLED_MASK) == DISABLED) { 12664 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 12665 setPressed(false); 12666 } 12667 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12668 // A disabled view that is clickable still consumes the touch 12669 // events, it just doesn't respond to them. 12670 return clickable; 12671 } 12672 if (mTouchDelegate != null) { 12673 if (mTouchDelegate.onTouchEvent(event)) { 12674 return true; 12675 } 12676 } 12677 12678 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { 12679 switch (action) { 12680 case MotionEvent.ACTION_UP: 12681 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12682 if ((viewFlags & TOOLTIP) == TOOLTIP) { 12683 handleTooltipUp(); 12684 } 12685 if (!clickable) { 12686 removeTapCallback(); 12687 removeLongPressCallback(); 12688 mInContextButtonPress = false; 12689 mHasPerformedLongPress = false; 12690 mIgnoreNextUpEvent = false; 12691 break; 12692 } 12693 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 12694 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 12695 // take focus if we don't have it already and we should in 12696 // touch mode. 12697 boolean focusTaken = false; 12698 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 12699 focusTaken = requestFocus(); 12700 } 12701 12702 if (prepressed) { 12703 // The button is being released before we actually 12704 // showed it as pressed. Make it show the pressed 12705 // state now (before scheduling the click) to ensure 12706 // the user sees it. 12707 setPressed(true, x, y); 12708 } 12709 12710 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 12711 // This is a tap, so remove the longpress check 12712 removeLongPressCallback(); 12713 12714 // Only perform take click actions if we were in the pressed state 12715 if (!focusTaken) { 12716 // Use a Runnable and post this rather than calling 12717 // performClick directly. This lets other visual state 12718 // of the view update before click actions start. 12719 if (mPerformClick == null) { 12720 mPerformClick = new PerformClick(); 12721 } 12722 if (!post(mPerformClick)) { 12723 performClick(); 12724 } 12725 } 12726 } 12727 12728 if (mUnsetPressedState == null) { 12729 mUnsetPressedState = new UnsetPressedState(); 12730 } 12731 12732 if (prepressed) { 12733 postDelayed(mUnsetPressedState, 12734 ViewConfiguration.getPressedStateDuration()); 12735 } else if (!post(mUnsetPressedState)) { 12736 // If the post failed, unpress right now 12737 mUnsetPressedState.run(); 12738 } 12739 12740 removeTapCallback(); 12741 } 12742 mIgnoreNextUpEvent = false; 12743 break; 12744 12745 case MotionEvent.ACTION_DOWN: 12746 if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { 12747 mPrivateFlags3 |= PFLAG3_FINGER_DOWN; 12748 } 12749 mHasPerformedLongPress = false; 12750 12751 if (!clickable) { 12752 checkForLongClick(0, x, y); 12753 break; 12754 } 12755 12756 if (performButtonActionOnTouchDown(event)) { 12757 break; 12758 } 12759 12760 // Walk up the hierarchy to determine if we're inside a scrolling container. 12761 boolean isInScrollingContainer = isInScrollingContainer(); 12762 12763 // For views inside a scrolling container, delay the pressed feedback for 12764 // a short period in case this is a scroll. 12765 if (isInScrollingContainer) { 12766 mPrivateFlags |= PFLAG_PREPRESSED; 12767 if (mPendingCheckForTap == null) { 12768 mPendingCheckForTap = new CheckForTap(); 12769 } 12770 mPendingCheckForTap.x = event.getX(); 12771 mPendingCheckForTap.y = event.getY(); 12772 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 12773 } else { 12774 // Not inside a scrolling container, so show the feedback right away 12775 setPressed(true, x, y); 12776 checkForLongClick(0, x, y); 12777 } 12778 break; 12779 12780 case MotionEvent.ACTION_CANCEL: 12781 if (clickable) { 12782 setPressed(false); 12783 } 12784 removeTapCallback(); 12785 removeLongPressCallback(); 12786 mInContextButtonPress = false; 12787 mHasPerformedLongPress = false; 12788 mIgnoreNextUpEvent = false; 12789 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12790 break; 12791 12792 case MotionEvent.ACTION_MOVE: 12793 if (clickable) { 12794 drawableHotspotChanged(x, y); 12795 } 12796 12797 // Be lenient about moving outside of buttons 12798 if (!pointInView(x, y, mTouchSlop)) { 12799 // Outside button 12800 // Remove any future long press/tap checks 12801 removeTapCallback(); 12802 removeLongPressCallback(); 12803 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 12804 setPressed(false); 12805 } 12806 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12807 } 12808 break; 12809 } 12810 12811 return true; 12812 } 12813 12814 return false; 12815 } 12816 12817 /** 12818 * @hide 12819 */ 12820 public boolean isInScrollingContainer() { 12821 ViewParent p = getParent(); 12822 while (p != null && p instanceof ViewGroup) { 12823 if (((ViewGroup) p).shouldDelayChildPressedState()) { 12824 return true; 12825 } 12826 p = p.getParent(); 12827 } 12828 return false; 12829 } 12830 12831 /** 12832 * Remove the longpress detection timer. 12833 */ 12834 private void removeLongPressCallback() { 12835 if (mPendingCheckForLongPress != null) { 12836 removeCallbacks(mPendingCheckForLongPress); 12837 } 12838 } 12839 12840 /** 12841 * Remove the pending click action 12842 */ 12843 private void removePerformClickCallback() { 12844 if (mPerformClick != null) { 12845 removeCallbacks(mPerformClick); 12846 } 12847 } 12848 12849 /** 12850 * Remove the prepress detection timer. 12851 */ 12852 private void removeUnsetPressCallback() { 12853 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 12854 setPressed(false); 12855 removeCallbacks(mUnsetPressedState); 12856 } 12857 } 12858 12859 /** 12860 * Remove the tap detection timer. 12861 */ 12862 private void removeTapCallback() { 12863 if (mPendingCheckForTap != null) { 12864 mPrivateFlags &= ~PFLAG_PREPRESSED; 12865 removeCallbacks(mPendingCheckForTap); 12866 } 12867 } 12868 12869 /** 12870 * Cancels a pending long press. Your subclass can use this if you 12871 * want the context menu to come up if the user presses and holds 12872 * at the same place, but you don't want it to come up if they press 12873 * and then move around enough to cause scrolling. 12874 */ 12875 public void cancelLongPress() { 12876 removeLongPressCallback(); 12877 12878 /* 12879 * The prepressed state handled by the tap callback is a display 12880 * construct, but the tap callback will post a long press callback 12881 * less its own timeout. Remove it here. 12882 */ 12883 removeTapCallback(); 12884 } 12885 12886 /** 12887 * Remove the pending callback for sending a 12888 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 12889 */ 12890 private void removeSendViewScrolledAccessibilityEventCallback() { 12891 if (mSendViewScrolledAccessibilityEvent != null) { 12892 removeCallbacks(mSendViewScrolledAccessibilityEvent); 12893 mSendViewScrolledAccessibilityEvent.mIsPending = false; 12894 } 12895 } 12896 12897 /** 12898 * Sets the TouchDelegate for this View. 12899 */ 12900 public void setTouchDelegate(TouchDelegate delegate) { 12901 mTouchDelegate = delegate; 12902 } 12903 12904 /** 12905 * Gets the TouchDelegate for this View. 12906 */ 12907 public TouchDelegate getTouchDelegate() { 12908 return mTouchDelegate; 12909 } 12910 12911 /** 12912 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 12913 * 12914 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 12915 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 12916 * available. This method should only be called for touch events. 12917 * 12918 * <p class="note">This api is not intended for most applications. Buffered dispatch 12919 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 12920 * streams will not improve your input latency. Side effects include: increased latency, 12921 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 12922 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 12923 * you.</p> 12924 */ 12925 public final void requestUnbufferedDispatch(MotionEvent event) { 12926 final int action = event.getAction(); 12927 if (mAttachInfo == null 12928 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 12929 || !event.isTouchEvent()) { 12930 return; 12931 } 12932 mAttachInfo.mUnbufferedDispatchRequested = true; 12933 } 12934 12935 /** 12936 * Set flags controlling behavior of this view. 12937 * 12938 * @param flags Constant indicating the value which should be set 12939 * @param mask Constant indicating the bit range that should be changed 12940 */ 12941 void setFlags(int flags, int mask) { 12942 final boolean accessibilityEnabled = 12943 AccessibilityManager.getInstance(mContext).isEnabled(); 12944 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 12945 12946 int old = mViewFlags; 12947 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 12948 12949 int changed = mViewFlags ^ old; 12950 if (changed == 0) { 12951 return; 12952 } 12953 int privateFlags = mPrivateFlags; 12954 12955 // If focusable is auto, update the FOCUSABLE bit. 12956 int focusableChangedByAuto = 0; 12957 if (((mViewFlags & FOCUSABLE_AUTO) != 0) 12958 && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) { 12959 // Heuristic only takes into account whether view is clickable. 12960 final int newFocus; 12961 if ((mViewFlags & CLICKABLE) != 0) { 12962 newFocus = FOCUSABLE; 12963 } else { 12964 newFocus = NOT_FOCUSABLE; 12965 } 12966 mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus; 12967 focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE); 12968 changed = (changed & ~FOCUSABLE) | focusableChangedByAuto; 12969 } 12970 12971 /* Check if the FOCUSABLE bit has changed */ 12972 if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) { 12973 if (((old & FOCUSABLE) == FOCUSABLE) 12974 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 12975 /* Give up focus if we are no longer focusable */ 12976 clearFocus(); 12977 } else if (((old & FOCUSABLE) == NOT_FOCUSABLE) 12978 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 12979 /* 12980 * Tell the view system that we are now available to take focus 12981 * if no one else already has it. 12982 */ 12983 if (mParent != null) { 12984 ViewRootImpl viewRootImpl = getViewRootImpl(); 12985 if (!sAutoFocusableOffUIThreadWontNotifyParents 12986 || focusableChangedByAuto == 0 12987 || viewRootImpl == null 12988 || viewRootImpl.mThread == Thread.currentThread()) { 12989 mParent.focusableViewAvailable(this); 12990 } 12991 } 12992 } 12993 } 12994 12995 final int newVisibility = flags & VISIBILITY_MASK; 12996 if (newVisibility == VISIBLE) { 12997 if ((changed & VISIBILITY_MASK) != 0) { 12998 /* 12999 * If this view is becoming visible, invalidate it in case it changed while 13000 * it was not visible. Marking it drawn ensures that the invalidation will 13001 * go through. 13002 */ 13003 mPrivateFlags |= PFLAG_DRAWN; 13004 invalidate(true); 13005 13006 needGlobalAttributesUpdate(true); 13007 13008 // a view becoming visible is worth notifying the parent 13009 // about in case nothing has focus. even if this specific view 13010 // isn't focusable, it may contain something that is, so let 13011 // the root view try to give this focus if nothing else does. 13012 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 13013 mParent.focusableViewAvailable(this); 13014 } 13015 } 13016 } 13017 13018 /* Check if the GONE bit has changed */ 13019 if ((changed & GONE) != 0) { 13020 needGlobalAttributesUpdate(false); 13021 requestLayout(); 13022 13023 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 13024 if (hasFocus()) clearFocus(); 13025 clearAccessibilityFocus(); 13026 destroyDrawingCache(); 13027 if (mParent instanceof View) { 13028 // GONE views noop invalidation, so invalidate the parent 13029 ((View) mParent).invalidate(true); 13030 } 13031 // Mark the view drawn to ensure that it gets invalidated properly the next 13032 // time it is visible and gets invalidated 13033 mPrivateFlags |= PFLAG_DRAWN; 13034 } 13035 if (mAttachInfo != null) { 13036 mAttachInfo.mViewVisibilityChanged = true; 13037 } 13038 } 13039 13040 /* Check if the VISIBLE bit has changed */ 13041 if ((changed & INVISIBLE) != 0) { 13042 needGlobalAttributesUpdate(false); 13043 /* 13044 * If this view is becoming invisible, set the DRAWN flag so that 13045 * the next invalidate() will not be skipped. 13046 */ 13047 mPrivateFlags |= PFLAG_DRAWN; 13048 13049 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 13050 // root view becoming invisible shouldn't clear focus and accessibility focus 13051 if (getRootView() != this) { 13052 if (hasFocus()) clearFocus(); 13053 clearAccessibilityFocus(); 13054 } 13055 } 13056 if (mAttachInfo != null) { 13057 mAttachInfo.mViewVisibilityChanged = true; 13058 } 13059 } 13060 13061 if ((changed & VISIBILITY_MASK) != 0) { 13062 // If the view is invisible, cleanup its display list to free up resources 13063 if (newVisibility != VISIBLE && mAttachInfo != null) { 13064 cleanupDraw(); 13065 } 13066 13067 if (mParent instanceof ViewGroup) { 13068 ((ViewGroup) mParent).onChildVisibilityChanged(this, 13069 (changed & VISIBILITY_MASK), newVisibility); 13070 ((View) mParent).invalidate(true); 13071 } else if (mParent != null) { 13072 mParent.invalidateChild(this, null); 13073 } 13074 13075 if (mAttachInfo != null) { 13076 dispatchVisibilityChanged(this, newVisibility); 13077 13078 // Aggregated visibility changes are dispatched to attached views 13079 // in visible windows where the parent is currently shown/drawn 13080 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 13081 // discounting clipping or overlapping. This makes it a good place 13082 // to change animation states. 13083 if (mParent != null && getWindowVisibility() == VISIBLE && 13084 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 13085 dispatchVisibilityAggregated(newVisibility == VISIBLE); 13086 } 13087 notifySubtreeAccessibilityStateChangedIfNeeded(); 13088 } 13089 } 13090 13091 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 13092 destroyDrawingCache(); 13093 } 13094 13095 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 13096 destroyDrawingCache(); 13097 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13098 invalidateParentCaches(); 13099 } 13100 13101 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 13102 destroyDrawingCache(); 13103 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13104 } 13105 13106 if ((changed & DRAW_MASK) != 0) { 13107 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 13108 if (mBackground != null 13109 || mDefaultFocusHighlight != null 13110 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 13111 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 13112 } else { 13113 mPrivateFlags |= PFLAG_SKIP_DRAW; 13114 } 13115 } else { 13116 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 13117 } 13118 requestLayout(); 13119 invalidate(true); 13120 } 13121 13122 if ((changed & KEEP_SCREEN_ON) != 0) { 13123 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 13124 mParent.recomputeViewAttributes(this); 13125 } 13126 } 13127 13128 if (accessibilityEnabled) { 13129 if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0 13130 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 13131 || (changed & CONTEXT_CLICKABLE) != 0) { 13132 if (oldIncludeForAccessibility != includeForAccessibility()) { 13133 notifySubtreeAccessibilityStateChangedIfNeeded(); 13134 } else { 13135 notifyViewAccessibilityStateChangedIfNeeded( 13136 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 13137 } 13138 } else if ((changed & ENABLED_MASK) != 0) { 13139 notifyViewAccessibilityStateChangedIfNeeded( 13140 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 13141 } 13142 } 13143 } 13144 13145 /** 13146 * Change the view's z order in the tree, so it's on top of other sibling 13147 * views. This ordering change may affect layout, if the parent container 13148 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 13149 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 13150 * method should be followed by calls to {@link #requestLayout()} and 13151 * {@link View#invalidate()} on the view's parent to force the parent to redraw 13152 * with the new child ordering. 13153 * 13154 * @see ViewGroup#bringChildToFront(View) 13155 */ 13156 public void bringToFront() { 13157 if (mParent != null) { 13158 mParent.bringChildToFront(this); 13159 } 13160 } 13161 13162 /** 13163 * This is called in response to an internal scroll in this view (i.e., the 13164 * view scrolled its own contents). This is typically as a result of 13165 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 13166 * called. 13167 * 13168 * @param l Current horizontal scroll origin. 13169 * @param t Current vertical scroll origin. 13170 * @param oldl Previous horizontal scroll origin. 13171 * @param oldt Previous vertical scroll origin. 13172 */ 13173 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 13174 notifySubtreeAccessibilityStateChangedIfNeeded(); 13175 13176 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 13177 postSendViewScrolledAccessibilityEventCallback(); 13178 } 13179 13180 mBackgroundSizeChanged = true; 13181 mDefaultFocusHighlightSizeChanged = true; 13182 if (mForegroundInfo != null) { 13183 mForegroundInfo.mBoundsChanged = true; 13184 } 13185 13186 final AttachInfo ai = mAttachInfo; 13187 if (ai != null) { 13188 ai.mViewScrollChanged = true; 13189 } 13190 13191 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 13192 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 13193 } 13194 } 13195 13196 /** 13197 * Interface definition for a callback to be invoked when the scroll 13198 * X or Y positions of a view change. 13199 * <p> 13200 * <b>Note:</b> Some views handle scrolling independently from View and may 13201 * have their own separate listeners for scroll-type events. For example, 13202 * {@link android.widget.ListView ListView} allows clients to register an 13203 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 13204 * to listen for changes in list scroll position. 13205 * 13206 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 13207 */ 13208 public interface OnScrollChangeListener { 13209 /** 13210 * Called when the scroll position of a view changes. 13211 * 13212 * @param v The view whose scroll position has changed. 13213 * @param scrollX Current horizontal scroll origin. 13214 * @param scrollY Current vertical scroll origin. 13215 * @param oldScrollX Previous horizontal scroll origin. 13216 * @param oldScrollY Previous vertical scroll origin. 13217 */ 13218 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 13219 } 13220 13221 /** 13222 * Interface definition for a callback to be invoked when the layout bounds of a view 13223 * changes due to layout processing. 13224 */ 13225 public interface OnLayoutChangeListener { 13226 /** 13227 * Called when the layout bounds of a view changes due to layout processing. 13228 * 13229 * @param v The view whose bounds have changed. 13230 * @param left The new value of the view's left property. 13231 * @param top The new value of the view's top property. 13232 * @param right The new value of the view's right property. 13233 * @param bottom The new value of the view's bottom property. 13234 * @param oldLeft The previous value of the view's left property. 13235 * @param oldTop The previous value of the view's top property. 13236 * @param oldRight The previous value of the view's right property. 13237 * @param oldBottom The previous value of the view's bottom property. 13238 */ 13239 void onLayoutChange(View v, int left, int top, int right, int bottom, 13240 int oldLeft, int oldTop, int oldRight, int oldBottom); 13241 } 13242 13243 /** 13244 * This is called during layout when the size of this view has changed. If 13245 * you were just added to the view hierarchy, you're called with the old 13246 * values of 0. 13247 * 13248 * @param w Current width of this view. 13249 * @param h Current height of this view. 13250 * @param oldw Old width of this view. 13251 * @param oldh Old height of this view. 13252 */ 13253 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 13254 } 13255 13256 /** 13257 * Called by draw to draw the child views. This may be overridden 13258 * by derived classes to gain control just before its children are drawn 13259 * (but after its own view has been drawn). 13260 * @param canvas the canvas on which to draw the view 13261 */ 13262 protected void dispatchDraw(Canvas canvas) { 13263 13264 } 13265 13266 /** 13267 * Gets the parent of this view. Note that the parent is a 13268 * ViewParent and not necessarily a View. 13269 * 13270 * @return Parent of this view. 13271 */ 13272 public final ViewParent getParent() { 13273 return mParent; 13274 } 13275 13276 /** 13277 * Set the horizontal scrolled position of your view. This will cause a call to 13278 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13279 * invalidated. 13280 * @param value the x position to scroll to 13281 */ 13282 public void setScrollX(int value) { 13283 scrollTo(value, mScrollY); 13284 } 13285 13286 /** 13287 * Set the vertical scrolled position of your view. This will cause a call to 13288 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13289 * invalidated. 13290 * @param value the y position to scroll to 13291 */ 13292 public void setScrollY(int value) { 13293 scrollTo(mScrollX, value); 13294 } 13295 13296 /** 13297 * Return the scrolled left position of this view. This is the left edge of 13298 * the displayed part of your view. You do not need to draw any pixels 13299 * farther left, since those are outside of the frame of your view on 13300 * screen. 13301 * 13302 * @return The left edge of the displayed part of your view, in pixels. 13303 */ 13304 public final int getScrollX() { 13305 return mScrollX; 13306 } 13307 13308 /** 13309 * Return the scrolled top position of this view. This is the top edge of 13310 * the displayed part of your view. You do not need to draw any pixels above 13311 * it, since those are outside of the frame of your view on screen. 13312 * 13313 * @return The top edge of the displayed part of your view, in pixels. 13314 */ 13315 public final int getScrollY() { 13316 return mScrollY; 13317 } 13318 13319 /** 13320 * Return the width of the your view. 13321 * 13322 * @return The width of your view, in pixels. 13323 */ 13324 @ViewDebug.ExportedProperty(category = "layout") 13325 public final int getWidth() { 13326 return mRight - mLeft; 13327 } 13328 13329 /** 13330 * Return the height of your view. 13331 * 13332 * @return The height of your view, in pixels. 13333 */ 13334 @ViewDebug.ExportedProperty(category = "layout") 13335 public final int getHeight() { 13336 return mBottom - mTop; 13337 } 13338 13339 /** 13340 * Return the visible drawing bounds of your view. Fills in the output 13341 * rectangle with the values from getScrollX(), getScrollY(), 13342 * getWidth(), and getHeight(). These bounds do not account for any 13343 * transformation properties currently set on the view, such as 13344 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 13345 * 13346 * @param outRect The (scrolled) drawing bounds of the view. 13347 */ 13348 public void getDrawingRect(Rect outRect) { 13349 outRect.left = mScrollX; 13350 outRect.top = mScrollY; 13351 outRect.right = mScrollX + (mRight - mLeft); 13352 outRect.bottom = mScrollY + (mBottom - mTop); 13353 } 13354 13355 /** 13356 * Like {@link #getMeasuredWidthAndState()}, but only returns the 13357 * raw width component (that is the result is masked by 13358 * {@link #MEASURED_SIZE_MASK}). 13359 * 13360 * @return The raw measured width of this view. 13361 */ 13362 public final int getMeasuredWidth() { 13363 return mMeasuredWidth & MEASURED_SIZE_MASK; 13364 } 13365 13366 /** 13367 * Return the full width measurement information for this view as computed 13368 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 13369 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13370 * This should be used during measurement and layout calculations only. Use 13371 * {@link #getWidth()} to see how wide a view is after layout. 13372 * 13373 * @return The measured width of this view as a bit mask. 13374 */ 13375 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 13376 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 13377 name = "MEASURED_STATE_TOO_SMALL"), 13378 }) 13379 public final int getMeasuredWidthAndState() { 13380 return mMeasuredWidth; 13381 } 13382 13383 /** 13384 * Like {@link #getMeasuredHeightAndState()}, but only returns the 13385 * raw height component (that is the result is masked by 13386 * {@link #MEASURED_SIZE_MASK}). 13387 * 13388 * @return The raw measured height of this view. 13389 */ 13390 public final int getMeasuredHeight() { 13391 return mMeasuredHeight & MEASURED_SIZE_MASK; 13392 } 13393 13394 /** 13395 * Return the full height measurement information for this view as computed 13396 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 13397 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13398 * This should be used during measurement and layout calculations only. Use 13399 * {@link #getHeight()} to see how wide a view is after layout. 13400 * 13401 * @return The measured height of this view as a bit mask. 13402 */ 13403 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 13404 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 13405 name = "MEASURED_STATE_TOO_SMALL"), 13406 }) 13407 public final int getMeasuredHeightAndState() { 13408 return mMeasuredHeight; 13409 } 13410 13411 /** 13412 * Return only the state bits of {@link #getMeasuredWidthAndState()} 13413 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 13414 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 13415 * and the height component is at the shifted bits 13416 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 13417 */ 13418 public final int getMeasuredState() { 13419 return (mMeasuredWidth&MEASURED_STATE_MASK) 13420 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 13421 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 13422 } 13423 13424 /** 13425 * The transform matrix of this view, which is calculated based on the current 13426 * rotation, scale, and pivot properties. 13427 * 13428 * @see #getRotation() 13429 * @see #getScaleX() 13430 * @see #getScaleY() 13431 * @see #getPivotX() 13432 * @see #getPivotY() 13433 * @return The current transform matrix for the view 13434 */ 13435 public Matrix getMatrix() { 13436 ensureTransformationInfo(); 13437 final Matrix matrix = mTransformationInfo.mMatrix; 13438 mRenderNode.getMatrix(matrix); 13439 return matrix; 13440 } 13441 13442 /** 13443 * Returns true if the transform matrix is the identity matrix. 13444 * Recomputes the matrix if necessary. 13445 * 13446 * @return True if the transform matrix is the identity matrix, false otherwise. 13447 */ 13448 final boolean hasIdentityMatrix() { 13449 return mRenderNode.hasIdentityMatrix(); 13450 } 13451 13452 void ensureTransformationInfo() { 13453 if (mTransformationInfo == null) { 13454 mTransformationInfo = new TransformationInfo(); 13455 } 13456 } 13457 13458 /** 13459 * Utility method to retrieve the inverse of the current mMatrix property. 13460 * We cache the matrix to avoid recalculating it when transform properties 13461 * have not changed. 13462 * 13463 * @return The inverse of the current matrix of this view. 13464 * @hide 13465 */ 13466 public final Matrix getInverseMatrix() { 13467 ensureTransformationInfo(); 13468 if (mTransformationInfo.mInverseMatrix == null) { 13469 mTransformationInfo.mInverseMatrix = new Matrix(); 13470 } 13471 final Matrix matrix = mTransformationInfo.mInverseMatrix; 13472 mRenderNode.getInverseMatrix(matrix); 13473 return matrix; 13474 } 13475 13476 /** 13477 * Gets the distance along the Z axis from the camera to this view. 13478 * 13479 * @see #setCameraDistance(float) 13480 * 13481 * @return The distance along the Z axis. 13482 */ 13483 public float getCameraDistance() { 13484 final float dpi = mResources.getDisplayMetrics().densityDpi; 13485 return -(mRenderNode.getCameraDistance() * dpi); 13486 } 13487 13488 /** 13489 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 13490 * views are drawn) from the camera to this view. The camera's distance 13491 * affects 3D transformations, for instance rotations around the X and Y 13492 * axis. If the rotationX or rotationY properties are changed and this view is 13493 * large (more than half the size of the screen), it is recommended to always 13494 * use a camera distance that's greater than the height (X axis rotation) or 13495 * the width (Y axis rotation) of this view.</p> 13496 * 13497 * <p>The distance of the camera from the view plane can have an affect on the 13498 * perspective distortion of the view when it is rotated around the x or y axis. 13499 * For example, a large distance will result in a large viewing angle, and there 13500 * will not be much perspective distortion of the view as it rotates. A short 13501 * distance may cause much more perspective distortion upon rotation, and can 13502 * also result in some drawing artifacts if the rotated view ends up partially 13503 * behind the camera (which is why the recommendation is to use a distance at 13504 * least as far as the size of the view, if the view is to be rotated.)</p> 13505 * 13506 * <p>The distance is expressed in "depth pixels." The default distance depends 13507 * on the screen density. For instance, on a medium density display, the 13508 * default distance is 1280. On a high density display, the default distance 13509 * is 1920.</p> 13510 * 13511 * <p>If you want to specify a distance that leads to visually consistent 13512 * results across various densities, use the following formula:</p> 13513 * <pre> 13514 * float scale = context.getResources().getDisplayMetrics().density; 13515 * view.setCameraDistance(distance * scale); 13516 * </pre> 13517 * 13518 * <p>The density scale factor of a high density display is 1.5, 13519 * and 1920 = 1280 * 1.5.</p> 13520 * 13521 * @param distance The distance in "depth pixels", if negative the opposite 13522 * value is used 13523 * 13524 * @see #setRotationX(float) 13525 * @see #setRotationY(float) 13526 */ 13527 public void setCameraDistance(float distance) { 13528 final float dpi = mResources.getDisplayMetrics().densityDpi; 13529 13530 invalidateViewProperty(true, false); 13531 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 13532 invalidateViewProperty(false, false); 13533 13534 invalidateParentIfNeededAndWasQuickRejected(); 13535 } 13536 13537 /** 13538 * The degrees that the view is rotated around the pivot point. 13539 * 13540 * @see #setRotation(float) 13541 * @see #getPivotX() 13542 * @see #getPivotY() 13543 * 13544 * @return The degrees of rotation. 13545 */ 13546 @ViewDebug.ExportedProperty(category = "drawing") 13547 public float getRotation() { 13548 return mRenderNode.getRotation(); 13549 } 13550 13551 /** 13552 * Sets the degrees that the view is rotated around the pivot point. Increasing values 13553 * result in clockwise rotation. 13554 * 13555 * @param rotation The degrees of rotation. 13556 * 13557 * @see #getRotation() 13558 * @see #getPivotX() 13559 * @see #getPivotY() 13560 * @see #setRotationX(float) 13561 * @see #setRotationY(float) 13562 * 13563 * @attr ref android.R.styleable#View_rotation 13564 */ 13565 public void setRotation(float rotation) { 13566 if (rotation != getRotation()) { 13567 // Double-invalidation is necessary to capture view's old and new areas 13568 invalidateViewProperty(true, false); 13569 mRenderNode.setRotation(rotation); 13570 invalidateViewProperty(false, true); 13571 13572 invalidateParentIfNeededAndWasQuickRejected(); 13573 notifySubtreeAccessibilityStateChangedIfNeeded(); 13574 } 13575 } 13576 13577 /** 13578 * The degrees that the view is rotated around the vertical axis through the pivot point. 13579 * 13580 * @see #getPivotX() 13581 * @see #getPivotY() 13582 * @see #setRotationY(float) 13583 * 13584 * @return The degrees of Y rotation. 13585 */ 13586 @ViewDebug.ExportedProperty(category = "drawing") 13587 public float getRotationY() { 13588 return mRenderNode.getRotationY(); 13589 } 13590 13591 /** 13592 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 13593 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 13594 * down the y axis. 13595 * 13596 * When rotating large views, it is recommended to adjust the camera distance 13597 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 13598 * 13599 * @param rotationY The degrees of Y rotation. 13600 * 13601 * @see #getRotationY() 13602 * @see #getPivotX() 13603 * @see #getPivotY() 13604 * @see #setRotation(float) 13605 * @see #setRotationX(float) 13606 * @see #setCameraDistance(float) 13607 * 13608 * @attr ref android.R.styleable#View_rotationY 13609 */ 13610 public void setRotationY(float rotationY) { 13611 if (rotationY != getRotationY()) { 13612 invalidateViewProperty(true, false); 13613 mRenderNode.setRotationY(rotationY); 13614 invalidateViewProperty(false, true); 13615 13616 invalidateParentIfNeededAndWasQuickRejected(); 13617 notifySubtreeAccessibilityStateChangedIfNeeded(); 13618 } 13619 } 13620 13621 /** 13622 * The degrees that the view is rotated around the horizontal axis through the pivot point. 13623 * 13624 * @see #getPivotX() 13625 * @see #getPivotY() 13626 * @see #setRotationX(float) 13627 * 13628 * @return The degrees of X rotation. 13629 */ 13630 @ViewDebug.ExportedProperty(category = "drawing") 13631 public float getRotationX() { 13632 return mRenderNode.getRotationX(); 13633 } 13634 13635 /** 13636 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 13637 * Increasing values result in clockwise rotation from the viewpoint of looking down the 13638 * x axis. 13639 * 13640 * When rotating large views, it is recommended to adjust the camera distance 13641 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 13642 * 13643 * @param rotationX The degrees of X rotation. 13644 * 13645 * @see #getRotationX() 13646 * @see #getPivotX() 13647 * @see #getPivotY() 13648 * @see #setRotation(float) 13649 * @see #setRotationY(float) 13650 * @see #setCameraDistance(float) 13651 * 13652 * @attr ref android.R.styleable#View_rotationX 13653 */ 13654 public void setRotationX(float rotationX) { 13655 if (rotationX != getRotationX()) { 13656 invalidateViewProperty(true, false); 13657 mRenderNode.setRotationX(rotationX); 13658 invalidateViewProperty(false, true); 13659 13660 invalidateParentIfNeededAndWasQuickRejected(); 13661 notifySubtreeAccessibilityStateChangedIfNeeded(); 13662 } 13663 } 13664 13665 /** 13666 * The amount that the view is scaled in x around the pivot point, as a proportion of 13667 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 13668 * 13669 * <p>By default, this is 1.0f. 13670 * 13671 * @see #getPivotX() 13672 * @see #getPivotY() 13673 * @return The scaling factor. 13674 */ 13675 @ViewDebug.ExportedProperty(category = "drawing") 13676 public float getScaleX() { 13677 return mRenderNode.getScaleX(); 13678 } 13679 13680 /** 13681 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 13682 * the view's unscaled width. A value of 1 means that no scaling is applied. 13683 * 13684 * @param scaleX The scaling factor. 13685 * @see #getPivotX() 13686 * @see #getPivotY() 13687 * 13688 * @attr ref android.R.styleable#View_scaleX 13689 */ 13690 public void setScaleX(float scaleX) { 13691 if (scaleX != getScaleX()) { 13692 invalidateViewProperty(true, false); 13693 mRenderNode.setScaleX(scaleX); 13694 invalidateViewProperty(false, true); 13695 13696 invalidateParentIfNeededAndWasQuickRejected(); 13697 notifySubtreeAccessibilityStateChangedIfNeeded(); 13698 } 13699 } 13700 13701 /** 13702 * The amount that the view is scaled in y around the pivot point, as a proportion of 13703 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 13704 * 13705 * <p>By default, this is 1.0f. 13706 * 13707 * @see #getPivotX() 13708 * @see #getPivotY() 13709 * @return The scaling factor. 13710 */ 13711 @ViewDebug.ExportedProperty(category = "drawing") 13712 public float getScaleY() { 13713 return mRenderNode.getScaleY(); 13714 } 13715 13716 /** 13717 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 13718 * the view's unscaled width. A value of 1 means that no scaling is applied. 13719 * 13720 * @param scaleY The scaling factor. 13721 * @see #getPivotX() 13722 * @see #getPivotY() 13723 * 13724 * @attr ref android.R.styleable#View_scaleY 13725 */ 13726 public void setScaleY(float scaleY) { 13727 if (scaleY != getScaleY()) { 13728 invalidateViewProperty(true, false); 13729 mRenderNode.setScaleY(scaleY); 13730 invalidateViewProperty(false, true); 13731 13732 invalidateParentIfNeededAndWasQuickRejected(); 13733 notifySubtreeAccessibilityStateChangedIfNeeded(); 13734 } 13735 } 13736 13737 /** 13738 * The x location of the point around which the view is {@link #setRotation(float) rotated} 13739 * and {@link #setScaleX(float) scaled}. 13740 * 13741 * @see #getRotation() 13742 * @see #getScaleX() 13743 * @see #getScaleY() 13744 * @see #getPivotY() 13745 * @return The x location of the pivot point. 13746 * 13747 * @attr ref android.R.styleable#View_transformPivotX 13748 */ 13749 @ViewDebug.ExportedProperty(category = "drawing") 13750 public float getPivotX() { 13751 return mRenderNode.getPivotX(); 13752 } 13753 13754 /** 13755 * Sets the x location of the point around which the view is 13756 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 13757 * By default, the pivot point is centered on the object. 13758 * Setting this property disables this behavior and causes the view to use only the 13759 * explicitly set pivotX and pivotY values. 13760 * 13761 * @param pivotX The x location of the pivot point. 13762 * @see #getRotation() 13763 * @see #getScaleX() 13764 * @see #getScaleY() 13765 * @see #getPivotY() 13766 * 13767 * @attr ref android.R.styleable#View_transformPivotX 13768 */ 13769 public void setPivotX(float pivotX) { 13770 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 13771 invalidateViewProperty(true, false); 13772 mRenderNode.setPivotX(pivotX); 13773 invalidateViewProperty(false, true); 13774 13775 invalidateParentIfNeededAndWasQuickRejected(); 13776 } 13777 } 13778 13779 /** 13780 * The y location of the point around which the view is {@link #setRotation(float) rotated} 13781 * and {@link #setScaleY(float) scaled}. 13782 * 13783 * @see #getRotation() 13784 * @see #getScaleX() 13785 * @see #getScaleY() 13786 * @see #getPivotY() 13787 * @return The y location of the pivot point. 13788 * 13789 * @attr ref android.R.styleable#View_transformPivotY 13790 */ 13791 @ViewDebug.ExportedProperty(category = "drawing") 13792 public float getPivotY() { 13793 return mRenderNode.getPivotY(); 13794 } 13795 13796 /** 13797 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 13798 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 13799 * Setting this property disables this behavior and causes the view to use only the 13800 * explicitly set pivotX and pivotY values. 13801 * 13802 * @param pivotY The y location of the pivot point. 13803 * @see #getRotation() 13804 * @see #getScaleX() 13805 * @see #getScaleY() 13806 * @see #getPivotY() 13807 * 13808 * @attr ref android.R.styleable#View_transformPivotY 13809 */ 13810 public void setPivotY(float pivotY) { 13811 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 13812 invalidateViewProperty(true, false); 13813 mRenderNode.setPivotY(pivotY); 13814 invalidateViewProperty(false, true); 13815 13816 invalidateParentIfNeededAndWasQuickRejected(); 13817 } 13818 } 13819 13820 /** 13821 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 13822 * completely transparent and 1 means the view is completely opaque. 13823 * 13824 * <p>By default this is 1.0f. 13825 * @return The opacity of the view. 13826 */ 13827 @ViewDebug.ExportedProperty(category = "drawing") 13828 public float getAlpha() { 13829 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 13830 } 13831 13832 /** 13833 * Sets the behavior for overlapping rendering for this view (see {@link 13834 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 13835 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 13836 * providing the value which is then used internally. That is, when {@link 13837 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 13838 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 13839 * instead. 13840 * 13841 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 13842 * instead of that returned by {@link #hasOverlappingRendering()}. 13843 * 13844 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 13845 */ 13846 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 13847 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 13848 if (hasOverlappingRendering) { 13849 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 13850 } else { 13851 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 13852 } 13853 } 13854 13855 /** 13856 * Returns the value for overlapping rendering that is used internally. This is either 13857 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 13858 * the return value of {@link #hasOverlappingRendering()}, otherwise. 13859 * 13860 * @return The value for overlapping rendering being used internally. 13861 */ 13862 public final boolean getHasOverlappingRendering() { 13863 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 13864 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 13865 hasOverlappingRendering(); 13866 } 13867 13868 /** 13869 * Returns whether this View has content which overlaps. 13870 * 13871 * <p>This function, intended to be overridden by specific View types, is an optimization when 13872 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 13873 * an offscreen buffer and then composited into place, which can be expensive. If the view has 13874 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 13875 * directly. An example of overlapping rendering is a TextView with a background image, such as 13876 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 13877 * ImageView with only the foreground image. The default implementation returns true; subclasses 13878 * should override if they have cases which can be optimized.</p> 13879 * 13880 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 13881 * necessitates that a View return true if it uses the methods internally without passing the 13882 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 13883 * 13884 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 13885 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 13886 * 13887 * @return true if the content in this view might overlap, false otherwise. 13888 */ 13889 @ViewDebug.ExportedProperty(category = "drawing") 13890 public boolean hasOverlappingRendering() { 13891 return true; 13892 } 13893 13894 /** 13895 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 13896 * completely transparent and 1 means the view is completely opaque. 13897 * 13898 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 13899 * can have significant performance implications, especially for large views. It is best to use 13900 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 13901 * 13902 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 13903 * strongly recommended for performance reasons to either override 13904 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 13905 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 13906 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 13907 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 13908 * of rendering cost, even for simple or small views. Starting with 13909 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 13910 * applied to the view at the rendering level.</p> 13911 * 13912 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 13913 * responsible for applying the opacity itself.</p> 13914 * 13915 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 13916 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 13917 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 13918 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 13919 * 13920 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 13921 * value will clip a View to its bounds, unless the View returns <code>false</code> from 13922 * {@link #hasOverlappingRendering}.</p> 13923 * 13924 * @param alpha The opacity of the view. 13925 * 13926 * @see #hasOverlappingRendering() 13927 * @see #setLayerType(int, android.graphics.Paint) 13928 * 13929 * @attr ref android.R.styleable#View_alpha 13930 */ 13931 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 13932 ensureTransformationInfo(); 13933 if (mTransformationInfo.mAlpha != alpha) { 13934 // Report visibility changes, which can affect children, to accessibility 13935 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 13936 notifySubtreeAccessibilityStateChangedIfNeeded(); 13937 } 13938 mTransformationInfo.mAlpha = alpha; 13939 if (onSetAlpha((int) (alpha * 255))) { 13940 mPrivateFlags |= PFLAG_ALPHA_SET; 13941 // subclass is handling alpha - don't optimize rendering cache invalidation 13942 invalidateParentCaches(); 13943 invalidate(true); 13944 } else { 13945 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13946 invalidateViewProperty(true, false); 13947 mRenderNode.setAlpha(getFinalAlpha()); 13948 } 13949 } 13950 } 13951 13952 /** 13953 * Faster version of setAlpha() which performs the same steps except there are 13954 * no calls to invalidate(). The caller of this function should perform proper invalidation 13955 * on the parent and this object. The return value indicates whether the subclass handles 13956 * alpha (the return value for onSetAlpha()). 13957 * 13958 * @param alpha The new value for the alpha property 13959 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 13960 * the new value for the alpha property is different from the old value 13961 */ 13962 boolean setAlphaNoInvalidation(float alpha) { 13963 ensureTransformationInfo(); 13964 if (mTransformationInfo.mAlpha != alpha) { 13965 mTransformationInfo.mAlpha = alpha; 13966 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 13967 if (subclassHandlesAlpha) { 13968 mPrivateFlags |= PFLAG_ALPHA_SET; 13969 return true; 13970 } else { 13971 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13972 mRenderNode.setAlpha(getFinalAlpha()); 13973 } 13974 } 13975 return false; 13976 } 13977 13978 /** 13979 * This property is hidden and intended only for use by the Fade transition, which 13980 * animates it to produce a visual translucency that does not side-effect (or get 13981 * affected by) the real alpha property. This value is composited with the other 13982 * alpha value (and the AlphaAnimation value, when that is present) to produce 13983 * a final visual translucency result, which is what is passed into the DisplayList. 13984 * 13985 * @hide 13986 */ 13987 public void setTransitionAlpha(float alpha) { 13988 ensureTransformationInfo(); 13989 if (mTransformationInfo.mTransitionAlpha != alpha) { 13990 mTransformationInfo.mTransitionAlpha = alpha; 13991 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13992 invalidateViewProperty(true, false); 13993 mRenderNode.setAlpha(getFinalAlpha()); 13994 } 13995 } 13996 13997 /** 13998 * Calculates the visual alpha of this view, which is a combination of the actual 13999 * alpha value and the transitionAlpha value (if set). 14000 */ 14001 private float getFinalAlpha() { 14002 if (mTransformationInfo != null) { 14003 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 14004 } 14005 return 1; 14006 } 14007 14008 /** 14009 * This property is hidden and intended only for use by the Fade transition, which 14010 * animates it to produce a visual translucency that does not side-effect (or get 14011 * affected by) the real alpha property. This value is composited with the other 14012 * alpha value (and the AlphaAnimation value, when that is present) to produce 14013 * a final visual translucency result, which is what is passed into the DisplayList. 14014 * 14015 * @hide 14016 */ 14017 @ViewDebug.ExportedProperty(category = "drawing") 14018 public float getTransitionAlpha() { 14019 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 14020 } 14021 14022 /** 14023 * Top position of this view relative to its parent. 14024 * 14025 * @return The top of this view, in pixels. 14026 */ 14027 @ViewDebug.CapturedViewProperty 14028 public final int getTop() { 14029 return mTop; 14030 } 14031 14032 /** 14033 * Sets the top position of this view relative to its parent. This method is meant to be called 14034 * by the layout system and should not generally be called otherwise, because the property 14035 * may be changed at any time by the layout. 14036 * 14037 * @param top The top of this view, in pixels. 14038 */ 14039 public final void setTop(int top) { 14040 if (top != mTop) { 14041 final boolean matrixIsIdentity = hasIdentityMatrix(); 14042 if (matrixIsIdentity) { 14043 if (mAttachInfo != null) { 14044 int minTop; 14045 int yLoc; 14046 if (top < mTop) { 14047 minTop = top; 14048 yLoc = top - mTop; 14049 } else { 14050 minTop = mTop; 14051 yLoc = 0; 14052 } 14053 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 14054 } 14055 } else { 14056 // Double-invalidation is necessary to capture view's old and new areas 14057 invalidate(true); 14058 } 14059 14060 int width = mRight - mLeft; 14061 int oldHeight = mBottom - mTop; 14062 14063 mTop = top; 14064 mRenderNode.setTop(mTop); 14065 14066 sizeChange(width, mBottom - mTop, width, oldHeight); 14067 14068 if (!matrixIsIdentity) { 14069 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14070 invalidate(true); 14071 } 14072 mBackgroundSizeChanged = true; 14073 mDefaultFocusHighlightSizeChanged = true; 14074 if (mForegroundInfo != null) { 14075 mForegroundInfo.mBoundsChanged = true; 14076 } 14077 invalidateParentIfNeeded(); 14078 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14079 // View was rejected last time it was drawn by its parent; this may have changed 14080 invalidateParentIfNeeded(); 14081 } 14082 } 14083 } 14084 14085 /** 14086 * Bottom position of this view relative to its parent. 14087 * 14088 * @return The bottom of this view, in pixels. 14089 */ 14090 @ViewDebug.CapturedViewProperty 14091 public final int getBottom() { 14092 return mBottom; 14093 } 14094 14095 /** 14096 * True if this view has changed since the last time being drawn. 14097 * 14098 * @return The dirty state of this view. 14099 */ 14100 public boolean isDirty() { 14101 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 14102 } 14103 14104 /** 14105 * Sets the bottom position of this view relative to its parent. This method is meant to be 14106 * called by the layout system and should not generally be called otherwise, because the 14107 * property may be changed at any time by the layout. 14108 * 14109 * @param bottom The bottom of this view, in pixels. 14110 */ 14111 public final void setBottom(int bottom) { 14112 if (bottom != mBottom) { 14113 final boolean matrixIsIdentity = hasIdentityMatrix(); 14114 if (matrixIsIdentity) { 14115 if (mAttachInfo != null) { 14116 int maxBottom; 14117 if (bottom < mBottom) { 14118 maxBottom = mBottom; 14119 } else { 14120 maxBottom = bottom; 14121 } 14122 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 14123 } 14124 } else { 14125 // Double-invalidation is necessary to capture view's old and new areas 14126 invalidate(true); 14127 } 14128 14129 int width = mRight - mLeft; 14130 int oldHeight = mBottom - mTop; 14131 14132 mBottom = bottom; 14133 mRenderNode.setBottom(mBottom); 14134 14135 sizeChange(width, mBottom - mTop, width, oldHeight); 14136 14137 if (!matrixIsIdentity) { 14138 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14139 invalidate(true); 14140 } 14141 mBackgroundSizeChanged = true; 14142 mDefaultFocusHighlightSizeChanged = true; 14143 if (mForegroundInfo != null) { 14144 mForegroundInfo.mBoundsChanged = true; 14145 } 14146 invalidateParentIfNeeded(); 14147 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14148 // View was rejected last time it was drawn by its parent; this may have changed 14149 invalidateParentIfNeeded(); 14150 } 14151 } 14152 } 14153 14154 /** 14155 * Left position of this view relative to its parent. 14156 * 14157 * @return The left edge of this view, in pixels. 14158 */ 14159 @ViewDebug.CapturedViewProperty 14160 public final int getLeft() { 14161 return mLeft; 14162 } 14163 14164 /** 14165 * Sets the left position of this view relative to its parent. This method is meant to be called 14166 * by the layout system and should not generally be called otherwise, because the property 14167 * may be changed at any time by the layout. 14168 * 14169 * @param left The left of this view, in pixels. 14170 */ 14171 public final void setLeft(int left) { 14172 if (left != mLeft) { 14173 final boolean matrixIsIdentity = hasIdentityMatrix(); 14174 if (matrixIsIdentity) { 14175 if (mAttachInfo != null) { 14176 int minLeft; 14177 int xLoc; 14178 if (left < mLeft) { 14179 minLeft = left; 14180 xLoc = left - mLeft; 14181 } else { 14182 minLeft = mLeft; 14183 xLoc = 0; 14184 } 14185 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 14186 } 14187 } else { 14188 // Double-invalidation is necessary to capture view's old and new areas 14189 invalidate(true); 14190 } 14191 14192 int oldWidth = mRight - mLeft; 14193 int height = mBottom - mTop; 14194 14195 mLeft = left; 14196 mRenderNode.setLeft(left); 14197 14198 sizeChange(mRight - mLeft, height, oldWidth, height); 14199 14200 if (!matrixIsIdentity) { 14201 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14202 invalidate(true); 14203 } 14204 mBackgroundSizeChanged = true; 14205 mDefaultFocusHighlightSizeChanged = true; 14206 if (mForegroundInfo != null) { 14207 mForegroundInfo.mBoundsChanged = true; 14208 } 14209 invalidateParentIfNeeded(); 14210 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14211 // View was rejected last time it was drawn by its parent; this may have changed 14212 invalidateParentIfNeeded(); 14213 } 14214 } 14215 } 14216 14217 /** 14218 * Right position of this view relative to its parent. 14219 * 14220 * @return The right edge of this view, in pixels. 14221 */ 14222 @ViewDebug.CapturedViewProperty 14223 public final int getRight() { 14224 return mRight; 14225 } 14226 14227 /** 14228 * Sets the right position of this view relative to its parent. This method is meant to be called 14229 * by the layout system and should not generally be called otherwise, because the property 14230 * may be changed at any time by the layout. 14231 * 14232 * @param right The right of this view, in pixels. 14233 */ 14234 public final void setRight(int right) { 14235 if (right != mRight) { 14236 final boolean matrixIsIdentity = hasIdentityMatrix(); 14237 if (matrixIsIdentity) { 14238 if (mAttachInfo != null) { 14239 int maxRight; 14240 if (right < mRight) { 14241 maxRight = mRight; 14242 } else { 14243 maxRight = right; 14244 } 14245 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 14246 } 14247 } else { 14248 // Double-invalidation is necessary to capture view's old and new areas 14249 invalidate(true); 14250 } 14251 14252 int oldWidth = mRight - mLeft; 14253 int height = mBottom - mTop; 14254 14255 mRight = right; 14256 mRenderNode.setRight(mRight); 14257 14258 sizeChange(mRight - mLeft, height, oldWidth, height); 14259 14260 if (!matrixIsIdentity) { 14261 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14262 invalidate(true); 14263 } 14264 mBackgroundSizeChanged = true; 14265 mDefaultFocusHighlightSizeChanged = true; 14266 if (mForegroundInfo != null) { 14267 mForegroundInfo.mBoundsChanged = true; 14268 } 14269 invalidateParentIfNeeded(); 14270 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14271 // View was rejected last time it was drawn by its parent; this may have changed 14272 invalidateParentIfNeeded(); 14273 } 14274 } 14275 } 14276 14277 /** 14278 * The visual x position of this view, in pixels. This is equivalent to the 14279 * {@link #setTranslationX(float) translationX} property plus the current 14280 * {@link #getLeft() left} property. 14281 * 14282 * @return The visual x position of this view, in pixels. 14283 */ 14284 @ViewDebug.ExportedProperty(category = "drawing") 14285 public float getX() { 14286 return mLeft + getTranslationX(); 14287 } 14288 14289 /** 14290 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 14291 * {@link #setTranslationX(float) translationX} property to be the difference between 14292 * the x value passed in and the current {@link #getLeft() left} property. 14293 * 14294 * @param x The visual x position of this view, in pixels. 14295 */ 14296 public void setX(float x) { 14297 setTranslationX(x - mLeft); 14298 } 14299 14300 /** 14301 * The visual y position of this view, in pixels. This is equivalent to the 14302 * {@link #setTranslationY(float) translationY} property plus the current 14303 * {@link #getTop() top} property. 14304 * 14305 * @return The visual y position of this view, in pixels. 14306 */ 14307 @ViewDebug.ExportedProperty(category = "drawing") 14308 public float getY() { 14309 return mTop + getTranslationY(); 14310 } 14311 14312 /** 14313 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 14314 * {@link #setTranslationY(float) translationY} property to be the difference between 14315 * the y value passed in and the current {@link #getTop() top} property. 14316 * 14317 * @param y The visual y position of this view, in pixels. 14318 */ 14319 public void setY(float y) { 14320 setTranslationY(y - mTop); 14321 } 14322 14323 /** 14324 * The visual z position of this view, in pixels. This is equivalent to the 14325 * {@link #setTranslationZ(float) translationZ} property plus the current 14326 * {@link #getElevation() elevation} property. 14327 * 14328 * @return The visual z position of this view, in pixels. 14329 */ 14330 @ViewDebug.ExportedProperty(category = "drawing") 14331 public float getZ() { 14332 return getElevation() + getTranslationZ(); 14333 } 14334 14335 /** 14336 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 14337 * {@link #setTranslationZ(float) translationZ} property to be the difference between 14338 * the x value passed in and the current {@link #getElevation() elevation} property. 14339 * 14340 * @param z The visual z position of this view, in pixels. 14341 */ 14342 public void setZ(float z) { 14343 setTranslationZ(z - getElevation()); 14344 } 14345 14346 /** 14347 * The base elevation of this view relative to its parent, in pixels. 14348 * 14349 * @return The base depth position of the view, in pixels. 14350 */ 14351 @ViewDebug.ExportedProperty(category = "drawing") 14352 public float getElevation() { 14353 return mRenderNode.getElevation(); 14354 } 14355 14356 /** 14357 * Sets the base elevation of this view, in pixels. 14358 * 14359 * @attr ref android.R.styleable#View_elevation 14360 */ 14361 public void setElevation(float elevation) { 14362 if (elevation != getElevation()) { 14363 invalidateViewProperty(true, false); 14364 mRenderNode.setElevation(elevation); 14365 invalidateViewProperty(false, true); 14366 14367 invalidateParentIfNeededAndWasQuickRejected(); 14368 } 14369 } 14370 14371 /** 14372 * The horizontal location of this view relative to its {@link #getLeft() left} position. 14373 * This position is post-layout, in addition to wherever the object's 14374 * layout placed it. 14375 * 14376 * @return The horizontal position of this view relative to its left position, in pixels. 14377 */ 14378 @ViewDebug.ExportedProperty(category = "drawing") 14379 public float getTranslationX() { 14380 return mRenderNode.getTranslationX(); 14381 } 14382 14383 /** 14384 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 14385 * This effectively positions the object post-layout, in addition to wherever the object's 14386 * layout placed it. 14387 * 14388 * @param translationX The horizontal position of this view relative to its left position, 14389 * in pixels. 14390 * 14391 * @attr ref android.R.styleable#View_translationX 14392 */ 14393 public void setTranslationX(float translationX) { 14394 if (translationX != getTranslationX()) { 14395 invalidateViewProperty(true, false); 14396 mRenderNode.setTranslationX(translationX); 14397 invalidateViewProperty(false, true); 14398 14399 invalidateParentIfNeededAndWasQuickRejected(); 14400 notifySubtreeAccessibilityStateChangedIfNeeded(); 14401 } 14402 } 14403 14404 /** 14405 * The vertical location of this view relative to its {@link #getTop() top} position. 14406 * This position is post-layout, in addition to wherever the object's 14407 * layout placed it. 14408 * 14409 * @return The vertical position of this view relative to its top position, 14410 * in pixels. 14411 */ 14412 @ViewDebug.ExportedProperty(category = "drawing") 14413 public float getTranslationY() { 14414 return mRenderNode.getTranslationY(); 14415 } 14416 14417 /** 14418 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 14419 * This effectively positions the object post-layout, in addition to wherever the object's 14420 * layout placed it. 14421 * 14422 * @param translationY The vertical position of this view relative to its top position, 14423 * in pixels. 14424 * 14425 * @attr ref android.R.styleable#View_translationY 14426 */ 14427 public void setTranslationY(float translationY) { 14428 if (translationY != getTranslationY()) { 14429 invalidateViewProperty(true, false); 14430 mRenderNode.setTranslationY(translationY); 14431 invalidateViewProperty(false, true); 14432 14433 invalidateParentIfNeededAndWasQuickRejected(); 14434 notifySubtreeAccessibilityStateChangedIfNeeded(); 14435 } 14436 } 14437 14438 /** 14439 * The depth location of this view relative to its {@link #getElevation() elevation}. 14440 * 14441 * @return The depth of this view relative to its elevation. 14442 */ 14443 @ViewDebug.ExportedProperty(category = "drawing") 14444 public float getTranslationZ() { 14445 return mRenderNode.getTranslationZ(); 14446 } 14447 14448 /** 14449 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 14450 * 14451 * @attr ref android.R.styleable#View_translationZ 14452 */ 14453 public void setTranslationZ(float translationZ) { 14454 if (translationZ != getTranslationZ()) { 14455 invalidateViewProperty(true, false); 14456 mRenderNode.setTranslationZ(translationZ); 14457 invalidateViewProperty(false, true); 14458 14459 invalidateParentIfNeededAndWasQuickRejected(); 14460 } 14461 } 14462 14463 /** @hide */ 14464 public void setAnimationMatrix(Matrix matrix) { 14465 invalidateViewProperty(true, false); 14466 mRenderNode.setAnimationMatrix(matrix); 14467 invalidateViewProperty(false, true); 14468 14469 invalidateParentIfNeededAndWasQuickRejected(); 14470 } 14471 14472 /** 14473 * Returns the current StateListAnimator if exists. 14474 * 14475 * @return StateListAnimator or null if it does not exists 14476 * @see #setStateListAnimator(android.animation.StateListAnimator) 14477 */ 14478 public StateListAnimator getStateListAnimator() { 14479 return mStateListAnimator; 14480 } 14481 14482 /** 14483 * Attaches the provided StateListAnimator to this View. 14484 * <p> 14485 * Any previously attached StateListAnimator will be detached. 14486 * 14487 * @param stateListAnimator The StateListAnimator to update the view 14488 * @see android.animation.StateListAnimator 14489 */ 14490 public void setStateListAnimator(StateListAnimator stateListAnimator) { 14491 if (mStateListAnimator == stateListAnimator) { 14492 return; 14493 } 14494 if (mStateListAnimator != null) { 14495 mStateListAnimator.setTarget(null); 14496 } 14497 mStateListAnimator = stateListAnimator; 14498 if (stateListAnimator != null) { 14499 stateListAnimator.setTarget(this); 14500 if (isAttachedToWindow()) { 14501 stateListAnimator.setState(getDrawableState()); 14502 } 14503 } 14504 } 14505 14506 /** 14507 * Returns whether the Outline should be used to clip the contents of the View. 14508 * <p> 14509 * Note that this flag will only be respected if the View's Outline returns true from 14510 * {@link Outline#canClip()}. 14511 * 14512 * @see #setOutlineProvider(ViewOutlineProvider) 14513 * @see #setClipToOutline(boolean) 14514 */ 14515 public final boolean getClipToOutline() { 14516 return mRenderNode.getClipToOutline(); 14517 } 14518 14519 /** 14520 * Sets whether the View's Outline should be used to clip the contents of the View. 14521 * <p> 14522 * Only a single non-rectangular clip can be applied on a View at any time. 14523 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 14524 * circular reveal} animation take priority over Outline clipping, and 14525 * child Outline clipping takes priority over Outline clipping done by a 14526 * parent. 14527 * <p> 14528 * Note that this flag will only be respected if the View's Outline returns true from 14529 * {@link Outline#canClip()}. 14530 * 14531 * @see #setOutlineProvider(ViewOutlineProvider) 14532 * @see #getClipToOutline() 14533 */ 14534 public void setClipToOutline(boolean clipToOutline) { 14535 damageInParent(); 14536 if (getClipToOutline() != clipToOutline) { 14537 mRenderNode.setClipToOutline(clipToOutline); 14538 } 14539 } 14540 14541 // correspond to the enum values of View_outlineProvider 14542 private static final int PROVIDER_BACKGROUND = 0; 14543 private static final int PROVIDER_NONE = 1; 14544 private static final int PROVIDER_BOUNDS = 2; 14545 private static final int PROVIDER_PADDED_BOUNDS = 3; 14546 private void setOutlineProviderFromAttribute(int providerInt) { 14547 switch (providerInt) { 14548 case PROVIDER_BACKGROUND: 14549 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 14550 break; 14551 case PROVIDER_NONE: 14552 setOutlineProvider(null); 14553 break; 14554 case PROVIDER_BOUNDS: 14555 setOutlineProvider(ViewOutlineProvider.BOUNDS); 14556 break; 14557 case PROVIDER_PADDED_BOUNDS: 14558 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 14559 break; 14560 } 14561 } 14562 14563 /** 14564 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 14565 * the shape of the shadow it casts, and enables outline clipping. 14566 * <p> 14567 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 14568 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 14569 * outline provider with this method allows this behavior to be overridden. 14570 * <p> 14571 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 14572 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 14573 * <p> 14574 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 14575 * 14576 * @see #setClipToOutline(boolean) 14577 * @see #getClipToOutline() 14578 * @see #getOutlineProvider() 14579 */ 14580 public void setOutlineProvider(ViewOutlineProvider provider) { 14581 mOutlineProvider = provider; 14582 invalidateOutline(); 14583 } 14584 14585 /** 14586 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 14587 * that defines the shape of the shadow it casts, and enables outline clipping. 14588 * 14589 * @see #setOutlineProvider(ViewOutlineProvider) 14590 */ 14591 public ViewOutlineProvider getOutlineProvider() { 14592 return mOutlineProvider; 14593 } 14594 14595 /** 14596 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 14597 * 14598 * @see #setOutlineProvider(ViewOutlineProvider) 14599 */ 14600 public void invalidateOutline() { 14601 rebuildOutline(); 14602 14603 notifySubtreeAccessibilityStateChangedIfNeeded(); 14604 invalidateViewProperty(false, false); 14605 } 14606 14607 /** 14608 * Internal version of {@link #invalidateOutline()} which invalidates the 14609 * outline without invalidating the view itself. This is intended to be called from 14610 * within methods in the View class itself which are the result of the view being 14611 * invalidated already. For example, when we are drawing the background of a View, 14612 * we invalidate the outline in case it changed in the meantime, but we do not 14613 * need to invalidate the view because we're already drawing the background as part 14614 * of drawing the view in response to an earlier invalidation of the view. 14615 */ 14616 private void rebuildOutline() { 14617 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 14618 if (mAttachInfo == null) return; 14619 14620 if (mOutlineProvider == null) { 14621 // no provider, remove outline 14622 mRenderNode.setOutline(null); 14623 } else { 14624 final Outline outline = mAttachInfo.mTmpOutline; 14625 outline.setEmpty(); 14626 outline.setAlpha(1.0f); 14627 14628 mOutlineProvider.getOutline(this, outline); 14629 mRenderNode.setOutline(outline); 14630 } 14631 } 14632 14633 /** 14634 * HierarchyViewer only 14635 * 14636 * @hide 14637 */ 14638 @ViewDebug.ExportedProperty(category = "drawing") 14639 public boolean hasShadow() { 14640 return mRenderNode.hasShadow(); 14641 } 14642 14643 14644 /** @hide */ 14645 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 14646 mRenderNode.setRevealClip(shouldClip, x, y, radius); 14647 invalidateViewProperty(false, false); 14648 } 14649 14650 /** 14651 * Hit rectangle in parent's coordinates 14652 * 14653 * @param outRect The hit rectangle of the view. 14654 */ 14655 public void getHitRect(Rect outRect) { 14656 if (hasIdentityMatrix() || mAttachInfo == null) { 14657 outRect.set(mLeft, mTop, mRight, mBottom); 14658 } else { 14659 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 14660 tmpRect.set(0, 0, getWidth(), getHeight()); 14661 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 14662 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 14663 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 14664 } 14665 } 14666 14667 /** 14668 * Determines whether the given point, in local coordinates is inside the view. 14669 */ 14670 /*package*/ final boolean pointInView(float localX, float localY) { 14671 return pointInView(localX, localY, 0); 14672 } 14673 14674 /** 14675 * Utility method to determine whether the given point, in local coordinates, 14676 * is inside the view, where the area of the view is expanded by the slop factor. 14677 * This method is called while processing touch-move events to determine if the event 14678 * is still within the view. 14679 * 14680 * @hide 14681 */ 14682 public boolean pointInView(float localX, float localY, float slop) { 14683 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 14684 localY < ((mBottom - mTop) + slop); 14685 } 14686 14687 /** 14688 * When a view has focus and the user navigates away from it, the next view is searched for 14689 * starting from the rectangle filled in by this method. 14690 * 14691 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 14692 * of the view. However, if your view maintains some idea of internal selection, 14693 * such as a cursor, or a selected row or column, you should override this method and 14694 * fill in a more specific rectangle. 14695 * 14696 * @param r The rectangle to fill in, in this view's coordinates. 14697 */ 14698 public void getFocusedRect(Rect r) { 14699 getDrawingRect(r); 14700 } 14701 14702 /** 14703 * If some part of this view is not clipped by any of its parents, then 14704 * return that area in r in global (root) coordinates. To convert r to local 14705 * coordinates (without taking possible View rotations into account), offset 14706 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 14707 * If the view is completely clipped or translated out, return false. 14708 * 14709 * @param r If true is returned, r holds the global coordinates of the 14710 * visible portion of this view. 14711 * @param globalOffset If true is returned, globalOffset holds the dx,dy 14712 * between this view and its root. globalOffet may be null. 14713 * @return true if r is non-empty (i.e. part of the view is visible at the 14714 * root level. 14715 */ 14716 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 14717 int width = mRight - mLeft; 14718 int height = mBottom - mTop; 14719 if (width > 0 && height > 0) { 14720 r.set(0, 0, width, height); 14721 if (globalOffset != null) { 14722 globalOffset.set(-mScrollX, -mScrollY); 14723 } 14724 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 14725 } 14726 return false; 14727 } 14728 14729 public final boolean getGlobalVisibleRect(Rect r) { 14730 return getGlobalVisibleRect(r, null); 14731 } 14732 14733 public final boolean getLocalVisibleRect(Rect r) { 14734 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 14735 if (getGlobalVisibleRect(r, offset)) { 14736 r.offset(-offset.x, -offset.y); // make r local 14737 return true; 14738 } 14739 return false; 14740 } 14741 14742 /** 14743 * Offset this view's vertical location by the specified number of pixels. 14744 * 14745 * @param offset the number of pixels to offset the view by 14746 */ 14747 public void offsetTopAndBottom(int offset) { 14748 if (offset != 0) { 14749 final boolean matrixIsIdentity = hasIdentityMatrix(); 14750 if (matrixIsIdentity) { 14751 if (isHardwareAccelerated()) { 14752 invalidateViewProperty(false, false); 14753 } else { 14754 final ViewParent p = mParent; 14755 if (p != null && mAttachInfo != null) { 14756 final Rect r = mAttachInfo.mTmpInvalRect; 14757 int minTop; 14758 int maxBottom; 14759 int yLoc; 14760 if (offset < 0) { 14761 minTop = mTop + offset; 14762 maxBottom = mBottom; 14763 yLoc = offset; 14764 } else { 14765 minTop = mTop; 14766 maxBottom = mBottom + offset; 14767 yLoc = 0; 14768 } 14769 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 14770 p.invalidateChild(this, r); 14771 } 14772 } 14773 } else { 14774 invalidateViewProperty(false, false); 14775 } 14776 14777 mTop += offset; 14778 mBottom += offset; 14779 mRenderNode.offsetTopAndBottom(offset); 14780 if (isHardwareAccelerated()) { 14781 invalidateViewProperty(false, false); 14782 invalidateParentIfNeededAndWasQuickRejected(); 14783 } else { 14784 if (!matrixIsIdentity) { 14785 invalidateViewProperty(false, true); 14786 } 14787 invalidateParentIfNeeded(); 14788 } 14789 notifySubtreeAccessibilityStateChangedIfNeeded(); 14790 } 14791 } 14792 14793 /** 14794 * Offset this view's horizontal location by the specified amount of pixels. 14795 * 14796 * @param offset the number of pixels to offset the view by 14797 */ 14798 public void offsetLeftAndRight(int offset) { 14799 if (offset != 0) { 14800 final boolean matrixIsIdentity = hasIdentityMatrix(); 14801 if (matrixIsIdentity) { 14802 if (isHardwareAccelerated()) { 14803 invalidateViewProperty(false, false); 14804 } else { 14805 final ViewParent p = mParent; 14806 if (p != null && mAttachInfo != null) { 14807 final Rect r = mAttachInfo.mTmpInvalRect; 14808 int minLeft; 14809 int maxRight; 14810 if (offset < 0) { 14811 minLeft = mLeft + offset; 14812 maxRight = mRight; 14813 } else { 14814 minLeft = mLeft; 14815 maxRight = mRight + offset; 14816 } 14817 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 14818 p.invalidateChild(this, r); 14819 } 14820 } 14821 } else { 14822 invalidateViewProperty(false, false); 14823 } 14824 14825 mLeft += offset; 14826 mRight += offset; 14827 mRenderNode.offsetLeftAndRight(offset); 14828 if (isHardwareAccelerated()) { 14829 invalidateViewProperty(false, false); 14830 invalidateParentIfNeededAndWasQuickRejected(); 14831 } else { 14832 if (!matrixIsIdentity) { 14833 invalidateViewProperty(false, true); 14834 } 14835 invalidateParentIfNeeded(); 14836 } 14837 notifySubtreeAccessibilityStateChangedIfNeeded(); 14838 } 14839 } 14840 14841 /** 14842 * Get the LayoutParams associated with this view. All views should have 14843 * layout parameters. These supply parameters to the <i>parent</i> of this 14844 * view specifying how it should be arranged. There are many subclasses of 14845 * ViewGroup.LayoutParams, and these correspond to the different subclasses 14846 * of ViewGroup that are responsible for arranging their children. 14847 * 14848 * This method may return null if this View is not attached to a parent 14849 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 14850 * was not invoked successfully. When a View is attached to a parent 14851 * ViewGroup, this method must not return null. 14852 * 14853 * @return The LayoutParams associated with this view, or null if no 14854 * parameters have been set yet 14855 */ 14856 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 14857 public ViewGroup.LayoutParams getLayoutParams() { 14858 return mLayoutParams; 14859 } 14860 14861 /** 14862 * Set the layout parameters associated with this view. These supply 14863 * parameters to the <i>parent</i> of this view specifying how it should be 14864 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 14865 * correspond to the different subclasses of ViewGroup that are responsible 14866 * for arranging their children. 14867 * 14868 * @param params The layout parameters for this view, cannot be null 14869 */ 14870 public void setLayoutParams(ViewGroup.LayoutParams params) { 14871 if (params == null) { 14872 throw new NullPointerException("Layout parameters cannot be null"); 14873 } 14874 mLayoutParams = params; 14875 resolveLayoutParams(); 14876 if (mParent instanceof ViewGroup) { 14877 ((ViewGroup) mParent).onSetLayoutParams(this, params); 14878 } 14879 requestLayout(); 14880 } 14881 14882 /** 14883 * Resolve the layout parameters depending on the resolved layout direction 14884 * 14885 * @hide 14886 */ 14887 public void resolveLayoutParams() { 14888 if (mLayoutParams != null) { 14889 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 14890 } 14891 } 14892 14893 /** 14894 * Set the scrolled position of your view. This will cause a call to 14895 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14896 * invalidated. 14897 * @param x the x position to scroll to 14898 * @param y the y position to scroll to 14899 */ 14900 public void scrollTo(int x, int y) { 14901 if (mScrollX != x || mScrollY != y) { 14902 int oldX = mScrollX; 14903 int oldY = mScrollY; 14904 mScrollX = x; 14905 mScrollY = y; 14906 invalidateParentCaches(); 14907 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 14908 if (!awakenScrollBars()) { 14909 postInvalidateOnAnimation(); 14910 } 14911 } 14912 } 14913 14914 /** 14915 * Move the scrolled position of your view. This will cause a call to 14916 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14917 * invalidated. 14918 * @param x the amount of pixels to scroll by horizontally 14919 * @param y the amount of pixels to scroll by vertically 14920 */ 14921 public void scrollBy(int x, int y) { 14922 scrollTo(mScrollX + x, mScrollY + y); 14923 } 14924 14925 /** 14926 * <p>Trigger the scrollbars to draw. When invoked this method starts an 14927 * animation to fade the scrollbars out after a default delay. If a subclass 14928 * provides animated scrolling, the start delay should equal the duration 14929 * of the scrolling animation.</p> 14930 * 14931 * <p>The animation starts only if at least one of the scrollbars is 14932 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 14933 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14934 * this method returns true, and false otherwise. If the animation is 14935 * started, this method calls {@link #invalidate()}; in that case the 14936 * caller should not call {@link #invalidate()}.</p> 14937 * 14938 * <p>This method should be invoked every time a subclass directly updates 14939 * the scroll parameters.</p> 14940 * 14941 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 14942 * and {@link #scrollTo(int, int)}.</p> 14943 * 14944 * @return true if the animation is played, false otherwise 14945 * 14946 * @see #awakenScrollBars(int) 14947 * @see #scrollBy(int, int) 14948 * @see #scrollTo(int, int) 14949 * @see #isHorizontalScrollBarEnabled() 14950 * @see #isVerticalScrollBarEnabled() 14951 * @see #setHorizontalScrollBarEnabled(boolean) 14952 * @see #setVerticalScrollBarEnabled(boolean) 14953 */ 14954 protected boolean awakenScrollBars() { 14955 return mScrollCache != null && 14956 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 14957 } 14958 14959 /** 14960 * Trigger the scrollbars to draw. 14961 * This method differs from awakenScrollBars() only in its default duration. 14962 * initialAwakenScrollBars() will show the scroll bars for longer than 14963 * usual to give the user more of a chance to notice them. 14964 * 14965 * @return true if the animation is played, false otherwise. 14966 */ 14967 private boolean initialAwakenScrollBars() { 14968 return mScrollCache != null && 14969 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 14970 } 14971 14972 /** 14973 * <p> 14974 * Trigger the scrollbars to draw. When invoked this method starts an 14975 * animation to fade the scrollbars out after a fixed delay. If a subclass 14976 * provides animated scrolling, the start delay should equal the duration of 14977 * the scrolling animation. 14978 * </p> 14979 * 14980 * <p> 14981 * The animation starts only if at least one of the scrollbars is enabled, 14982 * as specified by {@link #isHorizontalScrollBarEnabled()} and 14983 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14984 * this method returns true, and false otherwise. If the animation is 14985 * started, this method calls {@link #invalidate()}; in that case the caller 14986 * should not call {@link #invalidate()}. 14987 * </p> 14988 * 14989 * <p> 14990 * This method should be invoked every time a subclass directly updates the 14991 * scroll parameters. 14992 * </p> 14993 * 14994 * @param startDelay the delay, in milliseconds, after which the animation 14995 * should start; when the delay is 0, the animation starts 14996 * immediately 14997 * @return true if the animation is played, false otherwise 14998 * 14999 * @see #scrollBy(int, int) 15000 * @see #scrollTo(int, int) 15001 * @see #isHorizontalScrollBarEnabled() 15002 * @see #isVerticalScrollBarEnabled() 15003 * @see #setHorizontalScrollBarEnabled(boolean) 15004 * @see #setVerticalScrollBarEnabled(boolean) 15005 */ 15006 protected boolean awakenScrollBars(int startDelay) { 15007 return awakenScrollBars(startDelay, true); 15008 } 15009 15010 /** 15011 * <p> 15012 * Trigger the scrollbars to draw. When invoked this method starts an 15013 * animation to fade the scrollbars out after a fixed delay. If a subclass 15014 * provides animated scrolling, the start delay should equal the duration of 15015 * the scrolling animation. 15016 * </p> 15017 * 15018 * <p> 15019 * The animation starts only if at least one of the scrollbars is enabled, 15020 * as specified by {@link #isHorizontalScrollBarEnabled()} and 15021 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 15022 * this method returns true, and false otherwise. If the animation is 15023 * started, this method calls {@link #invalidate()} if the invalidate parameter 15024 * is set to true; in that case the caller 15025 * should not call {@link #invalidate()}. 15026 * </p> 15027 * 15028 * <p> 15029 * This method should be invoked every time a subclass directly updates the 15030 * scroll parameters. 15031 * </p> 15032 * 15033 * @param startDelay the delay, in milliseconds, after which the animation 15034 * should start; when the delay is 0, the animation starts 15035 * immediately 15036 * 15037 * @param invalidate Whether this method should call invalidate 15038 * 15039 * @return true if the animation is played, false otherwise 15040 * 15041 * @see #scrollBy(int, int) 15042 * @see #scrollTo(int, int) 15043 * @see #isHorizontalScrollBarEnabled() 15044 * @see #isVerticalScrollBarEnabled() 15045 * @see #setHorizontalScrollBarEnabled(boolean) 15046 * @see #setVerticalScrollBarEnabled(boolean) 15047 */ 15048 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 15049 final ScrollabilityCache scrollCache = mScrollCache; 15050 15051 if (scrollCache == null || !scrollCache.fadeScrollBars) { 15052 return false; 15053 } 15054 15055 if (scrollCache.scrollBar == null) { 15056 scrollCache.scrollBar = new ScrollBarDrawable(); 15057 scrollCache.scrollBar.setState(getDrawableState()); 15058 scrollCache.scrollBar.setCallback(this); 15059 } 15060 15061 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 15062 15063 if (invalidate) { 15064 // Invalidate to show the scrollbars 15065 postInvalidateOnAnimation(); 15066 } 15067 15068 if (scrollCache.state == ScrollabilityCache.OFF) { 15069 // FIXME: this is copied from WindowManagerService. 15070 // We should get this value from the system when it 15071 // is possible to do so. 15072 final int KEY_REPEAT_FIRST_DELAY = 750; 15073 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 15074 } 15075 15076 // Tell mScrollCache when we should start fading. This may 15077 // extend the fade start time if one was already scheduled 15078 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 15079 scrollCache.fadeStartTime = fadeStartTime; 15080 scrollCache.state = ScrollabilityCache.ON; 15081 15082 // Schedule our fader to run, unscheduling any old ones first 15083 if (mAttachInfo != null) { 15084 mAttachInfo.mHandler.removeCallbacks(scrollCache); 15085 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 15086 } 15087 15088 return true; 15089 } 15090 15091 return false; 15092 } 15093 15094 /** 15095 * Do not invalidate views which are not visible and which are not running an animation. They 15096 * will not get drawn and they should not set dirty flags as if they will be drawn 15097 */ 15098 private boolean skipInvalidate() { 15099 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 15100 (!(mParent instanceof ViewGroup) || 15101 !((ViewGroup) mParent).isViewTransitioning(this)); 15102 } 15103 15104 /** 15105 * Mark the area defined by dirty as needing to be drawn. If the view is 15106 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 15107 * point in the future. 15108 * <p> 15109 * This must be called from a UI thread. To call from a non-UI thread, call 15110 * {@link #postInvalidate()}. 15111 * <p> 15112 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 15113 * {@code dirty}. 15114 * 15115 * @param dirty the rectangle representing the bounds of the dirty region 15116 */ 15117 public void invalidate(Rect dirty) { 15118 final int scrollX = mScrollX; 15119 final int scrollY = mScrollY; 15120 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 15121 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 15122 } 15123 15124 /** 15125 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 15126 * coordinates of the dirty rect are relative to the view. If the view is 15127 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 15128 * point in the future. 15129 * <p> 15130 * This must be called from a UI thread. To call from a non-UI thread, call 15131 * {@link #postInvalidate()}. 15132 * 15133 * @param l the left position of the dirty region 15134 * @param t the top position of the dirty region 15135 * @param r the right position of the dirty region 15136 * @param b the bottom position of the dirty region 15137 */ 15138 public void invalidate(int l, int t, int r, int b) { 15139 final int scrollX = mScrollX; 15140 final int scrollY = mScrollY; 15141 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 15142 } 15143 15144 /** 15145 * Invalidate the whole view. If the view is visible, 15146 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 15147 * the future. 15148 * <p> 15149 * This must be called from a UI thread. To call from a non-UI thread, call 15150 * {@link #postInvalidate()}. 15151 */ 15152 public void invalidate() { 15153 invalidate(true); 15154 } 15155 15156 /** 15157 * This is where the invalidate() work actually happens. A full invalidate() 15158 * causes the drawing cache to be invalidated, but this function can be 15159 * called with invalidateCache set to false to skip that invalidation step 15160 * for cases that do not need it (for example, a component that remains at 15161 * the same dimensions with the same content). 15162 * 15163 * @param invalidateCache Whether the drawing cache for this view should be 15164 * invalidated as well. This is usually true for a full 15165 * invalidate, but may be set to false if the View's contents or 15166 * dimensions have not changed. 15167 * @hide 15168 */ 15169 public void invalidate(boolean invalidateCache) { 15170 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 15171 } 15172 15173 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 15174 boolean fullInvalidate) { 15175 if (mGhostView != null) { 15176 mGhostView.invalidate(true); 15177 return; 15178 } 15179 15180 if (skipInvalidate()) { 15181 return; 15182 } 15183 15184 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 15185 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 15186 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 15187 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 15188 if (fullInvalidate) { 15189 mLastIsOpaque = isOpaque(); 15190 mPrivateFlags &= ~PFLAG_DRAWN; 15191 } 15192 15193 mPrivateFlags |= PFLAG_DIRTY; 15194 15195 if (invalidateCache) { 15196 mPrivateFlags |= PFLAG_INVALIDATED; 15197 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15198 } 15199 15200 // Propagate the damage rectangle to the parent view. 15201 final AttachInfo ai = mAttachInfo; 15202 final ViewParent p = mParent; 15203 if (p != null && ai != null && l < r && t < b) { 15204 final Rect damage = ai.mTmpInvalRect; 15205 damage.set(l, t, r, b); 15206 p.invalidateChild(this, damage); 15207 } 15208 15209 // Damage the entire projection receiver, if necessary. 15210 if (mBackground != null && mBackground.isProjected()) { 15211 final View receiver = getProjectionReceiver(); 15212 if (receiver != null) { 15213 receiver.damageInParent(); 15214 } 15215 } 15216 } 15217 } 15218 15219 /** 15220 * @return this view's projection receiver, or {@code null} if none exists 15221 */ 15222 private View getProjectionReceiver() { 15223 ViewParent p = getParent(); 15224 while (p != null && p instanceof View) { 15225 final View v = (View) p; 15226 if (v.isProjectionReceiver()) { 15227 return v; 15228 } 15229 p = p.getParent(); 15230 } 15231 15232 return null; 15233 } 15234 15235 /** 15236 * @return whether the view is a projection receiver 15237 */ 15238 private boolean isProjectionReceiver() { 15239 return mBackground != null; 15240 } 15241 15242 /** 15243 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 15244 * set any flags or handle all of the cases handled by the default invalidation methods. 15245 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 15246 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 15247 * walk up the hierarchy, transforming the dirty rect as necessary. 15248 * 15249 * The method also handles normal invalidation logic if display list properties are not 15250 * being used in this view. The invalidateParent and forceRedraw flags are used by that 15251 * backup approach, to handle these cases used in the various property-setting methods. 15252 * 15253 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 15254 * are not being used in this view 15255 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 15256 * list properties are not being used in this view 15257 */ 15258 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 15259 if (!isHardwareAccelerated() 15260 || !mRenderNode.isValid() 15261 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 15262 if (invalidateParent) { 15263 invalidateParentCaches(); 15264 } 15265 if (forceRedraw) { 15266 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15267 } 15268 invalidate(false); 15269 } else { 15270 damageInParent(); 15271 } 15272 } 15273 15274 /** 15275 * Tells the parent view to damage this view's bounds. 15276 * 15277 * @hide 15278 */ 15279 protected void damageInParent() { 15280 if (mParent != null && mAttachInfo != null) { 15281 mParent.onDescendantInvalidated(this, this); 15282 } 15283 } 15284 15285 /** 15286 * Utility method to transform a given Rect by the current matrix of this view. 15287 */ 15288 void transformRect(final Rect rect) { 15289 if (!getMatrix().isIdentity()) { 15290 RectF boundingRect = mAttachInfo.mTmpTransformRect; 15291 boundingRect.set(rect); 15292 getMatrix().mapRect(boundingRect); 15293 rect.set((int) Math.floor(boundingRect.left), 15294 (int) Math.floor(boundingRect.top), 15295 (int) Math.ceil(boundingRect.right), 15296 (int) Math.ceil(boundingRect.bottom)); 15297 } 15298 } 15299 15300 /** 15301 * Used to indicate that the parent of this view should clear its caches. This functionality 15302 * is used to force the parent to rebuild its display list (when hardware-accelerated), 15303 * which is necessary when various parent-managed properties of the view change, such as 15304 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 15305 * clears the parent caches and does not causes an invalidate event. 15306 * 15307 * @hide 15308 */ 15309 protected void invalidateParentCaches() { 15310 if (mParent instanceof View) { 15311 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 15312 } 15313 } 15314 15315 /** 15316 * Used to indicate that the parent of this view should be invalidated. This functionality 15317 * is used to force the parent to rebuild its display list (when hardware-accelerated), 15318 * which is necessary when various parent-managed properties of the view change, such as 15319 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 15320 * an invalidation event to the parent. 15321 * 15322 * @hide 15323 */ 15324 protected void invalidateParentIfNeeded() { 15325 if (isHardwareAccelerated() && mParent instanceof View) { 15326 ((View) mParent).invalidate(true); 15327 } 15328 } 15329 15330 /** 15331 * @hide 15332 */ 15333 protected void invalidateParentIfNeededAndWasQuickRejected() { 15334 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 15335 // View was rejected last time it was drawn by its parent; this may have changed 15336 invalidateParentIfNeeded(); 15337 } 15338 } 15339 15340 /** 15341 * Indicates whether this View is opaque. An opaque View guarantees that it will 15342 * draw all the pixels overlapping its bounds using a fully opaque color. 15343 * 15344 * Subclasses of View should override this method whenever possible to indicate 15345 * whether an instance is opaque. Opaque Views are treated in a special way by 15346 * the View hierarchy, possibly allowing it to perform optimizations during 15347 * invalidate/draw passes. 15348 * 15349 * @return True if this View is guaranteed to be fully opaque, false otherwise. 15350 */ 15351 @ViewDebug.ExportedProperty(category = "drawing") 15352 public boolean isOpaque() { 15353 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 15354 getFinalAlpha() >= 1.0f; 15355 } 15356 15357 /** 15358 * @hide 15359 */ 15360 protected void computeOpaqueFlags() { 15361 // Opaque if: 15362 // - Has a background 15363 // - Background is opaque 15364 // - Doesn't have scrollbars or scrollbars overlay 15365 15366 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 15367 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 15368 } else { 15369 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 15370 } 15371 15372 final int flags = mViewFlags; 15373 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 15374 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 15375 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 15376 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 15377 } else { 15378 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 15379 } 15380 } 15381 15382 /** 15383 * @hide 15384 */ 15385 protected boolean hasOpaqueScrollbars() { 15386 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 15387 } 15388 15389 /** 15390 * @return A handler associated with the thread running the View. This 15391 * handler can be used to pump events in the UI events queue. 15392 */ 15393 public Handler getHandler() { 15394 final AttachInfo attachInfo = mAttachInfo; 15395 if (attachInfo != null) { 15396 return attachInfo.mHandler; 15397 } 15398 return null; 15399 } 15400 15401 /** 15402 * Returns the queue of runnable for this view. 15403 * 15404 * @return the queue of runnables for this view 15405 */ 15406 private HandlerActionQueue getRunQueue() { 15407 if (mRunQueue == null) { 15408 mRunQueue = new HandlerActionQueue(); 15409 } 15410 return mRunQueue; 15411 } 15412 15413 /** 15414 * Gets the view root associated with the View. 15415 * @return The view root, or null if none. 15416 * @hide 15417 */ 15418 public ViewRootImpl getViewRootImpl() { 15419 if (mAttachInfo != null) { 15420 return mAttachInfo.mViewRootImpl; 15421 } 15422 return null; 15423 } 15424 15425 /** 15426 * @hide 15427 */ 15428 public ThreadedRenderer getThreadedRenderer() { 15429 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 15430 } 15431 15432 /** 15433 * <p>Causes the Runnable to be added to the message queue. 15434 * The runnable will be run on the user interface thread.</p> 15435 * 15436 * @param action The Runnable that will be executed. 15437 * 15438 * @return Returns true if the Runnable was successfully placed in to the 15439 * message queue. Returns false on failure, usually because the 15440 * looper processing the message queue is exiting. 15441 * 15442 * @see #postDelayed 15443 * @see #removeCallbacks 15444 */ 15445 public boolean post(Runnable action) { 15446 final AttachInfo attachInfo = mAttachInfo; 15447 if (attachInfo != null) { 15448 return attachInfo.mHandler.post(action); 15449 } 15450 15451 // Postpone the runnable until we know on which thread it needs to run. 15452 // Assume that the runnable will be successfully placed after attach. 15453 getRunQueue().post(action); 15454 return true; 15455 } 15456 15457 /** 15458 * <p>Causes the Runnable to be added to the message queue, to be run 15459 * after the specified amount of time elapses. 15460 * The runnable will be run on the user interface thread.</p> 15461 * 15462 * @param action The Runnable that will be executed. 15463 * @param delayMillis The delay (in milliseconds) until the Runnable 15464 * will be executed. 15465 * 15466 * @return true if the Runnable was successfully placed in to the 15467 * message queue. Returns false on failure, usually because the 15468 * looper processing the message queue is exiting. Note that a 15469 * result of true does not mean the Runnable will be processed -- 15470 * if the looper is quit before the delivery time of the message 15471 * occurs then the message will be dropped. 15472 * 15473 * @see #post 15474 * @see #removeCallbacks 15475 */ 15476 public boolean postDelayed(Runnable action, long delayMillis) { 15477 final AttachInfo attachInfo = mAttachInfo; 15478 if (attachInfo != null) { 15479 return attachInfo.mHandler.postDelayed(action, delayMillis); 15480 } 15481 15482 // Postpone the runnable until we know on which thread it needs to run. 15483 // Assume that the runnable will be successfully placed after attach. 15484 getRunQueue().postDelayed(action, delayMillis); 15485 return true; 15486 } 15487 15488 /** 15489 * <p>Causes the Runnable to execute on the next animation time step. 15490 * The runnable will be run on the user interface thread.</p> 15491 * 15492 * @param action The Runnable that will be executed. 15493 * 15494 * @see #postOnAnimationDelayed 15495 * @see #removeCallbacks 15496 */ 15497 public void postOnAnimation(Runnable action) { 15498 final AttachInfo attachInfo = mAttachInfo; 15499 if (attachInfo != null) { 15500 attachInfo.mViewRootImpl.mChoreographer.postCallback( 15501 Choreographer.CALLBACK_ANIMATION, action, null); 15502 } else { 15503 // Postpone the runnable until we know 15504 // on which thread it needs to run. 15505 getRunQueue().post(action); 15506 } 15507 } 15508 15509 /** 15510 * <p>Causes the Runnable to execute on the next animation time step, 15511 * after the specified amount of time elapses. 15512 * The runnable will be run on the user interface thread.</p> 15513 * 15514 * @param action The Runnable that will be executed. 15515 * @param delayMillis The delay (in milliseconds) until the Runnable 15516 * will be executed. 15517 * 15518 * @see #postOnAnimation 15519 * @see #removeCallbacks 15520 */ 15521 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 15522 final AttachInfo attachInfo = mAttachInfo; 15523 if (attachInfo != null) { 15524 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15525 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 15526 } else { 15527 // Postpone the runnable until we know 15528 // on which thread it needs to run. 15529 getRunQueue().postDelayed(action, delayMillis); 15530 } 15531 } 15532 15533 /** 15534 * <p>Removes the specified Runnable from the message queue.</p> 15535 * 15536 * @param action The Runnable to remove from the message handling queue 15537 * 15538 * @return true if this view could ask the Handler to remove the Runnable, 15539 * false otherwise. When the returned value is true, the Runnable 15540 * may or may not have been actually removed from the message queue 15541 * (for instance, if the Runnable was not in the queue already.) 15542 * 15543 * @see #post 15544 * @see #postDelayed 15545 * @see #postOnAnimation 15546 * @see #postOnAnimationDelayed 15547 */ 15548 public boolean removeCallbacks(Runnable action) { 15549 if (action != null) { 15550 final AttachInfo attachInfo = mAttachInfo; 15551 if (attachInfo != null) { 15552 attachInfo.mHandler.removeCallbacks(action); 15553 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15554 Choreographer.CALLBACK_ANIMATION, action, null); 15555 } 15556 getRunQueue().removeCallbacks(action); 15557 } 15558 return true; 15559 } 15560 15561 /** 15562 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 15563 * Use this to invalidate the View from a non-UI thread.</p> 15564 * 15565 * <p>This method can be invoked from outside of the UI thread 15566 * only when this View is attached to a window.</p> 15567 * 15568 * @see #invalidate() 15569 * @see #postInvalidateDelayed(long) 15570 */ 15571 public void postInvalidate() { 15572 postInvalidateDelayed(0); 15573 } 15574 15575 /** 15576 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 15577 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 15578 * 15579 * <p>This method can be invoked from outside of the UI thread 15580 * only when this View is attached to a window.</p> 15581 * 15582 * @param left The left coordinate of the rectangle to invalidate. 15583 * @param top The top coordinate of the rectangle to invalidate. 15584 * @param right The right coordinate of the rectangle to invalidate. 15585 * @param bottom The bottom coordinate of the rectangle to invalidate. 15586 * 15587 * @see #invalidate(int, int, int, int) 15588 * @see #invalidate(Rect) 15589 * @see #postInvalidateDelayed(long, int, int, int, int) 15590 */ 15591 public void postInvalidate(int left, int top, int right, int bottom) { 15592 postInvalidateDelayed(0, left, top, right, bottom); 15593 } 15594 15595 /** 15596 * <p>Cause an invalidate to happen on a subsequent cycle through the event 15597 * loop. Waits for the specified amount of time.</p> 15598 * 15599 * <p>This method can be invoked from outside of the UI thread 15600 * only when this View is attached to a window.</p> 15601 * 15602 * @param delayMilliseconds the duration in milliseconds to delay the 15603 * invalidation by 15604 * 15605 * @see #invalidate() 15606 * @see #postInvalidate() 15607 */ 15608 public void postInvalidateDelayed(long delayMilliseconds) { 15609 // We try only with the AttachInfo because there's no point in invalidating 15610 // if we are not attached to our window 15611 final AttachInfo attachInfo = mAttachInfo; 15612 if (attachInfo != null) { 15613 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 15614 } 15615 } 15616 15617 /** 15618 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 15619 * through the event loop. Waits for the specified amount of time.</p> 15620 * 15621 * <p>This method can be invoked from outside of the UI thread 15622 * only when this View is attached to a window.</p> 15623 * 15624 * @param delayMilliseconds the duration in milliseconds to delay the 15625 * invalidation by 15626 * @param left The left coordinate of the rectangle to invalidate. 15627 * @param top The top coordinate of the rectangle to invalidate. 15628 * @param right The right coordinate of the rectangle to invalidate. 15629 * @param bottom The bottom coordinate of the rectangle to invalidate. 15630 * 15631 * @see #invalidate(int, int, int, int) 15632 * @see #invalidate(Rect) 15633 * @see #postInvalidate(int, int, int, int) 15634 */ 15635 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 15636 int right, int bottom) { 15637 15638 // We try only with the AttachInfo because there's no point in invalidating 15639 // if we are not attached to our window 15640 final AttachInfo attachInfo = mAttachInfo; 15641 if (attachInfo != null) { 15642 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 15643 info.target = this; 15644 info.left = left; 15645 info.top = top; 15646 info.right = right; 15647 info.bottom = bottom; 15648 15649 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 15650 } 15651 } 15652 15653 /** 15654 * <p>Cause an invalidate to happen on the next animation time step, typically the 15655 * next display frame.</p> 15656 * 15657 * <p>This method can be invoked from outside of the UI thread 15658 * only when this View is attached to a window.</p> 15659 * 15660 * @see #invalidate() 15661 */ 15662 public void postInvalidateOnAnimation() { 15663 // We try only with the AttachInfo because there's no point in invalidating 15664 // if we are not attached to our window 15665 final AttachInfo attachInfo = mAttachInfo; 15666 if (attachInfo != null) { 15667 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 15668 } 15669 } 15670 15671 /** 15672 * <p>Cause an invalidate of the specified area to happen on the next animation 15673 * time step, typically the next display frame.</p> 15674 * 15675 * <p>This method can be invoked from outside of the UI thread 15676 * only when this View is attached to a window.</p> 15677 * 15678 * @param left The left coordinate of the rectangle to invalidate. 15679 * @param top The top coordinate of the rectangle to invalidate. 15680 * @param right The right coordinate of the rectangle to invalidate. 15681 * @param bottom The bottom coordinate of the rectangle to invalidate. 15682 * 15683 * @see #invalidate(int, int, int, int) 15684 * @see #invalidate(Rect) 15685 */ 15686 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 15687 // We try only with the AttachInfo because there's no point in invalidating 15688 // if we are not attached to our window 15689 final AttachInfo attachInfo = mAttachInfo; 15690 if (attachInfo != null) { 15691 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 15692 info.target = this; 15693 info.left = left; 15694 info.top = top; 15695 info.right = right; 15696 info.bottom = bottom; 15697 15698 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 15699 } 15700 } 15701 15702 /** 15703 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 15704 * This event is sent at most once every 15705 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 15706 */ 15707 private void postSendViewScrolledAccessibilityEventCallback() { 15708 if (mSendViewScrolledAccessibilityEvent == null) { 15709 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 15710 } 15711 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 15712 mSendViewScrolledAccessibilityEvent.mIsPending = true; 15713 postDelayed(mSendViewScrolledAccessibilityEvent, 15714 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 15715 } 15716 } 15717 15718 /** 15719 * Called by a parent to request that a child update its values for mScrollX 15720 * and mScrollY if necessary. This will typically be done if the child is 15721 * animating a scroll using a {@link android.widget.Scroller Scroller} 15722 * object. 15723 */ 15724 public void computeScroll() { 15725 } 15726 15727 /** 15728 * <p>Indicate whether the horizontal edges are faded when the view is 15729 * scrolled horizontally.</p> 15730 * 15731 * @return true if the horizontal edges should are faded on scroll, false 15732 * otherwise 15733 * 15734 * @see #setHorizontalFadingEdgeEnabled(boolean) 15735 * 15736 * @attr ref android.R.styleable#View_requiresFadingEdge 15737 */ 15738 public boolean isHorizontalFadingEdgeEnabled() { 15739 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 15740 } 15741 15742 /** 15743 * <p>Define whether the horizontal edges should be faded when this view 15744 * is scrolled horizontally.</p> 15745 * 15746 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 15747 * be faded when the view is scrolled 15748 * horizontally 15749 * 15750 * @see #isHorizontalFadingEdgeEnabled() 15751 * 15752 * @attr ref android.R.styleable#View_requiresFadingEdge 15753 */ 15754 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 15755 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 15756 if (horizontalFadingEdgeEnabled) { 15757 initScrollCache(); 15758 } 15759 15760 mViewFlags ^= FADING_EDGE_HORIZONTAL; 15761 } 15762 } 15763 15764 /** 15765 * <p>Indicate whether the vertical edges are faded when the view is 15766 * scrolled horizontally.</p> 15767 * 15768 * @return true if the vertical edges should are faded on scroll, false 15769 * otherwise 15770 * 15771 * @see #setVerticalFadingEdgeEnabled(boolean) 15772 * 15773 * @attr ref android.R.styleable#View_requiresFadingEdge 15774 */ 15775 public boolean isVerticalFadingEdgeEnabled() { 15776 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 15777 } 15778 15779 /** 15780 * <p>Define whether the vertical edges should be faded when this view 15781 * is scrolled vertically.</p> 15782 * 15783 * @param verticalFadingEdgeEnabled true if the vertical edges should 15784 * be faded when the view is scrolled 15785 * vertically 15786 * 15787 * @see #isVerticalFadingEdgeEnabled() 15788 * 15789 * @attr ref android.R.styleable#View_requiresFadingEdge 15790 */ 15791 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 15792 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 15793 if (verticalFadingEdgeEnabled) { 15794 initScrollCache(); 15795 } 15796 15797 mViewFlags ^= FADING_EDGE_VERTICAL; 15798 } 15799 } 15800 15801 /** 15802 * Returns the strength, or intensity, of the top faded edge. The strength is 15803 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15804 * returns 0.0 or 1.0 but no value in between. 15805 * 15806 * Subclasses should override this method to provide a smoother fade transition 15807 * when scrolling occurs. 15808 * 15809 * @return the intensity of the top fade as a float between 0.0f and 1.0f 15810 */ 15811 protected float getTopFadingEdgeStrength() { 15812 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 15813 } 15814 15815 /** 15816 * Returns the strength, or intensity, of the bottom faded edge. The strength is 15817 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15818 * returns 0.0 or 1.0 but no value in between. 15819 * 15820 * Subclasses should override this method to provide a smoother fade transition 15821 * when scrolling occurs. 15822 * 15823 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 15824 */ 15825 protected float getBottomFadingEdgeStrength() { 15826 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 15827 computeVerticalScrollRange() ? 1.0f : 0.0f; 15828 } 15829 15830 /** 15831 * Returns the strength, or intensity, of the left faded edge. The strength is 15832 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15833 * returns 0.0 or 1.0 but no value in between. 15834 * 15835 * Subclasses should override this method to provide a smoother fade transition 15836 * when scrolling occurs. 15837 * 15838 * @return the intensity of the left fade as a float between 0.0f and 1.0f 15839 */ 15840 protected float getLeftFadingEdgeStrength() { 15841 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 15842 } 15843 15844 /** 15845 * Returns the strength, or intensity, of the right faded edge. The strength is 15846 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15847 * returns 0.0 or 1.0 but no value in between. 15848 * 15849 * Subclasses should override this method to provide a smoother fade transition 15850 * when scrolling occurs. 15851 * 15852 * @return the intensity of the right fade as a float between 0.0f and 1.0f 15853 */ 15854 protected float getRightFadingEdgeStrength() { 15855 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 15856 computeHorizontalScrollRange() ? 1.0f : 0.0f; 15857 } 15858 15859 /** 15860 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 15861 * scrollbar is not drawn by default.</p> 15862 * 15863 * @return true if the horizontal scrollbar should be painted, false 15864 * otherwise 15865 * 15866 * @see #setHorizontalScrollBarEnabled(boolean) 15867 */ 15868 public boolean isHorizontalScrollBarEnabled() { 15869 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 15870 } 15871 15872 /** 15873 * <p>Define whether the horizontal scrollbar should be drawn or not. The 15874 * scrollbar is not drawn by default.</p> 15875 * 15876 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 15877 * be painted 15878 * 15879 * @see #isHorizontalScrollBarEnabled() 15880 */ 15881 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 15882 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 15883 mViewFlags ^= SCROLLBARS_HORIZONTAL; 15884 computeOpaqueFlags(); 15885 resolvePadding(); 15886 } 15887 } 15888 15889 /** 15890 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 15891 * scrollbar is not drawn by default.</p> 15892 * 15893 * @return true if the vertical scrollbar should be painted, false 15894 * otherwise 15895 * 15896 * @see #setVerticalScrollBarEnabled(boolean) 15897 */ 15898 public boolean isVerticalScrollBarEnabled() { 15899 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 15900 } 15901 15902 /** 15903 * <p>Define whether the vertical scrollbar should be drawn or not. The 15904 * scrollbar is not drawn by default.</p> 15905 * 15906 * @param verticalScrollBarEnabled true if the vertical scrollbar should 15907 * be painted 15908 * 15909 * @see #isVerticalScrollBarEnabled() 15910 */ 15911 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 15912 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 15913 mViewFlags ^= SCROLLBARS_VERTICAL; 15914 computeOpaqueFlags(); 15915 resolvePadding(); 15916 } 15917 } 15918 15919 /** 15920 * @hide 15921 */ 15922 protected void recomputePadding() { 15923 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15924 } 15925 15926 /** 15927 * Define whether scrollbars will fade when the view is not scrolling. 15928 * 15929 * @param fadeScrollbars whether to enable fading 15930 * 15931 * @attr ref android.R.styleable#View_fadeScrollbars 15932 */ 15933 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 15934 initScrollCache(); 15935 final ScrollabilityCache scrollabilityCache = mScrollCache; 15936 scrollabilityCache.fadeScrollBars = fadeScrollbars; 15937 if (fadeScrollbars) { 15938 scrollabilityCache.state = ScrollabilityCache.OFF; 15939 } else { 15940 scrollabilityCache.state = ScrollabilityCache.ON; 15941 } 15942 } 15943 15944 /** 15945 * 15946 * Returns true if scrollbars will fade when this view is not scrolling 15947 * 15948 * @return true if scrollbar fading is enabled 15949 * 15950 * @attr ref android.R.styleable#View_fadeScrollbars 15951 */ 15952 public boolean isScrollbarFadingEnabled() { 15953 return mScrollCache != null && mScrollCache.fadeScrollBars; 15954 } 15955 15956 /** 15957 * 15958 * Returns the delay before scrollbars fade. 15959 * 15960 * @return the delay before scrollbars fade 15961 * 15962 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 15963 */ 15964 public int getScrollBarDefaultDelayBeforeFade() { 15965 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 15966 mScrollCache.scrollBarDefaultDelayBeforeFade; 15967 } 15968 15969 /** 15970 * Define the delay before scrollbars fade. 15971 * 15972 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 15973 * 15974 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 15975 */ 15976 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 15977 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 15978 } 15979 15980 /** 15981 * 15982 * Returns the scrollbar fade duration. 15983 * 15984 * @return the scrollbar fade duration, in milliseconds 15985 * 15986 * @attr ref android.R.styleable#View_scrollbarFadeDuration 15987 */ 15988 public int getScrollBarFadeDuration() { 15989 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 15990 mScrollCache.scrollBarFadeDuration; 15991 } 15992 15993 /** 15994 * Define the scrollbar fade duration. 15995 * 15996 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 15997 * 15998 * @attr ref android.R.styleable#View_scrollbarFadeDuration 15999 */ 16000 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 16001 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 16002 } 16003 16004 /** 16005 * 16006 * Returns the scrollbar size. 16007 * 16008 * @return the scrollbar size 16009 * 16010 * @attr ref android.R.styleable#View_scrollbarSize 16011 */ 16012 public int getScrollBarSize() { 16013 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 16014 mScrollCache.scrollBarSize; 16015 } 16016 16017 /** 16018 * Define the scrollbar size. 16019 * 16020 * @param scrollBarSize - the scrollbar size 16021 * 16022 * @attr ref android.R.styleable#View_scrollbarSize 16023 */ 16024 public void setScrollBarSize(int scrollBarSize) { 16025 getScrollCache().scrollBarSize = scrollBarSize; 16026 } 16027 16028 /** 16029 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 16030 * inset. When inset, they add to the padding of the view. And the scrollbars 16031 * can be drawn inside the padding area or on the edge of the view. For example, 16032 * if a view has a background drawable and you want to draw the scrollbars 16033 * inside the padding specified by the drawable, you can use 16034 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 16035 * appear at the edge of the view, ignoring the padding, then you can use 16036 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 16037 * @param style the style of the scrollbars. Should be one of 16038 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 16039 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 16040 * @see #SCROLLBARS_INSIDE_OVERLAY 16041 * @see #SCROLLBARS_INSIDE_INSET 16042 * @see #SCROLLBARS_OUTSIDE_OVERLAY 16043 * @see #SCROLLBARS_OUTSIDE_INSET 16044 * 16045 * @attr ref android.R.styleable#View_scrollbarStyle 16046 */ 16047 public void setScrollBarStyle(@ScrollBarStyle int style) { 16048 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 16049 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 16050 computeOpaqueFlags(); 16051 resolvePadding(); 16052 } 16053 } 16054 16055 /** 16056 * <p>Returns the current scrollbar style.</p> 16057 * @return the current scrollbar style 16058 * @see #SCROLLBARS_INSIDE_OVERLAY 16059 * @see #SCROLLBARS_INSIDE_INSET 16060 * @see #SCROLLBARS_OUTSIDE_OVERLAY 16061 * @see #SCROLLBARS_OUTSIDE_INSET 16062 * 16063 * @attr ref android.R.styleable#View_scrollbarStyle 16064 */ 16065 @ViewDebug.ExportedProperty(mapping = { 16066 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 16067 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 16068 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 16069 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 16070 }) 16071 @ScrollBarStyle 16072 public int getScrollBarStyle() { 16073 return mViewFlags & SCROLLBARS_STYLE_MASK; 16074 } 16075 16076 /** 16077 * <p>Compute the horizontal range that the horizontal scrollbar 16078 * represents.</p> 16079 * 16080 * <p>The range is expressed in arbitrary units that must be the same as the 16081 * units used by {@link #computeHorizontalScrollExtent()} and 16082 * {@link #computeHorizontalScrollOffset()}.</p> 16083 * 16084 * <p>The default range is the drawing width of this view.</p> 16085 * 16086 * @return the total horizontal range represented by the horizontal 16087 * scrollbar 16088 * 16089 * @see #computeHorizontalScrollExtent() 16090 * @see #computeHorizontalScrollOffset() 16091 * @see android.widget.ScrollBarDrawable 16092 */ 16093 protected int computeHorizontalScrollRange() { 16094 return getWidth(); 16095 } 16096 16097 /** 16098 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 16099 * within the horizontal range. This value is used to compute the position 16100 * of the thumb within the scrollbar's track.</p> 16101 * 16102 * <p>The range is expressed in arbitrary units that must be the same as the 16103 * units used by {@link #computeHorizontalScrollRange()} and 16104 * {@link #computeHorizontalScrollExtent()}.</p> 16105 * 16106 * <p>The default offset is the scroll offset of this view.</p> 16107 * 16108 * @return the horizontal offset of the scrollbar's thumb 16109 * 16110 * @see #computeHorizontalScrollRange() 16111 * @see #computeHorizontalScrollExtent() 16112 * @see android.widget.ScrollBarDrawable 16113 */ 16114 protected int computeHorizontalScrollOffset() { 16115 return mScrollX; 16116 } 16117 16118 /** 16119 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 16120 * within the horizontal range. This value is used to compute the length 16121 * of the thumb within the scrollbar's track.</p> 16122 * 16123 * <p>The range is expressed in arbitrary units that must be the same as the 16124 * units used by {@link #computeHorizontalScrollRange()} and 16125 * {@link #computeHorizontalScrollOffset()}.</p> 16126 * 16127 * <p>The default extent is the drawing width of this view.</p> 16128 * 16129 * @return the horizontal extent of the scrollbar's thumb 16130 * 16131 * @see #computeHorizontalScrollRange() 16132 * @see #computeHorizontalScrollOffset() 16133 * @see android.widget.ScrollBarDrawable 16134 */ 16135 protected int computeHorizontalScrollExtent() { 16136 return getWidth(); 16137 } 16138 16139 /** 16140 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 16141 * 16142 * <p>The range is expressed in arbitrary units that must be the same as the 16143 * units used by {@link #computeVerticalScrollExtent()} and 16144 * {@link #computeVerticalScrollOffset()}.</p> 16145 * 16146 * @return the total vertical range represented by the vertical scrollbar 16147 * 16148 * <p>The default range is the drawing height of this view.</p> 16149 * 16150 * @see #computeVerticalScrollExtent() 16151 * @see #computeVerticalScrollOffset() 16152 * @see android.widget.ScrollBarDrawable 16153 */ 16154 protected int computeVerticalScrollRange() { 16155 return getHeight(); 16156 } 16157 16158 /** 16159 * <p>Compute the vertical offset of the vertical scrollbar's thumb 16160 * within the horizontal range. This value is used to compute the position 16161 * of the thumb within the scrollbar's track.</p> 16162 * 16163 * <p>The range is expressed in arbitrary units that must be the same as the 16164 * units used by {@link #computeVerticalScrollRange()} and 16165 * {@link #computeVerticalScrollExtent()}.</p> 16166 * 16167 * <p>The default offset is the scroll offset of this view.</p> 16168 * 16169 * @return the vertical offset of the scrollbar's thumb 16170 * 16171 * @see #computeVerticalScrollRange() 16172 * @see #computeVerticalScrollExtent() 16173 * @see android.widget.ScrollBarDrawable 16174 */ 16175 protected int computeVerticalScrollOffset() { 16176 return mScrollY; 16177 } 16178 16179 /** 16180 * <p>Compute the vertical extent of the vertical scrollbar's thumb 16181 * within the vertical range. This value is used to compute the length 16182 * of the thumb within the scrollbar's track.</p> 16183 * 16184 * <p>The range is expressed in arbitrary units that must be the same as the 16185 * units used by {@link #computeVerticalScrollRange()} and 16186 * {@link #computeVerticalScrollOffset()}.</p> 16187 * 16188 * <p>The default extent is the drawing height of this view.</p> 16189 * 16190 * @return the vertical extent of the scrollbar's thumb 16191 * 16192 * @see #computeVerticalScrollRange() 16193 * @see #computeVerticalScrollOffset() 16194 * @see android.widget.ScrollBarDrawable 16195 */ 16196 protected int computeVerticalScrollExtent() { 16197 return getHeight(); 16198 } 16199 16200 /** 16201 * Check if this view can be scrolled horizontally in a certain direction. 16202 * 16203 * @param direction Negative to check scrolling left, positive to check scrolling right. 16204 * @return true if this view can be scrolled in the specified direction, false otherwise. 16205 */ 16206 public boolean canScrollHorizontally(int direction) { 16207 final int offset = computeHorizontalScrollOffset(); 16208 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 16209 if (range == 0) return false; 16210 if (direction < 0) { 16211 return offset > 0; 16212 } else { 16213 return offset < range - 1; 16214 } 16215 } 16216 16217 /** 16218 * Check if this view can be scrolled vertically in a certain direction. 16219 * 16220 * @param direction Negative to check scrolling up, positive to check scrolling down. 16221 * @return true if this view can be scrolled in the specified direction, false otherwise. 16222 */ 16223 public boolean canScrollVertically(int direction) { 16224 final int offset = computeVerticalScrollOffset(); 16225 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 16226 if (range == 0) return false; 16227 if (direction < 0) { 16228 return offset > 0; 16229 } else { 16230 return offset < range - 1; 16231 } 16232 } 16233 16234 void getScrollIndicatorBounds(@NonNull Rect out) { 16235 out.left = mScrollX; 16236 out.right = mScrollX + mRight - mLeft; 16237 out.top = mScrollY; 16238 out.bottom = mScrollY + mBottom - mTop; 16239 } 16240 16241 private void onDrawScrollIndicators(Canvas c) { 16242 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 16243 // No scroll indicators enabled. 16244 return; 16245 } 16246 16247 final Drawable dr = mScrollIndicatorDrawable; 16248 if (dr == null) { 16249 // Scroll indicators aren't supported here. 16250 return; 16251 } 16252 16253 final int h = dr.getIntrinsicHeight(); 16254 final int w = dr.getIntrinsicWidth(); 16255 final Rect rect = mAttachInfo.mTmpInvalRect; 16256 getScrollIndicatorBounds(rect); 16257 16258 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 16259 final boolean canScrollUp = canScrollVertically(-1); 16260 if (canScrollUp) { 16261 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 16262 dr.draw(c); 16263 } 16264 } 16265 16266 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 16267 final boolean canScrollDown = canScrollVertically(1); 16268 if (canScrollDown) { 16269 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 16270 dr.draw(c); 16271 } 16272 } 16273 16274 final int leftRtl; 16275 final int rightRtl; 16276 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 16277 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 16278 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 16279 } else { 16280 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 16281 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 16282 } 16283 16284 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 16285 if ((mPrivateFlags3 & leftMask) != 0) { 16286 final boolean canScrollLeft = canScrollHorizontally(-1); 16287 if (canScrollLeft) { 16288 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 16289 dr.draw(c); 16290 } 16291 } 16292 16293 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 16294 if ((mPrivateFlags3 & rightMask) != 0) { 16295 final boolean canScrollRight = canScrollHorizontally(1); 16296 if (canScrollRight) { 16297 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 16298 dr.draw(c); 16299 } 16300 } 16301 } 16302 16303 private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds, 16304 @Nullable Rect touchBounds) { 16305 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 16306 if (bounds == null) { 16307 return; 16308 } 16309 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 16310 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 16311 && !isVerticalScrollBarHidden(); 16312 final int size = getHorizontalScrollbarHeight(); 16313 final int verticalScrollBarGap = drawVerticalScrollBar ? 16314 getVerticalScrollbarWidth() : 0; 16315 final int width = mRight - mLeft; 16316 final int height = mBottom - mTop; 16317 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 16318 bounds.left = mScrollX + (mPaddingLeft & inside); 16319 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 16320 bounds.bottom = bounds.top + size; 16321 16322 if (touchBounds == null) { 16323 return; 16324 } 16325 if (touchBounds != bounds) { 16326 touchBounds.set(bounds); 16327 } 16328 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 16329 if (touchBounds.height() < minTouchTarget) { 16330 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 16331 touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height); 16332 touchBounds.top = touchBounds.bottom - minTouchTarget; 16333 } 16334 if (touchBounds.width() < minTouchTarget) { 16335 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 16336 touchBounds.left -= adjust; 16337 touchBounds.right = touchBounds.left + minTouchTarget; 16338 } 16339 } 16340 16341 private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) { 16342 if (mRoundScrollbarRenderer == null) { 16343 getStraightVerticalScrollBarBounds(bounds, touchBounds); 16344 } else { 16345 getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds); 16346 } 16347 } 16348 16349 private void getRoundVerticalScrollBarBounds(Rect bounds) { 16350 final int width = mRight - mLeft; 16351 final int height = mBottom - mTop; 16352 // Do not take padding into account as we always want the scrollbars 16353 // to hug the screen for round wearable devices. 16354 bounds.left = mScrollX; 16355 bounds.top = mScrollY; 16356 bounds.right = bounds.left + width; 16357 bounds.bottom = mScrollY + height; 16358 } 16359 16360 private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds, 16361 @Nullable Rect touchBounds) { 16362 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 16363 if (bounds == null) { 16364 return; 16365 } 16366 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 16367 final int size = getVerticalScrollbarWidth(); 16368 int verticalScrollbarPosition = mVerticalScrollbarPosition; 16369 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 16370 verticalScrollbarPosition = isLayoutRtl() ? 16371 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 16372 } 16373 final int width = mRight - mLeft; 16374 final int height = mBottom - mTop; 16375 switch (verticalScrollbarPosition) { 16376 default: 16377 case SCROLLBAR_POSITION_RIGHT: 16378 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 16379 break; 16380 case SCROLLBAR_POSITION_LEFT: 16381 bounds.left = mScrollX + (mUserPaddingLeft & inside); 16382 break; 16383 } 16384 bounds.top = mScrollY + (mPaddingTop & inside); 16385 bounds.right = bounds.left + size; 16386 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 16387 16388 if (touchBounds == null) { 16389 return; 16390 } 16391 if (touchBounds != bounds) { 16392 touchBounds.set(bounds); 16393 } 16394 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 16395 if (touchBounds.width() < minTouchTarget) { 16396 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 16397 if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) { 16398 touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width); 16399 touchBounds.left = touchBounds.right - minTouchTarget; 16400 } else { 16401 touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX); 16402 touchBounds.right = touchBounds.left + minTouchTarget; 16403 } 16404 } 16405 if (touchBounds.height() < minTouchTarget) { 16406 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 16407 touchBounds.top -= adjust; 16408 touchBounds.bottom = touchBounds.top + minTouchTarget; 16409 } 16410 } 16411 16412 /** 16413 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 16414 * scrollbars are painted only if they have been awakened first.</p> 16415 * 16416 * @param canvas the canvas on which to draw the scrollbars 16417 * 16418 * @see #awakenScrollBars(int) 16419 */ 16420 protected final void onDrawScrollBars(Canvas canvas) { 16421 // scrollbars are drawn only when the animation is running 16422 final ScrollabilityCache cache = mScrollCache; 16423 16424 if (cache != null) { 16425 16426 int state = cache.state; 16427 16428 if (state == ScrollabilityCache.OFF) { 16429 return; 16430 } 16431 16432 boolean invalidate = false; 16433 16434 if (state == ScrollabilityCache.FADING) { 16435 // We're fading -- get our fade interpolation 16436 if (cache.interpolatorValues == null) { 16437 cache.interpolatorValues = new float[1]; 16438 } 16439 16440 float[] values = cache.interpolatorValues; 16441 16442 // Stops the animation if we're done 16443 if (cache.scrollBarInterpolator.timeToValues(values) == 16444 Interpolator.Result.FREEZE_END) { 16445 cache.state = ScrollabilityCache.OFF; 16446 } else { 16447 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 16448 } 16449 16450 // This will make the scroll bars inval themselves after 16451 // drawing. We only want this when we're fading so that 16452 // we prevent excessive redraws 16453 invalidate = true; 16454 } else { 16455 // We're just on -- but we may have been fading before so 16456 // reset alpha 16457 cache.scrollBar.mutate().setAlpha(255); 16458 } 16459 16460 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 16461 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 16462 && !isVerticalScrollBarHidden(); 16463 16464 // Fork out the scroll bar drawing for round wearable devices. 16465 if (mRoundScrollbarRenderer != null) { 16466 if (drawVerticalScrollBar) { 16467 final Rect bounds = cache.mScrollBarBounds; 16468 getVerticalScrollBarBounds(bounds, null); 16469 mRoundScrollbarRenderer.drawRoundScrollbars( 16470 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 16471 if (invalidate) { 16472 invalidate(); 16473 } 16474 } 16475 // Do not draw horizontal scroll bars for round wearable devices. 16476 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 16477 final ScrollBarDrawable scrollBar = cache.scrollBar; 16478 16479 if (drawHorizontalScrollBar) { 16480 scrollBar.setParameters(computeHorizontalScrollRange(), 16481 computeHorizontalScrollOffset(), 16482 computeHorizontalScrollExtent(), false); 16483 final Rect bounds = cache.mScrollBarBounds; 16484 getHorizontalScrollBarBounds(bounds, null); 16485 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 16486 bounds.right, bounds.bottom); 16487 if (invalidate) { 16488 invalidate(bounds); 16489 } 16490 } 16491 16492 if (drawVerticalScrollBar) { 16493 scrollBar.setParameters(computeVerticalScrollRange(), 16494 computeVerticalScrollOffset(), 16495 computeVerticalScrollExtent(), true); 16496 final Rect bounds = cache.mScrollBarBounds; 16497 getVerticalScrollBarBounds(bounds, null); 16498 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 16499 bounds.right, bounds.bottom); 16500 if (invalidate) { 16501 invalidate(bounds); 16502 } 16503 } 16504 } 16505 } 16506 } 16507 16508 /** 16509 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 16510 * FastScroller is visible. 16511 * @return whether to temporarily hide the vertical scrollbar 16512 * @hide 16513 */ 16514 protected boolean isVerticalScrollBarHidden() { 16515 return false; 16516 } 16517 16518 /** 16519 * <p>Draw the horizontal scrollbar if 16520 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 16521 * 16522 * @param canvas the canvas on which to draw the scrollbar 16523 * @param scrollBar the scrollbar's drawable 16524 * 16525 * @see #isHorizontalScrollBarEnabled() 16526 * @see #computeHorizontalScrollRange() 16527 * @see #computeHorizontalScrollExtent() 16528 * @see #computeHorizontalScrollOffset() 16529 * @see android.widget.ScrollBarDrawable 16530 * @hide 16531 */ 16532 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 16533 int l, int t, int r, int b) { 16534 scrollBar.setBounds(l, t, r, b); 16535 scrollBar.draw(canvas); 16536 } 16537 16538 /** 16539 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 16540 * returns true.</p> 16541 * 16542 * @param canvas the canvas on which to draw the scrollbar 16543 * @param scrollBar the scrollbar's drawable 16544 * 16545 * @see #isVerticalScrollBarEnabled() 16546 * @see #computeVerticalScrollRange() 16547 * @see #computeVerticalScrollExtent() 16548 * @see #computeVerticalScrollOffset() 16549 * @see android.widget.ScrollBarDrawable 16550 * @hide 16551 */ 16552 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 16553 int l, int t, int r, int b) { 16554 scrollBar.setBounds(l, t, r, b); 16555 scrollBar.draw(canvas); 16556 } 16557 16558 /** 16559 * Implement this to do your drawing. 16560 * 16561 * @param canvas the canvas on which the background will be drawn 16562 */ 16563 protected void onDraw(Canvas canvas) { 16564 } 16565 16566 /* 16567 * Caller is responsible for calling requestLayout if necessary. 16568 * (This allows addViewInLayout to not request a new layout.) 16569 */ 16570 void assignParent(ViewParent parent) { 16571 if (mParent == null) { 16572 mParent = parent; 16573 } else if (parent == null) { 16574 mParent = null; 16575 } else { 16576 throw new RuntimeException("view " + this + " being added, but" 16577 + " it already has a parent"); 16578 } 16579 } 16580 16581 /** 16582 * This is called when the view is attached to a window. At this point it 16583 * has a Surface and will start drawing. Note that this function is 16584 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 16585 * however it may be called any time before the first onDraw -- including 16586 * before or after {@link #onMeasure(int, int)}. 16587 * 16588 * @see #onDetachedFromWindow() 16589 */ 16590 @CallSuper 16591 protected void onAttachedToWindow() { 16592 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 16593 mParent.requestTransparentRegion(this); 16594 } 16595 16596 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 16597 16598 jumpDrawablesToCurrentState(); 16599 16600 resetSubtreeAccessibilityStateChanged(); 16601 16602 // rebuild, since Outline not maintained while View is detached 16603 rebuildOutline(); 16604 16605 if (isFocused()) { 16606 InputMethodManager imm = InputMethodManager.peekInstance(); 16607 if (imm != null) { 16608 imm.focusIn(this); 16609 } 16610 } 16611 } 16612 16613 /** 16614 * Resolve all RTL related properties. 16615 * 16616 * @return true if resolution of RTL properties has been done 16617 * 16618 * @hide 16619 */ 16620 public boolean resolveRtlPropertiesIfNeeded() { 16621 if (!needRtlPropertiesResolution()) return false; 16622 16623 // Order is important here: LayoutDirection MUST be resolved first 16624 if (!isLayoutDirectionResolved()) { 16625 resolveLayoutDirection(); 16626 resolveLayoutParams(); 16627 } 16628 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 16629 if (!isTextDirectionResolved()) { 16630 resolveTextDirection(); 16631 } 16632 if (!isTextAlignmentResolved()) { 16633 resolveTextAlignment(); 16634 } 16635 // Should resolve Drawables before Padding because we need the layout direction of the 16636 // Drawable to correctly resolve Padding. 16637 if (!areDrawablesResolved()) { 16638 resolveDrawables(); 16639 } 16640 if (!isPaddingResolved()) { 16641 resolvePadding(); 16642 } 16643 onRtlPropertiesChanged(getLayoutDirection()); 16644 return true; 16645 } 16646 16647 /** 16648 * Reset resolution of all RTL related properties. 16649 * 16650 * @hide 16651 */ 16652 public void resetRtlProperties() { 16653 resetResolvedLayoutDirection(); 16654 resetResolvedTextDirection(); 16655 resetResolvedTextAlignment(); 16656 resetResolvedPadding(); 16657 resetResolvedDrawables(); 16658 } 16659 16660 /** 16661 * @see #onScreenStateChanged(int) 16662 */ 16663 void dispatchScreenStateChanged(int screenState) { 16664 onScreenStateChanged(screenState); 16665 } 16666 16667 /** 16668 * This method is called whenever the state of the screen this view is 16669 * attached to changes. A state change will usually occurs when the screen 16670 * turns on or off (whether it happens automatically or the user does it 16671 * manually.) 16672 * 16673 * @param screenState The new state of the screen. Can be either 16674 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 16675 */ 16676 public void onScreenStateChanged(int screenState) { 16677 } 16678 16679 /** 16680 * @see #onMovedToDisplay(int, Configuration) 16681 */ 16682 void dispatchMovedToDisplay(Display display, Configuration config) { 16683 mAttachInfo.mDisplay = display; 16684 mAttachInfo.mDisplayState = display.getState(); 16685 onMovedToDisplay(display.getDisplayId(), config); 16686 } 16687 16688 /** 16689 * Called by the system when the hosting activity is moved from one display to another without 16690 * recreation. This means that the activity is declared to handle all changes to configuration 16691 * that happened when it was switched to another display, so it wasn't destroyed and created 16692 * again. 16693 * 16694 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the 16695 * applied configuration actually changed. It is up to app developer to choose whether to handle 16696 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)} 16697 * call. 16698 * 16699 * <p>Use this callback to track changes to the displays if some functionality relies on an 16700 * association with some display properties. 16701 * 16702 * @param displayId The id of the display to which the view was moved. 16703 * @param config Configuration of the resources on new display after move. 16704 * 16705 * @see #onConfigurationChanged(Configuration) 16706 * @hide 16707 */ 16708 public void onMovedToDisplay(int displayId, Configuration config) { 16709 } 16710 16711 /** 16712 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 16713 */ 16714 private boolean hasRtlSupport() { 16715 return mContext.getApplicationInfo().hasRtlSupport(); 16716 } 16717 16718 /** 16719 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 16720 * RTL not supported) 16721 */ 16722 private boolean isRtlCompatibilityMode() { 16723 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 16724 return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport(); 16725 } 16726 16727 /** 16728 * @return true if RTL properties need resolution. 16729 * 16730 */ 16731 private boolean needRtlPropertiesResolution() { 16732 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 16733 } 16734 16735 /** 16736 * Called when any RTL property (layout direction or text direction or text alignment) has 16737 * been changed. 16738 * 16739 * Subclasses need to override this method to take care of cached information that depends on the 16740 * resolved layout direction, or to inform child views that inherit their layout direction. 16741 * 16742 * The default implementation does nothing. 16743 * 16744 * @param layoutDirection the direction of the layout 16745 * 16746 * @see #LAYOUT_DIRECTION_LTR 16747 * @see #LAYOUT_DIRECTION_RTL 16748 */ 16749 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 16750 } 16751 16752 /** 16753 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 16754 * that the parent directionality can and will be resolved before its children. 16755 * 16756 * @return true if resolution has been done, false otherwise. 16757 * 16758 * @hide 16759 */ 16760 public boolean resolveLayoutDirection() { 16761 // Clear any previous layout direction resolution 16762 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 16763 16764 if (hasRtlSupport()) { 16765 // Set resolved depending on layout direction 16766 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 16767 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 16768 case LAYOUT_DIRECTION_INHERIT: 16769 // We cannot resolve yet. LTR is by default and let the resolution happen again 16770 // later to get the correct resolved value 16771 if (!canResolveLayoutDirection()) return false; 16772 16773 // Parent has not yet resolved, LTR is still the default 16774 try { 16775 if (!mParent.isLayoutDirectionResolved()) return false; 16776 16777 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 16778 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16779 } 16780 } catch (AbstractMethodError e) { 16781 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 16782 " does not fully implement ViewParent", e); 16783 } 16784 break; 16785 case LAYOUT_DIRECTION_RTL: 16786 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16787 break; 16788 case LAYOUT_DIRECTION_LOCALE: 16789 if((LAYOUT_DIRECTION_RTL == 16790 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 16791 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16792 } 16793 break; 16794 default: 16795 // Nothing to do, LTR by default 16796 } 16797 } 16798 16799 // Set to resolved 16800 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 16801 return true; 16802 } 16803 16804 /** 16805 * Check if layout direction resolution can be done. 16806 * 16807 * @return true if layout direction resolution can be done otherwise return false. 16808 */ 16809 public boolean canResolveLayoutDirection() { 16810 switch (getRawLayoutDirection()) { 16811 case LAYOUT_DIRECTION_INHERIT: 16812 if (mParent != null) { 16813 try { 16814 return mParent.canResolveLayoutDirection(); 16815 } catch (AbstractMethodError e) { 16816 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 16817 " does not fully implement ViewParent", e); 16818 } 16819 } 16820 return false; 16821 16822 default: 16823 return true; 16824 } 16825 } 16826 16827 /** 16828 * Reset the resolved layout direction. Layout direction will be resolved during a call to 16829 * {@link #onMeasure(int, int)}. 16830 * 16831 * @hide 16832 */ 16833 public void resetResolvedLayoutDirection() { 16834 // Reset the current resolved bits 16835 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 16836 } 16837 16838 /** 16839 * @return true if the layout direction is inherited. 16840 * 16841 * @hide 16842 */ 16843 public boolean isLayoutDirectionInherited() { 16844 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 16845 } 16846 16847 /** 16848 * @return true if layout direction has been resolved. 16849 */ 16850 public boolean isLayoutDirectionResolved() { 16851 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 16852 } 16853 16854 /** 16855 * Return if padding has been resolved 16856 * 16857 * @hide 16858 */ 16859 boolean isPaddingResolved() { 16860 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 16861 } 16862 16863 /** 16864 * Resolves padding depending on layout direction, if applicable, and 16865 * recomputes internal padding values to adjust for scroll bars. 16866 * 16867 * @hide 16868 */ 16869 public void resolvePadding() { 16870 final int resolvedLayoutDirection = getLayoutDirection(); 16871 16872 if (!isRtlCompatibilityMode()) { 16873 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 16874 // If start / end padding are defined, they will be resolved (hence overriding) to 16875 // left / right or right / left depending on the resolved layout direction. 16876 // If start / end padding are not defined, use the left / right ones. 16877 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 16878 Rect padding = sThreadLocal.get(); 16879 if (padding == null) { 16880 padding = new Rect(); 16881 sThreadLocal.set(padding); 16882 } 16883 mBackground.getPadding(padding); 16884 if (!mLeftPaddingDefined) { 16885 mUserPaddingLeftInitial = padding.left; 16886 } 16887 if (!mRightPaddingDefined) { 16888 mUserPaddingRightInitial = padding.right; 16889 } 16890 } 16891 switch (resolvedLayoutDirection) { 16892 case LAYOUT_DIRECTION_RTL: 16893 if (mUserPaddingStart != UNDEFINED_PADDING) { 16894 mUserPaddingRight = mUserPaddingStart; 16895 } else { 16896 mUserPaddingRight = mUserPaddingRightInitial; 16897 } 16898 if (mUserPaddingEnd != UNDEFINED_PADDING) { 16899 mUserPaddingLeft = mUserPaddingEnd; 16900 } else { 16901 mUserPaddingLeft = mUserPaddingLeftInitial; 16902 } 16903 break; 16904 case LAYOUT_DIRECTION_LTR: 16905 default: 16906 if (mUserPaddingStart != UNDEFINED_PADDING) { 16907 mUserPaddingLeft = mUserPaddingStart; 16908 } else { 16909 mUserPaddingLeft = mUserPaddingLeftInitial; 16910 } 16911 if (mUserPaddingEnd != UNDEFINED_PADDING) { 16912 mUserPaddingRight = mUserPaddingEnd; 16913 } else { 16914 mUserPaddingRight = mUserPaddingRightInitial; 16915 } 16916 } 16917 16918 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 16919 } 16920 16921 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 16922 onRtlPropertiesChanged(resolvedLayoutDirection); 16923 16924 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 16925 } 16926 16927 /** 16928 * Reset the resolved layout direction. 16929 * 16930 * @hide 16931 */ 16932 public void resetResolvedPadding() { 16933 resetResolvedPaddingInternal(); 16934 } 16935 16936 /** 16937 * Used when we only want to reset *this* view's padding and not trigger overrides 16938 * in ViewGroup that reset children too. 16939 */ 16940 void resetResolvedPaddingInternal() { 16941 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 16942 } 16943 16944 /** 16945 * This is called when the view is detached from a window. At this point it 16946 * no longer has a surface for drawing. 16947 * 16948 * @see #onAttachedToWindow() 16949 */ 16950 @CallSuper 16951 protected void onDetachedFromWindow() { 16952 } 16953 16954 /** 16955 * This is a framework-internal mirror of onDetachedFromWindow() that's called 16956 * after onDetachedFromWindow(). 16957 * 16958 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 16959 * The super method should be called at the end of the overridden method to ensure 16960 * subclasses are destroyed first 16961 * 16962 * @hide 16963 */ 16964 @CallSuper 16965 protected void onDetachedFromWindowInternal() { 16966 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 16967 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 16968 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 16969 16970 removeUnsetPressCallback(); 16971 removeLongPressCallback(); 16972 removePerformClickCallback(); 16973 removeSendViewScrolledAccessibilityEventCallback(); 16974 stopNestedScroll(); 16975 16976 // Anything that started animating right before detach should already 16977 // be in its final state when re-attached. 16978 jumpDrawablesToCurrentState(); 16979 16980 destroyDrawingCache(); 16981 16982 cleanupDraw(); 16983 mCurrentAnimation = null; 16984 16985 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 16986 hideTooltip(); 16987 } 16988 } 16989 16990 private void cleanupDraw() { 16991 resetDisplayList(); 16992 if (mAttachInfo != null) { 16993 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 16994 } 16995 } 16996 16997 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 16998 } 16999 17000 /** 17001 * @return The number of times this view has been attached to a window 17002 */ 17003 protected int getWindowAttachCount() { 17004 return mWindowAttachCount; 17005 } 17006 17007 /** 17008 * Retrieve a unique token identifying the window this view is attached to. 17009 * @return Return the window's token for use in 17010 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 17011 */ 17012 public IBinder getWindowToken() { 17013 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 17014 } 17015 17016 /** 17017 * Retrieve the {@link WindowId} for the window this view is 17018 * currently attached to. 17019 */ 17020 public WindowId getWindowId() { 17021 if (mAttachInfo == null) { 17022 return null; 17023 } 17024 if (mAttachInfo.mWindowId == null) { 17025 try { 17026 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 17027 mAttachInfo.mWindowToken); 17028 mAttachInfo.mWindowId = new WindowId( 17029 mAttachInfo.mIWindowId); 17030 } catch (RemoteException e) { 17031 } 17032 } 17033 return mAttachInfo.mWindowId; 17034 } 17035 17036 /** 17037 * Retrieve a unique token identifying the top-level "real" window of 17038 * the window that this view is attached to. That is, this is like 17039 * {@link #getWindowToken}, except if the window this view in is a panel 17040 * window (attached to another containing window), then the token of 17041 * the containing window is returned instead. 17042 * 17043 * @return Returns the associated window token, either 17044 * {@link #getWindowToken()} or the containing window's token. 17045 */ 17046 public IBinder getApplicationWindowToken() { 17047 AttachInfo ai = mAttachInfo; 17048 if (ai != null) { 17049 IBinder appWindowToken = ai.mPanelParentWindowToken; 17050 if (appWindowToken == null) { 17051 appWindowToken = ai.mWindowToken; 17052 } 17053 return appWindowToken; 17054 } 17055 return null; 17056 } 17057 17058 /** 17059 * Gets the logical display to which the view's window has been attached. 17060 * 17061 * @return The logical display, or null if the view is not currently attached to a window. 17062 */ 17063 public Display getDisplay() { 17064 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 17065 } 17066 17067 /** 17068 * Retrieve private session object this view hierarchy is using to 17069 * communicate with the window manager. 17070 * @return the session object to communicate with the window manager 17071 */ 17072 /*package*/ IWindowSession getWindowSession() { 17073 return mAttachInfo != null ? mAttachInfo.mSession : null; 17074 } 17075 17076 /** 17077 * Return the visibility value of the least visible component passed. 17078 */ 17079 int combineVisibility(int vis1, int vis2) { 17080 // This works because VISIBLE < INVISIBLE < GONE. 17081 return Math.max(vis1, vis2); 17082 } 17083 17084 /** 17085 * @param info the {@link android.view.View.AttachInfo} to associated with 17086 * this view 17087 */ 17088 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 17089 mAttachInfo = info; 17090 if (mOverlay != null) { 17091 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 17092 } 17093 mWindowAttachCount++; 17094 // We will need to evaluate the drawable state at least once. 17095 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17096 if (mFloatingTreeObserver != null) { 17097 info.mTreeObserver.merge(mFloatingTreeObserver); 17098 mFloatingTreeObserver = null; 17099 } 17100 17101 registerPendingFrameMetricsObservers(); 17102 17103 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 17104 mAttachInfo.mScrollContainers.add(this); 17105 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 17106 } 17107 // Transfer all pending runnables. 17108 if (mRunQueue != null) { 17109 mRunQueue.executeActions(info.mHandler); 17110 mRunQueue = null; 17111 } 17112 performCollectViewAttributes(mAttachInfo, visibility); 17113 onAttachedToWindow(); 17114 17115 ListenerInfo li = mListenerInfo; 17116 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 17117 li != null ? li.mOnAttachStateChangeListeners : null; 17118 if (listeners != null && listeners.size() > 0) { 17119 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 17120 // perform the dispatching. The iterator is a safe guard against listeners that 17121 // could mutate the list by calling the various add/remove methods. This prevents 17122 // the array from being modified while we iterate it. 17123 for (OnAttachStateChangeListener listener : listeners) { 17124 listener.onViewAttachedToWindow(this); 17125 } 17126 } 17127 17128 int vis = info.mWindowVisibility; 17129 if (vis != GONE) { 17130 onWindowVisibilityChanged(vis); 17131 if (isShown()) { 17132 // Calling onVisibilityAggregated directly here since the subtree will also 17133 // receive dispatchAttachedToWindow and this same call 17134 onVisibilityAggregated(vis == VISIBLE); 17135 } 17136 } 17137 17138 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 17139 // As all views in the subtree will already receive dispatchAttachedToWindow 17140 // traversing the subtree again here is not desired. 17141 onVisibilityChanged(this, visibility); 17142 17143 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 17144 // If nobody has evaluated the drawable state yet, then do it now. 17145 refreshDrawableState(); 17146 } 17147 needGlobalAttributesUpdate(false); 17148 17149 notifyEnterOrExitForAutoFillIfNeeded(true); 17150 } 17151 17152 void dispatchDetachedFromWindow() { 17153 AttachInfo info = mAttachInfo; 17154 if (info != null) { 17155 int vis = info.mWindowVisibility; 17156 if (vis != GONE) { 17157 onWindowVisibilityChanged(GONE); 17158 if (isShown()) { 17159 // Invoking onVisibilityAggregated directly here since the subtree 17160 // will also receive detached from window 17161 onVisibilityAggregated(false); 17162 } 17163 } 17164 } 17165 17166 onDetachedFromWindow(); 17167 onDetachedFromWindowInternal(); 17168 17169 InputMethodManager imm = InputMethodManager.peekInstance(); 17170 if (imm != null) { 17171 imm.onViewDetachedFromWindow(this); 17172 } 17173 17174 ListenerInfo li = mListenerInfo; 17175 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 17176 li != null ? li.mOnAttachStateChangeListeners : null; 17177 if (listeners != null && listeners.size() > 0) { 17178 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 17179 // perform the dispatching. The iterator is a safe guard against listeners that 17180 // could mutate the list by calling the various add/remove methods. This prevents 17181 // the array from being modified while we iterate it. 17182 for (OnAttachStateChangeListener listener : listeners) { 17183 listener.onViewDetachedFromWindow(this); 17184 } 17185 } 17186 17187 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 17188 mAttachInfo.mScrollContainers.remove(this); 17189 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 17190 } 17191 17192 mAttachInfo = null; 17193 if (mOverlay != null) { 17194 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 17195 } 17196 17197 notifyEnterOrExitForAutoFillIfNeeded(false); 17198 } 17199 17200 /** 17201 * Cancel any deferred high-level input events that were previously posted to the event queue. 17202 * 17203 * <p>Many views post high-level events such as click handlers to the event queue 17204 * to run deferred in order to preserve a desired user experience - clearing visible 17205 * pressed states before executing, etc. This method will abort any events of this nature 17206 * that are currently in flight.</p> 17207 * 17208 * <p>Custom views that generate their own high-level deferred input events should override 17209 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 17210 * 17211 * <p>This will also cancel pending input events for any child views.</p> 17212 * 17213 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 17214 * This will not impact newer events posted after this call that may occur as a result of 17215 * lower-level input events still waiting in the queue. If you are trying to prevent 17216 * double-submitted events for the duration of some sort of asynchronous transaction 17217 * you should also take other steps to protect against unexpected double inputs e.g. calling 17218 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 17219 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 17220 */ 17221 public final void cancelPendingInputEvents() { 17222 dispatchCancelPendingInputEvents(); 17223 } 17224 17225 /** 17226 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 17227 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 17228 */ 17229 void dispatchCancelPendingInputEvents() { 17230 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 17231 onCancelPendingInputEvents(); 17232 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 17233 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 17234 " did not call through to super.onCancelPendingInputEvents()"); 17235 } 17236 } 17237 17238 /** 17239 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 17240 * a parent view. 17241 * 17242 * <p>This method is responsible for removing any pending high-level input events that were 17243 * posted to the event queue to run later. Custom view classes that post their own deferred 17244 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 17245 * {@link android.os.Handler} should override this method, call 17246 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 17247 * </p> 17248 */ 17249 public void onCancelPendingInputEvents() { 17250 removePerformClickCallback(); 17251 cancelLongPress(); 17252 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 17253 } 17254 17255 /** 17256 * Store this view hierarchy's frozen state into the given container. 17257 * 17258 * @param container The SparseArray in which to save the view's state. 17259 * 17260 * @see #restoreHierarchyState(android.util.SparseArray) 17261 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17262 * @see #onSaveInstanceState() 17263 */ 17264 public void saveHierarchyState(SparseArray<Parcelable> container) { 17265 dispatchSaveInstanceState(container); 17266 } 17267 17268 /** 17269 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 17270 * this view and its children. May be overridden to modify how freezing happens to a 17271 * view's children; for example, some views may want to not store state for their children. 17272 * 17273 * @param container The SparseArray in which to save the view's state. 17274 * 17275 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17276 * @see #saveHierarchyState(android.util.SparseArray) 17277 * @see #onSaveInstanceState() 17278 */ 17279 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 17280 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 17281 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 17282 Parcelable state = onSaveInstanceState(); 17283 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 17284 throw new IllegalStateException( 17285 "Derived class did not call super.onSaveInstanceState()"); 17286 } 17287 if (state != null) { 17288 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 17289 // + ": " + state); 17290 container.put(mID, state); 17291 } 17292 } 17293 } 17294 17295 /** 17296 * Hook allowing a view to generate a representation of its internal state 17297 * that can later be used to create a new instance with that same state. 17298 * This state should only contain information that is not persistent or can 17299 * not be reconstructed later. For example, you will never store your 17300 * current position on screen because that will be computed again when a 17301 * new instance of the view is placed in its view hierarchy. 17302 * <p> 17303 * Some examples of things you may store here: the current cursor position 17304 * in a text view (but usually not the text itself since that is stored in a 17305 * content provider or other persistent storage), the currently selected 17306 * item in a list view. 17307 * 17308 * @return Returns a Parcelable object containing the view's current dynamic 17309 * state, or null if there is nothing interesting to save. 17310 * @see #onRestoreInstanceState(android.os.Parcelable) 17311 * @see #saveHierarchyState(android.util.SparseArray) 17312 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17313 * @see #setSaveEnabled(boolean) 17314 */ 17315 @CallSuper 17316 @Nullable protected Parcelable onSaveInstanceState() { 17317 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17318 if (mStartActivityRequestWho != null || isAutofilled() 17319 || mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) { 17320 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 17321 17322 if (mStartActivityRequestWho != null) { 17323 state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED; 17324 } 17325 17326 if (isAutofilled()) { 17327 state.mSavedData |= BaseSavedState.IS_AUTOFILLED; 17328 } 17329 17330 if (mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) { 17331 state.mSavedData |= BaseSavedState.ACCESSIBILITY_ID; 17332 } 17333 17334 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 17335 state.mIsAutofilled = isAutofilled(); 17336 state.mAccessibilityViewId = mAccessibilityViewId; 17337 return state; 17338 } 17339 return BaseSavedState.EMPTY_STATE; 17340 } 17341 17342 /** 17343 * Restore this view hierarchy's frozen state from the given container. 17344 * 17345 * @param container The SparseArray which holds previously frozen states. 17346 * 17347 * @see #saveHierarchyState(android.util.SparseArray) 17348 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17349 * @see #onRestoreInstanceState(android.os.Parcelable) 17350 */ 17351 public void restoreHierarchyState(SparseArray<Parcelable> container) { 17352 dispatchRestoreInstanceState(container); 17353 } 17354 17355 /** 17356 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 17357 * state for this view and its children. May be overridden to modify how restoring 17358 * happens to a view's children; for example, some views may want to not store state 17359 * for their children. 17360 * 17361 * @param container The SparseArray which holds previously saved state. 17362 * 17363 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17364 * @see #restoreHierarchyState(android.util.SparseArray) 17365 * @see #onRestoreInstanceState(android.os.Parcelable) 17366 */ 17367 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 17368 if (mID != NO_ID) { 17369 Parcelable state = container.get(mID); 17370 if (state != null) { 17371 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 17372 // + ": " + state); 17373 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 17374 onRestoreInstanceState(state); 17375 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 17376 throw new IllegalStateException( 17377 "Derived class did not call super.onRestoreInstanceState()"); 17378 } 17379 } 17380 } 17381 } 17382 17383 /** 17384 * Hook allowing a view to re-apply a representation of its internal state that had previously 17385 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 17386 * null state. 17387 * 17388 * @param state The frozen state that had previously been returned by 17389 * {@link #onSaveInstanceState}. 17390 * 17391 * @see #onSaveInstanceState() 17392 * @see #restoreHierarchyState(android.util.SparseArray) 17393 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17394 */ 17395 @CallSuper 17396 protected void onRestoreInstanceState(Parcelable state) { 17397 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17398 if (state != null && !(state instanceof AbsSavedState)) { 17399 throw new IllegalArgumentException("Wrong state class, expecting View State but " 17400 + "received " + state.getClass().toString() + " instead. This usually happens " 17401 + "when two views of different type have the same id in the same hierarchy. " 17402 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 17403 + "other views do not use the same id."); 17404 } 17405 if (state != null && state instanceof BaseSavedState) { 17406 BaseSavedState baseState = (BaseSavedState) state; 17407 17408 if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) { 17409 mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved; 17410 } 17411 if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) { 17412 setAutofilled(baseState.mIsAutofilled); 17413 } 17414 if ((baseState.mSavedData & BaseSavedState.ACCESSIBILITY_ID) != 0) { 17415 mAccessibilityViewId = baseState.mAccessibilityViewId; 17416 } 17417 } 17418 } 17419 17420 /** 17421 * <p>Return the time at which the drawing of the view hierarchy started.</p> 17422 * 17423 * @return the drawing start time in milliseconds 17424 */ 17425 public long getDrawingTime() { 17426 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 17427 } 17428 17429 /** 17430 * <p>Enables or disables the duplication of the parent's state into this view. When 17431 * duplication is enabled, this view gets its drawable state from its parent rather 17432 * than from its own internal properties.</p> 17433 * 17434 * <p>Note: in the current implementation, setting this property to true after the 17435 * view was added to a ViewGroup might have no effect at all. This property should 17436 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 17437 * 17438 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 17439 * property is enabled, an exception will be thrown.</p> 17440 * 17441 * <p>Note: if the child view uses and updates additional states which are unknown to the 17442 * parent, these states should not be affected by this method.</p> 17443 * 17444 * @param enabled True to enable duplication of the parent's drawable state, false 17445 * to disable it. 17446 * 17447 * @see #getDrawableState() 17448 * @see #isDuplicateParentStateEnabled() 17449 */ 17450 public void setDuplicateParentStateEnabled(boolean enabled) { 17451 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 17452 } 17453 17454 /** 17455 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 17456 * 17457 * @return True if this view's drawable state is duplicated from the parent, 17458 * false otherwise 17459 * 17460 * @see #getDrawableState() 17461 * @see #setDuplicateParentStateEnabled(boolean) 17462 */ 17463 public boolean isDuplicateParentStateEnabled() { 17464 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 17465 } 17466 17467 /** 17468 * <p>Specifies the type of layer backing this view. The layer can be 17469 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17470 * {@link #LAYER_TYPE_HARDWARE}.</p> 17471 * 17472 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17473 * instance that controls how the layer is composed on screen. The following 17474 * properties of the paint are taken into account when composing the layer:</p> 17475 * <ul> 17476 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17477 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17478 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17479 * </ul> 17480 * 17481 * <p>If this view has an alpha value set to < 1.0 by calling 17482 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 17483 * by this view's alpha value.</p> 17484 * 17485 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 17486 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 17487 * for more information on when and how to use layers.</p> 17488 * 17489 * @param layerType The type of layer to use with this view, must be one of 17490 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17491 * {@link #LAYER_TYPE_HARDWARE} 17492 * @param paint The paint used to compose the layer. This argument is optional 17493 * and can be null. It is ignored when the layer type is 17494 * {@link #LAYER_TYPE_NONE} 17495 * 17496 * @see #getLayerType() 17497 * @see #LAYER_TYPE_NONE 17498 * @see #LAYER_TYPE_SOFTWARE 17499 * @see #LAYER_TYPE_HARDWARE 17500 * @see #setAlpha(float) 17501 * 17502 * @attr ref android.R.styleable#View_layerType 17503 */ 17504 public void setLayerType(int layerType, @Nullable Paint paint) { 17505 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 17506 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 17507 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 17508 } 17509 17510 boolean typeChanged = mRenderNode.setLayerType(layerType); 17511 17512 if (!typeChanged) { 17513 setLayerPaint(paint); 17514 return; 17515 } 17516 17517 if (layerType != LAYER_TYPE_SOFTWARE) { 17518 // Destroy any previous software drawing cache if present 17519 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 17520 // drawing cache created in View#draw when drawing to a SW canvas. 17521 destroyDrawingCache(); 17522 } 17523 17524 mLayerType = layerType; 17525 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 17526 mRenderNode.setLayerPaint(mLayerPaint); 17527 17528 // draw() behaves differently if we are on a layer, so we need to 17529 // invalidate() here 17530 invalidateParentCaches(); 17531 invalidate(true); 17532 } 17533 17534 /** 17535 * Updates the {@link Paint} object used with the current layer (used only if the current 17536 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 17537 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 17538 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 17539 * ensure that the view gets redrawn immediately. 17540 * 17541 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17542 * instance that controls how the layer is composed on screen. The following 17543 * properties of the paint are taken into account when composing the layer:</p> 17544 * <ul> 17545 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17546 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17547 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17548 * </ul> 17549 * 17550 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 17551 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 17552 * 17553 * @param paint The paint used to compose the layer. This argument is optional 17554 * and can be null. It is ignored when the layer type is 17555 * {@link #LAYER_TYPE_NONE} 17556 * 17557 * @see #setLayerType(int, android.graphics.Paint) 17558 */ 17559 public void setLayerPaint(@Nullable Paint paint) { 17560 int layerType = getLayerType(); 17561 if (layerType != LAYER_TYPE_NONE) { 17562 mLayerPaint = paint; 17563 if (layerType == LAYER_TYPE_HARDWARE) { 17564 if (mRenderNode.setLayerPaint(paint)) { 17565 invalidateViewProperty(false, false); 17566 } 17567 } else { 17568 invalidate(); 17569 } 17570 } 17571 } 17572 17573 /** 17574 * Indicates what type of layer is currently associated with this view. By default 17575 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 17576 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 17577 * for more information on the different types of layers. 17578 * 17579 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17580 * {@link #LAYER_TYPE_HARDWARE} 17581 * 17582 * @see #setLayerType(int, android.graphics.Paint) 17583 * @see #buildLayer() 17584 * @see #LAYER_TYPE_NONE 17585 * @see #LAYER_TYPE_SOFTWARE 17586 * @see #LAYER_TYPE_HARDWARE 17587 */ 17588 public int getLayerType() { 17589 return mLayerType; 17590 } 17591 17592 /** 17593 * Forces this view's layer to be created and this view to be rendered 17594 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 17595 * invoking this method will have no effect. 17596 * 17597 * This method can for instance be used to render a view into its layer before 17598 * starting an animation. If this view is complex, rendering into the layer 17599 * before starting the animation will avoid skipping frames. 17600 * 17601 * @throws IllegalStateException If this view is not attached to a window 17602 * 17603 * @see #setLayerType(int, android.graphics.Paint) 17604 */ 17605 public void buildLayer() { 17606 if (mLayerType == LAYER_TYPE_NONE) return; 17607 17608 final AttachInfo attachInfo = mAttachInfo; 17609 if (attachInfo == null) { 17610 throw new IllegalStateException("This view must be attached to a window first"); 17611 } 17612 17613 if (getWidth() == 0 || getHeight() == 0) { 17614 return; 17615 } 17616 17617 switch (mLayerType) { 17618 case LAYER_TYPE_HARDWARE: 17619 updateDisplayListIfDirty(); 17620 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 17621 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 17622 } 17623 break; 17624 case LAYER_TYPE_SOFTWARE: 17625 buildDrawingCache(true); 17626 break; 17627 } 17628 } 17629 17630 /** 17631 * Destroys all hardware rendering resources. This method is invoked 17632 * when the system needs to reclaim resources. Upon execution of this 17633 * method, you should free any OpenGL resources created by the view. 17634 * 17635 * Note: you <strong>must</strong> call 17636 * <code>super.destroyHardwareResources()</code> when overriding 17637 * this method. 17638 * 17639 * @hide 17640 */ 17641 @CallSuper 17642 protected void destroyHardwareResources() { 17643 if (mOverlay != null) { 17644 mOverlay.getOverlayView().destroyHardwareResources(); 17645 } 17646 if (mGhostView != null) { 17647 mGhostView.destroyHardwareResources(); 17648 } 17649 } 17650 17651 /** 17652 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 17653 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 17654 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 17655 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 17656 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 17657 * null.</p> 17658 * 17659 * <p>Enabling the drawing cache is similar to 17660 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 17661 * acceleration is turned off. When hardware acceleration is turned on, enabling the 17662 * drawing cache has no effect on rendering because the system uses a different mechanism 17663 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 17664 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 17665 * for information on how to enable software and hardware layers.</p> 17666 * 17667 * <p>This API can be used to manually generate 17668 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 17669 * {@link #getDrawingCache()}.</p> 17670 * 17671 * @param enabled true to enable the drawing cache, false otherwise 17672 * 17673 * @see #isDrawingCacheEnabled() 17674 * @see #getDrawingCache() 17675 * @see #buildDrawingCache() 17676 * @see #setLayerType(int, android.graphics.Paint) 17677 */ 17678 public void setDrawingCacheEnabled(boolean enabled) { 17679 mCachingFailed = false; 17680 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 17681 } 17682 17683 /** 17684 * <p>Indicates whether the drawing cache is enabled for this view.</p> 17685 * 17686 * @return true if the drawing cache is enabled 17687 * 17688 * @see #setDrawingCacheEnabled(boolean) 17689 * @see #getDrawingCache() 17690 */ 17691 @ViewDebug.ExportedProperty(category = "drawing") 17692 public boolean isDrawingCacheEnabled() { 17693 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 17694 } 17695 17696 /** 17697 * Debugging utility which recursively outputs the dirty state of a view and its 17698 * descendants. 17699 * 17700 * @hide 17701 */ 17702 @SuppressWarnings({"UnusedDeclaration"}) 17703 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 17704 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 17705 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 17706 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 17707 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 17708 if (clear) { 17709 mPrivateFlags &= clearMask; 17710 } 17711 if (this instanceof ViewGroup) { 17712 ViewGroup parent = (ViewGroup) this; 17713 final int count = parent.getChildCount(); 17714 for (int i = 0; i < count; i++) { 17715 final View child = parent.getChildAt(i); 17716 child.outputDirtyFlags(indent + " ", clear, clearMask); 17717 } 17718 } 17719 } 17720 17721 /** 17722 * This method is used by ViewGroup to cause its children to restore or recreate their 17723 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 17724 * to recreate its own display list, which would happen if it went through the normal 17725 * draw/dispatchDraw mechanisms. 17726 * 17727 * @hide 17728 */ 17729 protected void dispatchGetDisplayList() {} 17730 17731 /** 17732 * A view that is not attached or hardware accelerated cannot create a display list. 17733 * This method checks these conditions and returns the appropriate result. 17734 * 17735 * @return true if view has the ability to create a display list, false otherwise. 17736 * 17737 * @hide 17738 */ 17739 public boolean canHaveDisplayList() { 17740 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 17741 } 17742 17743 /** 17744 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 17745 * @hide 17746 */ 17747 @NonNull 17748 public RenderNode updateDisplayListIfDirty() { 17749 final RenderNode renderNode = mRenderNode; 17750 if (!canHaveDisplayList()) { 17751 // can't populate RenderNode, don't try 17752 return renderNode; 17753 } 17754 17755 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 17756 || !renderNode.isValid() 17757 || (mRecreateDisplayList)) { 17758 // Don't need to recreate the display list, just need to tell our 17759 // children to restore/recreate theirs 17760 if (renderNode.isValid() 17761 && !mRecreateDisplayList) { 17762 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17763 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17764 dispatchGetDisplayList(); 17765 17766 return renderNode; // no work needed 17767 } 17768 17769 // If we got here, we're recreating it. Mark it as such to ensure that 17770 // we copy in child display lists into ours in drawChild() 17771 mRecreateDisplayList = true; 17772 17773 int width = mRight - mLeft; 17774 int height = mBottom - mTop; 17775 int layerType = getLayerType(); 17776 17777 final DisplayListCanvas canvas = renderNode.start(width, height); 17778 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 17779 17780 try { 17781 if (layerType == LAYER_TYPE_SOFTWARE) { 17782 buildDrawingCache(true); 17783 Bitmap cache = getDrawingCache(true); 17784 if (cache != null) { 17785 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 17786 } 17787 } else { 17788 computeScroll(); 17789 17790 canvas.translate(-mScrollX, -mScrollY); 17791 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17792 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17793 17794 // Fast path for layouts with no backgrounds 17795 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17796 dispatchDraw(canvas); 17797 drawAutofilledHighlight(canvas); 17798 if (mOverlay != null && !mOverlay.isEmpty()) { 17799 mOverlay.getOverlayView().draw(canvas); 17800 } 17801 if (debugDraw()) { 17802 debugDrawFocus(canvas); 17803 } 17804 } else { 17805 draw(canvas); 17806 } 17807 } 17808 } finally { 17809 renderNode.end(canvas); 17810 setDisplayListProperties(renderNode); 17811 } 17812 } else { 17813 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17814 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17815 } 17816 return renderNode; 17817 } 17818 17819 private void resetDisplayList() { 17820 mRenderNode.discardDisplayList(); 17821 if (mBackgroundRenderNode != null) { 17822 mBackgroundRenderNode.discardDisplayList(); 17823 } 17824 } 17825 17826 /** 17827 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 17828 * 17829 * @return A non-scaled bitmap representing this view or null if cache is disabled. 17830 * 17831 * @see #getDrawingCache(boolean) 17832 */ 17833 public Bitmap getDrawingCache() { 17834 return getDrawingCache(false); 17835 } 17836 17837 /** 17838 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 17839 * is null when caching is disabled. If caching is enabled and the cache is not ready, 17840 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 17841 * draw from the cache when the cache is enabled. To benefit from the cache, you must 17842 * request the drawing cache by calling this method and draw it on screen if the 17843 * returned bitmap is not null.</p> 17844 * 17845 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17846 * this method will create a bitmap of the same size as this view. Because this bitmap 17847 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17848 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17849 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17850 * size than the view. This implies that your application must be able to handle this 17851 * size.</p> 17852 * 17853 * @param autoScale Indicates whether the generated bitmap should be scaled based on 17854 * the current density of the screen when the application is in compatibility 17855 * mode. 17856 * 17857 * @return A bitmap representing this view or null if cache is disabled. 17858 * 17859 * @see #setDrawingCacheEnabled(boolean) 17860 * @see #isDrawingCacheEnabled() 17861 * @see #buildDrawingCache(boolean) 17862 * @see #destroyDrawingCache() 17863 */ 17864 public Bitmap getDrawingCache(boolean autoScale) { 17865 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 17866 return null; 17867 } 17868 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 17869 buildDrawingCache(autoScale); 17870 } 17871 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 17872 } 17873 17874 /** 17875 * <p>Frees the resources used by the drawing cache. If you call 17876 * {@link #buildDrawingCache()} manually without calling 17877 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17878 * should cleanup the cache with this method afterwards.</p> 17879 * 17880 * @see #setDrawingCacheEnabled(boolean) 17881 * @see #buildDrawingCache() 17882 * @see #getDrawingCache() 17883 */ 17884 public void destroyDrawingCache() { 17885 if (mDrawingCache != null) { 17886 mDrawingCache.recycle(); 17887 mDrawingCache = null; 17888 } 17889 if (mUnscaledDrawingCache != null) { 17890 mUnscaledDrawingCache.recycle(); 17891 mUnscaledDrawingCache = null; 17892 } 17893 } 17894 17895 /** 17896 * Setting a solid background color for the drawing cache's bitmaps will improve 17897 * performance and memory usage. Note, though that this should only be used if this 17898 * view will always be drawn on top of a solid color. 17899 * 17900 * @param color The background color to use for the drawing cache's bitmap 17901 * 17902 * @see #setDrawingCacheEnabled(boolean) 17903 * @see #buildDrawingCache() 17904 * @see #getDrawingCache() 17905 */ 17906 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 17907 if (color != mDrawingCacheBackgroundColor) { 17908 mDrawingCacheBackgroundColor = color; 17909 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 17910 } 17911 } 17912 17913 /** 17914 * @see #setDrawingCacheBackgroundColor(int) 17915 * 17916 * @return The background color to used for the drawing cache's bitmap 17917 */ 17918 @ColorInt 17919 public int getDrawingCacheBackgroundColor() { 17920 return mDrawingCacheBackgroundColor; 17921 } 17922 17923 /** 17924 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 17925 * 17926 * @see #buildDrawingCache(boolean) 17927 */ 17928 public void buildDrawingCache() { 17929 buildDrawingCache(false); 17930 } 17931 17932 /** 17933 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 17934 * 17935 * <p>If you call {@link #buildDrawingCache()} manually without calling 17936 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17937 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 17938 * 17939 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17940 * this method will create a bitmap of the same size as this view. Because this bitmap 17941 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17942 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17943 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17944 * size than the view. This implies that your application must be able to handle this 17945 * size.</p> 17946 * 17947 * <p>You should avoid calling this method when hardware acceleration is enabled. If 17948 * you do not need the drawing cache bitmap, calling this method will increase memory 17949 * usage and cause the view to be rendered in software once, thus negatively impacting 17950 * performance.</p> 17951 * 17952 * @see #getDrawingCache() 17953 * @see #destroyDrawingCache() 17954 */ 17955 public void buildDrawingCache(boolean autoScale) { 17956 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 17957 mDrawingCache == null : mUnscaledDrawingCache == null)) { 17958 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 17959 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 17960 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 17961 } 17962 try { 17963 buildDrawingCacheImpl(autoScale); 17964 } finally { 17965 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 17966 } 17967 } 17968 } 17969 17970 /** 17971 * private, internal implementation of buildDrawingCache, used to enable tracing 17972 */ 17973 private void buildDrawingCacheImpl(boolean autoScale) { 17974 mCachingFailed = false; 17975 17976 int width = mRight - mLeft; 17977 int height = mBottom - mTop; 17978 17979 final AttachInfo attachInfo = mAttachInfo; 17980 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 17981 17982 if (autoScale && scalingRequired) { 17983 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 17984 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 17985 } 17986 17987 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 17988 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 17989 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 17990 17991 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 17992 final long drawingCacheSize = 17993 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 17994 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 17995 if (width > 0 && height > 0) { 17996 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 17997 + " too large to fit into a software layer (or drawing cache), needs " 17998 + projectedBitmapSize + " bytes, only " 17999 + drawingCacheSize + " available"); 18000 } 18001 destroyDrawingCache(); 18002 mCachingFailed = true; 18003 return; 18004 } 18005 18006 boolean clear = true; 18007 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 18008 18009 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 18010 Bitmap.Config quality; 18011 if (!opaque) { 18012 // Never pick ARGB_4444 because it looks awful 18013 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 18014 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 18015 case DRAWING_CACHE_QUALITY_AUTO: 18016 case DRAWING_CACHE_QUALITY_LOW: 18017 case DRAWING_CACHE_QUALITY_HIGH: 18018 default: 18019 quality = Bitmap.Config.ARGB_8888; 18020 break; 18021 } 18022 } else { 18023 // Optimization for translucent windows 18024 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 18025 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 18026 } 18027 18028 // Try to cleanup memory 18029 if (bitmap != null) bitmap.recycle(); 18030 18031 try { 18032 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 18033 width, height, quality); 18034 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 18035 if (autoScale) { 18036 mDrawingCache = bitmap; 18037 } else { 18038 mUnscaledDrawingCache = bitmap; 18039 } 18040 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 18041 } catch (OutOfMemoryError e) { 18042 // If there is not enough memory to create the bitmap cache, just 18043 // ignore the issue as bitmap caches are not required to draw the 18044 // view hierarchy 18045 if (autoScale) { 18046 mDrawingCache = null; 18047 } else { 18048 mUnscaledDrawingCache = null; 18049 } 18050 mCachingFailed = true; 18051 return; 18052 } 18053 18054 clear = drawingCacheBackgroundColor != 0; 18055 } 18056 18057 Canvas canvas; 18058 if (attachInfo != null) { 18059 canvas = attachInfo.mCanvas; 18060 if (canvas == null) { 18061 canvas = new Canvas(); 18062 } 18063 canvas.setBitmap(bitmap); 18064 // Temporarily clobber the cached Canvas in case one of our children 18065 // is also using a drawing cache. Without this, the children would 18066 // steal the canvas by attaching their own bitmap to it and bad, bad 18067 // thing would happen (invisible views, corrupted drawings, etc.) 18068 attachInfo.mCanvas = null; 18069 } else { 18070 // This case should hopefully never or seldom happen 18071 canvas = new Canvas(bitmap); 18072 } 18073 18074 if (clear) { 18075 bitmap.eraseColor(drawingCacheBackgroundColor); 18076 } 18077 18078 computeScroll(); 18079 final int restoreCount = canvas.save(); 18080 18081 if (autoScale && scalingRequired) { 18082 final float scale = attachInfo.mApplicationScale; 18083 canvas.scale(scale, scale); 18084 } 18085 18086 canvas.translate(-mScrollX, -mScrollY); 18087 18088 mPrivateFlags |= PFLAG_DRAWN; 18089 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 18090 mLayerType != LAYER_TYPE_NONE) { 18091 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 18092 } 18093 18094 // Fast path for layouts with no backgrounds 18095 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18096 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18097 dispatchDraw(canvas); 18098 drawAutofilledHighlight(canvas); 18099 if (mOverlay != null && !mOverlay.isEmpty()) { 18100 mOverlay.getOverlayView().draw(canvas); 18101 } 18102 } else { 18103 draw(canvas); 18104 } 18105 18106 canvas.restoreToCount(restoreCount); 18107 canvas.setBitmap(null); 18108 18109 if (attachInfo != null) { 18110 // Restore the cached Canvas for our siblings 18111 attachInfo.mCanvas = canvas; 18112 } 18113 } 18114 18115 /** 18116 * Create a snapshot of the view into a bitmap. We should probably make 18117 * some form of this public, but should think about the API. 18118 * 18119 * @hide 18120 */ 18121 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 18122 int width = mRight - mLeft; 18123 int height = mBottom - mTop; 18124 18125 final AttachInfo attachInfo = mAttachInfo; 18126 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 18127 width = (int) ((width * scale) + 0.5f); 18128 height = (int) ((height * scale) + 0.5f); 18129 18130 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 18131 width > 0 ? width : 1, height > 0 ? height : 1, quality); 18132 if (bitmap == null) { 18133 throw new OutOfMemoryError(); 18134 } 18135 18136 Resources resources = getResources(); 18137 if (resources != null) { 18138 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 18139 } 18140 18141 Canvas canvas; 18142 if (attachInfo != null) { 18143 canvas = attachInfo.mCanvas; 18144 if (canvas == null) { 18145 canvas = new Canvas(); 18146 } 18147 canvas.setBitmap(bitmap); 18148 // Temporarily clobber the cached Canvas in case one of our children 18149 // is also using a drawing cache. Without this, the children would 18150 // steal the canvas by attaching their own bitmap to it and bad, bad 18151 // things would happen (invisible views, corrupted drawings, etc.) 18152 attachInfo.mCanvas = null; 18153 } else { 18154 // This case should hopefully never or seldom happen 18155 canvas = new Canvas(bitmap); 18156 } 18157 boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled(); 18158 canvas.setHwBitmapsInSwModeEnabled(true); 18159 if ((backgroundColor & 0xff000000) != 0) { 18160 bitmap.eraseColor(backgroundColor); 18161 } 18162 18163 computeScroll(); 18164 final int restoreCount = canvas.save(); 18165 canvas.scale(scale, scale); 18166 canvas.translate(-mScrollX, -mScrollY); 18167 18168 // Temporarily remove the dirty mask 18169 int flags = mPrivateFlags; 18170 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18171 18172 // Fast path for layouts with no backgrounds 18173 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18174 dispatchDraw(canvas); 18175 drawAutofilledHighlight(canvas); 18176 if (mOverlay != null && !mOverlay.isEmpty()) { 18177 mOverlay.getOverlayView().draw(canvas); 18178 } 18179 } else { 18180 draw(canvas); 18181 } 18182 18183 mPrivateFlags = flags; 18184 18185 canvas.restoreToCount(restoreCount); 18186 canvas.setBitmap(null); 18187 canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode); 18188 18189 if (attachInfo != null) { 18190 // Restore the cached Canvas for our siblings 18191 attachInfo.mCanvas = canvas; 18192 } 18193 18194 return bitmap; 18195 } 18196 18197 /** 18198 * Indicates whether this View is currently in edit mode. A View is usually 18199 * in edit mode when displayed within a developer tool. For instance, if 18200 * this View is being drawn by a visual user interface builder, this method 18201 * should return true. 18202 * 18203 * Subclasses should check the return value of this method to provide 18204 * different behaviors if their normal behavior might interfere with the 18205 * host environment. For instance: the class spawns a thread in its 18206 * constructor, the drawing code relies on device-specific features, etc. 18207 * 18208 * This method is usually checked in the drawing code of custom widgets. 18209 * 18210 * @return True if this View is in edit mode, false otherwise. 18211 */ 18212 public boolean isInEditMode() { 18213 return false; 18214 } 18215 18216 /** 18217 * If the View draws content inside its padding and enables fading edges, 18218 * it needs to support padding offsets. Padding offsets are added to the 18219 * fading edges to extend the length of the fade so that it covers pixels 18220 * drawn inside the padding. 18221 * 18222 * Subclasses of this class should override this method if they need 18223 * to draw content inside the padding. 18224 * 18225 * @return True if padding offset must be applied, false otherwise. 18226 * 18227 * @see #getLeftPaddingOffset() 18228 * @see #getRightPaddingOffset() 18229 * @see #getTopPaddingOffset() 18230 * @see #getBottomPaddingOffset() 18231 * 18232 * @since CURRENT 18233 */ 18234 protected boolean isPaddingOffsetRequired() { 18235 return false; 18236 } 18237 18238 /** 18239 * Amount by which to extend the left fading region. Called only when 18240 * {@link #isPaddingOffsetRequired()} returns true. 18241 * 18242 * @return The left padding offset in pixels. 18243 * 18244 * @see #isPaddingOffsetRequired() 18245 * 18246 * @since CURRENT 18247 */ 18248 protected int getLeftPaddingOffset() { 18249 return 0; 18250 } 18251 18252 /** 18253 * Amount by which to extend the right fading region. Called only when 18254 * {@link #isPaddingOffsetRequired()} returns true. 18255 * 18256 * @return The right padding offset in pixels. 18257 * 18258 * @see #isPaddingOffsetRequired() 18259 * 18260 * @since CURRENT 18261 */ 18262 protected int getRightPaddingOffset() { 18263 return 0; 18264 } 18265 18266 /** 18267 * Amount by which to extend the top fading region. Called only when 18268 * {@link #isPaddingOffsetRequired()} returns true. 18269 * 18270 * @return The top padding offset in pixels. 18271 * 18272 * @see #isPaddingOffsetRequired() 18273 * 18274 * @since CURRENT 18275 */ 18276 protected int getTopPaddingOffset() { 18277 return 0; 18278 } 18279 18280 /** 18281 * Amount by which to extend the bottom fading region. Called only when 18282 * {@link #isPaddingOffsetRequired()} returns true. 18283 * 18284 * @return The bottom padding offset in pixels. 18285 * 18286 * @see #isPaddingOffsetRequired() 18287 * 18288 * @since CURRENT 18289 */ 18290 protected int getBottomPaddingOffset() { 18291 return 0; 18292 } 18293 18294 /** 18295 * @hide 18296 * @param offsetRequired 18297 */ 18298 protected int getFadeTop(boolean offsetRequired) { 18299 int top = mPaddingTop; 18300 if (offsetRequired) top += getTopPaddingOffset(); 18301 return top; 18302 } 18303 18304 /** 18305 * @hide 18306 * @param offsetRequired 18307 */ 18308 protected int getFadeHeight(boolean offsetRequired) { 18309 int padding = mPaddingTop; 18310 if (offsetRequired) padding += getTopPaddingOffset(); 18311 return mBottom - mTop - mPaddingBottom - padding; 18312 } 18313 18314 /** 18315 * <p>Indicates whether this view is attached to a hardware accelerated 18316 * window or not.</p> 18317 * 18318 * <p>Even if this method returns true, it does not mean that every call 18319 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 18320 * accelerated {@link android.graphics.Canvas}. For instance, if this view 18321 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 18322 * window is hardware accelerated, 18323 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 18324 * return false, and this method will return true.</p> 18325 * 18326 * @return True if the view is attached to a window and the window is 18327 * hardware accelerated; false in any other case. 18328 */ 18329 @ViewDebug.ExportedProperty(category = "drawing") 18330 public boolean isHardwareAccelerated() { 18331 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 18332 } 18333 18334 /** 18335 * Sets a rectangular area on this view to which the view will be clipped 18336 * when it is drawn. Setting the value to null will remove the clip bounds 18337 * and the view will draw normally, using its full bounds. 18338 * 18339 * @param clipBounds The rectangular area, in the local coordinates of 18340 * this view, to which future drawing operations will be clipped. 18341 */ 18342 public void setClipBounds(Rect clipBounds) { 18343 if (clipBounds == mClipBounds 18344 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 18345 return; 18346 } 18347 if (clipBounds != null) { 18348 if (mClipBounds == null) { 18349 mClipBounds = new Rect(clipBounds); 18350 } else { 18351 mClipBounds.set(clipBounds); 18352 } 18353 } else { 18354 mClipBounds = null; 18355 } 18356 mRenderNode.setClipBounds(mClipBounds); 18357 invalidateViewProperty(false, false); 18358 } 18359 18360 /** 18361 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 18362 * 18363 * @return A copy of the current clip bounds if clip bounds are set, 18364 * otherwise null. 18365 */ 18366 public Rect getClipBounds() { 18367 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 18368 } 18369 18370 18371 /** 18372 * Populates an output rectangle with the clip bounds of the view, 18373 * returning {@code true} if successful or {@code false} if the view's 18374 * clip bounds are {@code null}. 18375 * 18376 * @param outRect rectangle in which to place the clip bounds of the view 18377 * @return {@code true} if successful or {@code false} if the view's 18378 * clip bounds are {@code null} 18379 */ 18380 public boolean getClipBounds(Rect outRect) { 18381 if (mClipBounds != null) { 18382 outRect.set(mClipBounds); 18383 return true; 18384 } 18385 return false; 18386 } 18387 18388 /** 18389 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 18390 * case of an active Animation being run on the view. 18391 */ 18392 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 18393 Animation a, boolean scalingRequired) { 18394 Transformation invalidationTransform; 18395 final int flags = parent.mGroupFlags; 18396 final boolean initialized = a.isInitialized(); 18397 if (!initialized) { 18398 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 18399 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 18400 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 18401 onAnimationStart(); 18402 } 18403 18404 final Transformation t = parent.getChildTransformation(); 18405 boolean more = a.getTransformation(drawingTime, t, 1f); 18406 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 18407 if (parent.mInvalidationTransformation == null) { 18408 parent.mInvalidationTransformation = new Transformation(); 18409 } 18410 invalidationTransform = parent.mInvalidationTransformation; 18411 a.getTransformation(drawingTime, invalidationTransform, 1f); 18412 } else { 18413 invalidationTransform = t; 18414 } 18415 18416 if (more) { 18417 if (!a.willChangeBounds()) { 18418 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 18419 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 18420 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 18421 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 18422 // The child need to draw an animation, potentially offscreen, so 18423 // make sure we do not cancel invalidate requests 18424 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18425 parent.invalidate(mLeft, mTop, mRight, mBottom); 18426 } 18427 } else { 18428 if (parent.mInvalidateRegion == null) { 18429 parent.mInvalidateRegion = new RectF(); 18430 } 18431 final RectF region = parent.mInvalidateRegion; 18432 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 18433 invalidationTransform); 18434 18435 // The child need to draw an animation, potentially offscreen, so 18436 // make sure we do not cancel invalidate requests 18437 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18438 18439 final int left = mLeft + (int) region.left; 18440 final int top = mTop + (int) region.top; 18441 parent.invalidate(left, top, left + (int) (region.width() + .5f), 18442 top + (int) (region.height() + .5f)); 18443 } 18444 } 18445 return more; 18446 } 18447 18448 /** 18449 * This method is called by getDisplayList() when a display list is recorded for a View. 18450 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 18451 */ 18452 void setDisplayListProperties(RenderNode renderNode) { 18453 if (renderNode != null) { 18454 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 18455 renderNode.setClipToBounds(mParent instanceof ViewGroup 18456 && ((ViewGroup) mParent).getClipChildren()); 18457 18458 float alpha = 1; 18459 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 18460 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18461 ViewGroup parentVG = (ViewGroup) mParent; 18462 final Transformation t = parentVG.getChildTransformation(); 18463 if (parentVG.getChildStaticTransformation(this, t)) { 18464 final int transformType = t.getTransformationType(); 18465 if (transformType != Transformation.TYPE_IDENTITY) { 18466 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 18467 alpha = t.getAlpha(); 18468 } 18469 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 18470 renderNode.setStaticMatrix(t.getMatrix()); 18471 } 18472 } 18473 } 18474 } 18475 if (mTransformationInfo != null) { 18476 alpha *= getFinalAlpha(); 18477 if (alpha < 1) { 18478 final int multipliedAlpha = (int) (255 * alpha); 18479 if (onSetAlpha(multipliedAlpha)) { 18480 alpha = 1; 18481 } 18482 } 18483 renderNode.setAlpha(alpha); 18484 } else if (alpha < 1) { 18485 renderNode.setAlpha(alpha); 18486 } 18487 } 18488 } 18489 18490 /** 18491 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 18492 * 18493 * This is where the View specializes rendering behavior based on layer type, 18494 * and hardware acceleration. 18495 */ 18496 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 18497 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 18498 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 18499 * 18500 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 18501 * HW accelerated, it can't handle drawing RenderNodes. 18502 */ 18503 boolean drawingWithRenderNode = mAttachInfo != null 18504 && mAttachInfo.mHardwareAccelerated 18505 && hardwareAcceleratedCanvas; 18506 18507 boolean more = false; 18508 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 18509 final int parentFlags = parent.mGroupFlags; 18510 18511 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 18512 parent.getChildTransformation().clear(); 18513 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18514 } 18515 18516 Transformation transformToApply = null; 18517 boolean concatMatrix = false; 18518 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 18519 final Animation a = getAnimation(); 18520 if (a != null) { 18521 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 18522 concatMatrix = a.willChangeTransformationMatrix(); 18523 if (concatMatrix) { 18524 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18525 } 18526 transformToApply = parent.getChildTransformation(); 18527 } else { 18528 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 18529 // No longer animating: clear out old animation matrix 18530 mRenderNode.setAnimationMatrix(null); 18531 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18532 } 18533 if (!drawingWithRenderNode 18534 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18535 final Transformation t = parent.getChildTransformation(); 18536 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 18537 if (hasTransform) { 18538 final int transformType = t.getTransformationType(); 18539 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 18540 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 18541 } 18542 } 18543 } 18544 18545 concatMatrix |= !childHasIdentityMatrix; 18546 18547 // Sets the flag as early as possible to allow draw() implementations 18548 // to call invalidate() successfully when doing animations 18549 mPrivateFlags |= PFLAG_DRAWN; 18550 18551 if (!concatMatrix && 18552 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 18553 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 18554 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 18555 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 18556 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 18557 return more; 18558 } 18559 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 18560 18561 if (hardwareAcceleratedCanvas) { 18562 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 18563 // retain the flag's value temporarily in the mRecreateDisplayList flag 18564 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 18565 mPrivateFlags &= ~PFLAG_INVALIDATED; 18566 } 18567 18568 RenderNode renderNode = null; 18569 Bitmap cache = null; 18570 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 18571 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 18572 if (layerType != LAYER_TYPE_NONE) { 18573 // If not drawing with RenderNode, treat HW layers as SW 18574 layerType = LAYER_TYPE_SOFTWARE; 18575 buildDrawingCache(true); 18576 } 18577 cache = getDrawingCache(true); 18578 } 18579 18580 if (drawingWithRenderNode) { 18581 // Delay getting the display list until animation-driven alpha values are 18582 // set up and possibly passed on to the view 18583 renderNode = updateDisplayListIfDirty(); 18584 if (!renderNode.isValid()) { 18585 // Uncommon, but possible. If a view is removed from the hierarchy during the call 18586 // to getDisplayList(), the display list will be marked invalid and we should not 18587 // try to use it again. 18588 renderNode = null; 18589 drawingWithRenderNode = false; 18590 } 18591 } 18592 18593 int sx = 0; 18594 int sy = 0; 18595 if (!drawingWithRenderNode) { 18596 computeScroll(); 18597 sx = mScrollX; 18598 sy = mScrollY; 18599 } 18600 18601 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 18602 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 18603 18604 int restoreTo = -1; 18605 if (!drawingWithRenderNode || transformToApply != null) { 18606 restoreTo = canvas.save(); 18607 } 18608 if (offsetForScroll) { 18609 canvas.translate(mLeft - sx, mTop - sy); 18610 } else { 18611 if (!drawingWithRenderNode) { 18612 canvas.translate(mLeft, mTop); 18613 } 18614 if (scalingRequired) { 18615 if (drawingWithRenderNode) { 18616 // TODO: Might not need this if we put everything inside the DL 18617 restoreTo = canvas.save(); 18618 } 18619 // mAttachInfo cannot be null, otherwise scalingRequired == false 18620 final float scale = 1.0f / mAttachInfo.mApplicationScale; 18621 canvas.scale(scale, scale); 18622 } 18623 } 18624 18625 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 18626 if (transformToApply != null 18627 || alpha < 1 18628 || !hasIdentityMatrix() 18629 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18630 if (transformToApply != null || !childHasIdentityMatrix) { 18631 int transX = 0; 18632 int transY = 0; 18633 18634 if (offsetForScroll) { 18635 transX = -sx; 18636 transY = -sy; 18637 } 18638 18639 if (transformToApply != null) { 18640 if (concatMatrix) { 18641 if (drawingWithRenderNode) { 18642 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 18643 } else { 18644 // Undo the scroll translation, apply the transformation matrix, 18645 // then redo the scroll translate to get the correct result. 18646 canvas.translate(-transX, -transY); 18647 canvas.concat(transformToApply.getMatrix()); 18648 canvas.translate(transX, transY); 18649 } 18650 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18651 } 18652 18653 float transformAlpha = transformToApply.getAlpha(); 18654 if (transformAlpha < 1) { 18655 alpha *= transformAlpha; 18656 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18657 } 18658 } 18659 18660 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 18661 canvas.translate(-transX, -transY); 18662 canvas.concat(getMatrix()); 18663 canvas.translate(transX, transY); 18664 } 18665 } 18666 18667 // Deal with alpha if it is or used to be <1 18668 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18669 if (alpha < 1) { 18670 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18671 } else { 18672 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18673 } 18674 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18675 if (!drawingWithDrawingCache) { 18676 final int multipliedAlpha = (int) (255 * alpha); 18677 if (!onSetAlpha(multipliedAlpha)) { 18678 if (drawingWithRenderNode) { 18679 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 18680 } else if (layerType == LAYER_TYPE_NONE) { 18681 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 18682 multipliedAlpha); 18683 } 18684 } else { 18685 // Alpha is handled by the child directly, clobber the layer's alpha 18686 mPrivateFlags |= PFLAG_ALPHA_SET; 18687 } 18688 } 18689 } 18690 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18691 onSetAlpha(255); 18692 mPrivateFlags &= ~PFLAG_ALPHA_SET; 18693 } 18694 18695 if (!drawingWithRenderNode) { 18696 // apply clips directly, since RenderNode won't do it for this draw 18697 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 18698 if (offsetForScroll) { 18699 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 18700 } else { 18701 if (!scalingRequired || cache == null) { 18702 canvas.clipRect(0, 0, getWidth(), getHeight()); 18703 } else { 18704 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 18705 } 18706 } 18707 } 18708 18709 if (mClipBounds != null) { 18710 // clip bounds ignore scroll 18711 canvas.clipRect(mClipBounds); 18712 } 18713 } 18714 18715 if (!drawingWithDrawingCache) { 18716 if (drawingWithRenderNode) { 18717 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18718 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 18719 } else { 18720 // Fast path for layouts with no backgrounds 18721 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18722 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18723 dispatchDraw(canvas); 18724 } else { 18725 draw(canvas); 18726 } 18727 } 18728 } else if (cache != null) { 18729 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18730 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 18731 // no layer paint, use temporary paint to draw bitmap 18732 Paint cachePaint = parent.mCachePaint; 18733 if (cachePaint == null) { 18734 cachePaint = new Paint(); 18735 cachePaint.setDither(false); 18736 parent.mCachePaint = cachePaint; 18737 } 18738 cachePaint.setAlpha((int) (alpha * 255)); 18739 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 18740 } else { 18741 // use layer paint to draw the bitmap, merging the two alphas, but also restore 18742 int layerPaintAlpha = mLayerPaint.getAlpha(); 18743 if (alpha < 1) { 18744 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 18745 } 18746 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 18747 if (alpha < 1) { 18748 mLayerPaint.setAlpha(layerPaintAlpha); 18749 } 18750 } 18751 } 18752 18753 if (restoreTo >= 0) { 18754 canvas.restoreToCount(restoreTo); 18755 } 18756 18757 if (a != null && !more) { 18758 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 18759 onSetAlpha(255); 18760 } 18761 parent.finishAnimatingView(this, a); 18762 } 18763 18764 if (more && hardwareAcceleratedCanvas) { 18765 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18766 // alpha animations should cause the child to recreate its display list 18767 invalidate(true); 18768 } 18769 } 18770 18771 mRecreateDisplayList = false; 18772 18773 return more; 18774 } 18775 18776 static Paint getDebugPaint() { 18777 if (sDebugPaint == null) { 18778 sDebugPaint = new Paint(); 18779 sDebugPaint.setAntiAlias(false); 18780 } 18781 return sDebugPaint; 18782 } 18783 18784 final int dipsToPixels(int dips) { 18785 float scale = getContext().getResources().getDisplayMetrics().density; 18786 return (int) (dips * scale + 0.5f); 18787 } 18788 18789 final private void debugDrawFocus(Canvas canvas) { 18790 if (isFocused()) { 18791 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 18792 final int l = mScrollX; 18793 final int r = l + mRight - mLeft; 18794 final int t = mScrollY; 18795 final int b = t + mBottom - mTop; 18796 18797 final Paint paint = getDebugPaint(); 18798 paint.setColor(DEBUG_CORNERS_COLOR); 18799 18800 // Draw squares in corners. 18801 paint.setStyle(Paint.Style.FILL); 18802 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 18803 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 18804 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 18805 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 18806 18807 // Draw big X across the view. 18808 paint.setStyle(Paint.Style.STROKE); 18809 canvas.drawLine(l, t, r, b, paint); 18810 canvas.drawLine(l, b, r, t, paint); 18811 } 18812 } 18813 18814 /** 18815 * Manually render this view (and all of its children) to the given Canvas. 18816 * The view must have already done a full layout before this function is 18817 * called. When implementing a view, implement 18818 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 18819 * If you do need to override this method, call the superclass version. 18820 * 18821 * @param canvas The Canvas to which the View is rendered. 18822 */ 18823 @CallSuper 18824 public void draw(Canvas canvas) { 18825 final int privateFlags = mPrivateFlags; 18826 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 18827 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 18828 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 18829 18830 /* 18831 * Draw traversal performs several drawing steps which must be executed 18832 * in the appropriate order: 18833 * 18834 * 1. Draw the background 18835 * 2. If necessary, save the canvas' layers to prepare for fading 18836 * 3. Draw view's content 18837 * 4. Draw children 18838 * 5. If necessary, draw the fading edges and restore layers 18839 * 6. Draw decorations (scrollbars for instance) 18840 */ 18841 18842 // Step 1, draw the background, if needed 18843 int saveCount; 18844 18845 if (!dirtyOpaque) { 18846 drawBackground(canvas); 18847 } 18848 18849 // skip step 2 & 5 if possible (common case) 18850 final int viewFlags = mViewFlags; 18851 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 18852 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 18853 if (!verticalEdges && !horizontalEdges) { 18854 // Step 3, draw the content 18855 if (!dirtyOpaque) onDraw(canvas); 18856 18857 // Step 4, draw the children 18858 dispatchDraw(canvas); 18859 18860 drawAutofilledHighlight(canvas); 18861 18862 // Overlay is part of the content and draws beneath Foreground 18863 if (mOverlay != null && !mOverlay.isEmpty()) { 18864 mOverlay.getOverlayView().dispatchDraw(canvas); 18865 } 18866 18867 // Step 6, draw decorations (foreground, scrollbars) 18868 onDrawForeground(canvas); 18869 18870 // Step 7, draw the default focus highlight 18871 drawDefaultFocusHighlight(canvas); 18872 18873 if (debugDraw()) { 18874 debugDrawFocus(canvas); 18875 } 18876 18877 // we're done... 18878 return; 18879 } 18880 18881 /* 18882 * Here we do the full fledged routine... 18883 * (this is an uncommon case where speed matters less, 18884 * this is why we repeat some of the tests that have been 18885 * done above) 18886 */ 18887 18888 boolean drawTop = false; 18889 boolean drawBottom = false; 18890 boolean drawLeft = false; 18891 boolean drawRight = false; 18892 18893 float topFadeStrength = 0.0f; 18894 float bottomFadeStrength = 0.0f; 18895 float leftFadeStrength = 0.0f; 18896 float rightFadeStrength = 0.0f; 18897 18898 // Step 2, save the canvas' layers 18899 int paddingLeft = mPaddingLeft; 18900 18901 final boolean offsetRequired = isPaddingOffsetRequired(); 18902 if (offsetRequired) { 18903 paddingLeft += getLeftPaddingOffset(); 18904 } 18905 18906 int left = mScrollX + paddingLeft; 18907 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 18908 int top = mScrollY + getFadeTop(offsetRequired); 18909 int bottom = top + getFadeHeight(offsetRequired); 18910 18911 if (offsetRequired) { 18912 right += getRightPaddingOffset(); 18913 bottom += getBottomPaddingOffset(); 18914 } 18915 18916 final ScrollabilityCache scrollabilityCache = mScrollCache; 18917 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 18918 int length = (int) fadeHeight; 18919 18920 // clip the fade length if top and bottom fades overlap 18921 // overlapping fades produce odd-looking artifacts 18922 if (verticalEdges && (top + length > bottom - length)) { 18923 length = (bottom - top) / 2; 18924 } 18925 18926 // also clip horizontal fades if necessary 18927 if (horizontalEdges && (left + length > right - length)) { 18928 length = (right - left) / 2; 18929 } 18930 18931 if (verticalEdges) { 18932 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 18933 drawTop = topFadeStrength * fadeHeight > 1.0f; 18934 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 18935 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 18936 } 18937 18938 if (horizontalEdges) { 18939 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 18940 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 18941 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 18942 drawRight = rightFadeStrength * fadeHeight > 1.0f; 18943 } 18944 18945 saveCount = canvas.getSaveCount(); 18946 18947 int solidColor = getSolidColor(); 18948 if (solidColor == 0) { 18949 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 18950 18951 if (drawTop) { 18952 canvas.saveLayer(left, top, right, top + length, null, flags); 18953 } 18954 18955 if (drawBottom) { 18956 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 18957 } 18958 18959 if (drawLeft) { 18960 canvas.saveLayer(left, top, left + length, bottom, null, flags); 18961 } 18962 18963 if (drawRight) { 18964 canvas.saveLayer(right - length, top, right, bottom, null, flags); 18965 } 18966 } else { 18967 scrollabilityCache.setFadeColor(solidColor); 18968 } 18969 18970 // Step 3, draw the content 18971 if (!dirtyOpaque) onDraw(canvas); 18972 18973 // Step 4, draw the children 18974 dispatchDraw(canvas); 18975 18976 // Step 5, draw the fade effect and restore layers 18977 final Paint p = scrollabilityCache.paint; 18978 final Matrix matrix = scrollabilityCache.matrix; 18979 final Shader fade = scrollabilityCache.shader; 18980 18981 if (drawTop) { 18982 matrix.setScale(1, fadeHeight * topFadeStrength); 18983 matrix.postTranslate(left, top); 18984 fade.setLocalMatrix(matrix); 18985 p.setShader(fade); 18986 canvas.drawRect(left, top, right, top + length, p); 18987 } 18988 18989 if (drawBottom) { 18990 matrix.setScale(1, fadeHeight * bottomFadeStrength); 18991 matrix.postRotate(180); 18992 matrix.postTranslate(left, bottom); 18993 fade.setLocalMatrix(matrix); 18994 p.setShader(fade); 18995 canvas.drawRect(left, bottom - length, right, bottom, p); 18996 } 18997 18998 if (drawLeft) { 18999 matrix.setScale(1, fadeHeight * leftFadeStrength); 19000 matrix.postRotate(-90); 19001 matrix.postTranslate(left, top); 19002 fade.setLocalMatrix(matrix); 19003 p.setShader(fade); 19004 canvas.drawRect(left, top, left + length, bottom, p); 19005 } 19006 19007 if (drawRight) { 19008 matrix.setScale(1, fadeHeight * rightFadeStrength); 19009 matrix.postRotate(90); 19010 matrix.postTranslate(right, top); 19011 fade.setLocalMatrix(matrix); 19012 p.setShader(fade); 19013 canvas.drawRect(right - length, top, right, bottom, p); 19014 } 19015 19016 canvas.restoreToCount(saveCount); 19017 19018 drawAutofilledHighlight(canvas); 19019 19020 // Overlay is part of the content and draws beneath Foreground 19021 if (mOverlay != null && !mOverlay.isEmpty()) { 19022 mOverlay.getOverlayView().dispatchDraw(canvas); 19023 } 19024 19025 // Step 6, draw decorations (foreground, scrollbars) 19026 onDrawForeground(canvas); 19027 19028 if (debugDraw()) { 19029 debugDrawFocus(canvas); 19030 } 19031 } 19032 19033 /** 19034 * Draws the background onto the specified canvas. 19035 * 19036 * @param canvas Canvas on which to draw the background 19037 */ 19038 private void drawBackground(Canvas canvas) { 19039 final Drawable background = mBackground; 19040 if (background == null) { 19041 return; 19042 } 19043 19044 setBackgroundBounds(); 19045 19046 // Attempt to use a display list if requested. 19047 if (canvas.isHardwareAccelerated() && mAttachInfo != null 19048 && mAttachInfo.mThreadedRenderer != null) { 19049 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 19050 19051 final RenderNode renderNode = mBackgroundRenderNode; 19052 if (renderNode != null && renderNode.isValid()) { 19053 setBackgroundRenderNodeProperties(renderNode); 19054 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 19055 return; 19056 } 19057 } 19058 19059 final int scrollX = mScrollX; 19060 final int scrollY = mScrollY; 19061 if ((scrollX | scrollY) == 0) { 19062 background.draw(canvas); 19063 } else { 19064 canvas.translate(scrollX, scrollY); 19065 background.draw(canvas); 19066 canvas.translate(-scrollX, -scrollY); 19067 } 19068 } 19069 19070 /** 19071 * Sets the correct background bounds and rebuilds the outline, if needed. 19072 * <p/> 19073 * This is called by LayoutLib. 19074 */ 19075 void setBackgroundBounds() { 19076 if (mBackgroundSizeChanged && mBackground != null) { 19077 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 19078 mBackgroundSizeChanged = false; 19079 rebuildOutline(); 19080 } 19081 } 19082 19083 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 19084 renderNode.setTranslationX(mScrollX); 19085 renderNode.setTranslationY(mScrollY); 19086 } 19087 19088 /** 19089 * Creates a new display list or updates the existing display list for the 19090 * specified Drawable. 19091 * 19092 * @param drawable Drawable for which to create a display list 19093 * @param renderNode Existing RenderNode, or {@code null} 19094 * @return A valid display list for the specified drawable 19095 */ 19096 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 19097 if (renderNode == null) { 19098 renderNode = RenderNode.create(drawable.getClass().getName(), this); 19099 } 19100 19101 final Rect bounds = drawable.getBounds(); 19102 final int width = bounds.width(); 19103 final int height = bounds.height(); 19104 final DisplayListCanvas canvas = renderNode.start(width, height); 19105 19106 // Reverse left/top translation done by drawable canvas, which will 19107 // instead be applied by rendernode's LTRB bounds below. This way, the 19108 // drawable's bounds match with its rendernode bounds and its content 19109 // will lie within those bounds in the rendernode tree. 19110 canvas.translate(-bounds.left, -bounds.top); 19111 19112 try { 19113 drawable.draw(canvas); 19114 } finally { 19115 renderNode.end(canvas); 19116 } 19117 19118 // Set up drawable properties that are view-independent. 19119 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 19120 renderNode.setProjectBackwards(drawable.isProjected()); 19121 renderNode.setProjectionReceiver(true); 19122 renderNode.setClipToBounds(false); 19123 return renderNode; 19124 } 19125 19126 /** 19127 * Returns the overlay for this view, creating it if it does not yet exist. 19128 * Adding drawables to the overlay will cause them to be displayed whenever 19129 * the view itself is redrawn. Objects in the overlay should be actively 19130 * managed: remove them when they should not be displayed anymore. The 19131 * overlay will always have the same size as its host view. 19132 * 19133 * <p>Note: Overlays do not currently work correctly with {@link 19134 * SurfaceView} or {@link TextureView}; contents in overlays for these 19135 * types of views may not display correctly.</p> 19136 * 19137 * @return The ViewOverlay object for this view. 19138 * @see ViewOverlay 19139 */ 19140 public ViewOverlay getOverlay() { 19141 if (mOverlay == null) { 19142 mOverlay = new ViewOverlay(mContext, this); 19143 } 19144 return mOverlay; 19145 } 19146 19147 /** 19148 * Override this if your view is known to always be drawn on top of a solid color background, 19149 * and needs to draw fading edges. Returning a non-zero color enables the view system to 19150 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 19151 * should be set to 0xFF. 19152 * 19153 * @see #setVerticalFadingEdgeEnabled(boolean) 19154 * @see #setHorizontalFadingEdgeEnabled(boolean) 19155 * 19156 * @return The known solid color background for this view, or 0 if the color may vary 19157 */ 19158 @ViewDebug.ExportedProperty(category = "drawing") 19159 @ColorInt 19160 public int getSolidColor() { 19161 return 0; 19162 } 19163 19164 /** 19165 * Build a human readable string representation of the specified view flags. 19166 * 19167 * @param flags the view flags to convert to a string 19168 * @return a String representing the supplied flags 19169 */ 19170 private static String printFlags(int flags) { 19171 String output = ""; 19172 int numFlags = 0; 19173 if ((flags & FOCUSABLE) == FOCUSABLE) { 19174 output += "TAKES_FOCUS"; 19175 numFlags++; 19176 } 19177 19178 switch (flags & VISIBILITY_MASK) { 19179 case INVISIBLE: 19180 if (numFlags > 0) { 19181 output += " "; 19182 } 19183 output += "INVISIBLE"; 19184 // USELESS HERE numFlags++; 19185 break; 19186 case GONE: 19187 if (numFlags > 0) { 19188 output += " "; 19189 } 19190 output += "GONE"; 19191 // USELESS HERE numFlags++; 19192 break; 19193 default: 19194 break; 19195 } 19196 return output; 19197 } 19198 19199 /** 19200 * Build a human readable string representation of the specified private 19201 * view flags. 19202 * 19203 * @param privateFlags the private view flags to convert to a string 19204 * @return a String representing the supplied flags 19205 */ 19206 private static String printPrivateFlags(int privateFlags) { 19207 String output = ""; 19208 int numFlags = 0; 19209 19210 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 19211 output += "WANTS_FOCUS"; 19212 numFlags++; 19213 } 19214 19215 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 19216 if (numFlags > 0) { 19217 output += " "; 19218 } 19219 output += "FOCUSED"; 19220 numFlags++; 19221 } 19222 19223 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 19224 if (numFlags > 0) { 19225 output += " "; 19226 } 19227 output += "SELECTED"; 19228 numFlags++; 19229 } 19230 19231 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 19232 if (numFlags > 0) { 19233 output += " "; 19234 } 19235 output += "IS_ROOT_NAMESPACE"; 19236 numFlags++; 19237 } 19238 19239 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 19240 if (numFlags > 0) { 19241 output += " "; 19242 } 19243 output += "HAS_BOUNDS"; 19244 numFlags++; 19245 } 19246 19247 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 19248 if (numFlags > 0) { 19249 output += " "; 19250 } 19251 output += "DRAWN"; 19252 // USELESS HERE numFlags++; 19253 } 19254 return output; 19255 } 19256 19257 /** 19258 * <p>Indicates whether or not this view's layout will be requested during 19259 * the next hierarchy layout pass.</p> 19260 * 19261 * @return true if the layout will be forced during next layout pass 19262 */ 19263 public boolean isLayoutRequested() { 19264 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19265 } 19266 19267 /** 19268 * Return true if o is a ViewGroup that is laying out using optical bounds. 19269 * @hide 19270 */ 19271 public static boolean isLayoutModeOptical(Object o) { 19272 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 19273 } 19274 19275 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 19276 Insets parentInsets = mParent instanceof View ? 19277 ((View) mParent).getOpticalInsets() : Insets.NONE; 19278 Insets childInsets = getOpticalInsets(); 19279 return setFrame( 19280 left + parentInsets.left - childInsets.left, 19281 top + parentInsets.top - childInsets.top, 19282 right + parentInsets.left + childInsets.right, 19283 bottom + parentInsets.top + childInsets.bottom); 19284 } 19285 19286 /** 19287 * Assign a size and position to a view and all of its 19288 * descendants 19289 * 19290 * <p>This is the second phase of the layout mechanism. 19291 * (The first is measuring). In this phase, each parent calls 19292 * layout on all of its children to position them. 19293 * This is typically done using the child measurements 19294 * that were stored in the measure pass().</p> 19295 * 19296 * <p>Derived classes should not override this method. 19297 * Derived classes with children should override 19298 * onLayout. In that method, they should 19299 * call layout on each of their children.</p> 19300 * 19301 * @param l Left position, relative to parent 19302 * @param t Top position, relative to parent 19303 * @param r Right position, relative to parent 19304 * @param b Bottom position, relative to parent 19305 */ 19306 @SuppressWarnings({"unchecked"}) 19307 public void layout(int l, int t, int r, int b) { 19308 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 19309 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 19310 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19311 } 19312 19313 int oldL = mLeft; 19314 int oldT = mTop; 19315 int oldB = mBottom; 19316 int oldR = mRight; 19317 19318 boolean changed = isLayoutModeOptical(mParent) ? 19319 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 19320 19321 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 19322 onLayout(changed, l, t, r, b); 19323 19324 if (shouldDrawRoundScrollbar()) { 19325 if(mRoundScrollbarRenderer == null) { 19326 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 19327 } 19328 } else { 19329 mRoundScrollbarRenderer = null; 19330 } 19331 19332 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 19333 19334 ListenerInfo li = mListenerInfo; 19335 if (li != null && li.mOnLayoutChangeListeners != null) { 19336 ArrayList<OnLayoutChangeListener> listenersCopy = 19337 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 19338 int numListeners = listenersCopy.size(); 19339 for (int i = 0; i < numListeners; ++i) { 19340 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 19341 } 19342 } 19343 } 19344 19345 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 19346 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 19347 19348 if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) { 19349 mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT; 19350 notifyEnterOrExitForAutoFillIfNeeded(true); 19351 } 19352 } 19353 19354 /** 19355 * Called from layout when this view should 19356 * assign a size and position to each of its children. 19357 * 19358 * Derived classes with children should override 19359 * this method and call layout on each of 19360 * their children. 19361 * @param changed This is a new size or position for this view 19362 * @param left Left position, relative to parent 19363 * @param top Top position, relative to parent 19364 * @param right Right position, relative to parent 19365 * @param bottom Bottom position, relative to parent 19366 */ 19367 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 19368 } 19369 19370 /** 19371 * Assign a size and position to this view. 19372 * 19373 * This is called from layout. 19374 * 19375 * @param left Left position, relative to parent 19376 * @param top Top position, relative to parent 19377 * @param right Right position, relative to parent 19378 * @param bottom Bottom position, relative to parent 19379 * @return true if the new size and position are different than the 19380 * previous ones 19381 * {@hide} 19382 */ 19383 protected boolean setFrame(int left, int top, int right, int bottom) { 19384 boolean changed = false; 19385 19386 if (DBG) { 19387 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 19388 + right + "," + bottom + ")"); 19389 } 19390 19391 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 19392 changed = true; 19393 19394 // Remember our drawn bit 19395 int drawn = mPrivateFlags & PFLAG_DRAWN; 19396 19397 int oldWidth = mRight - mLeft; 19398 int oldHeight = mBottom - mTop; 19399 int newWidth = right - left; 19400 int newHeight = bottom - top; 19401 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 19402 19403 // Invalidate our old position 19404 invalidate(sizeChanged); 19405 19406 mLeft = left; 19407 mTop = top; 19408 mRight = right; 19409 mBottom = bottom; 19410 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 19411 19412 mPrivateFlags |= PFLAG_HAS_BOUNDS; 19413 19414 19415 if (sizeChanged) { 19416 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 19417 } 19418 19419 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 19420 // If we are visible, force the DRAWN bit to on so that 19421 // this invalidate will go through (at least to our parent). 19422 // This is because someone may have invalidated this view 19423 // before this call to setFrame came in, thereby clearing 19424 // the DRAWN bit. 19425 mPrivateFlags |= PFLAG_DRAWN; 19426 invalidate(sizeChanged); 19427 // parent display list may need to be recreated based on a change in the bounds 19428 // of any child 19429 invalidateParentCaches(); 19430 } 19431 19432 // Reset drawn bit to original value (invalidate turns it off) 19433 mPrivateFlags |= drawn; 19434 19435 mBackgroundSizeChanged = true; 19436 mDefaultFocusHighlightSizeChanged = true; 19437 if (mForegroundInfo != null) { 19438 mForegroundInfo.mBoundsChanged = true; 19439 } 19440 19441 notifySubtreeAccessibilityStateChangedIfNeeded(); 19442 } 19443 return changed; 19444 } 19445 19446 /** 19447 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 19448 * @hide 19449 */ 19450 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 19451 setFrame(left, top, right, bottom); 19452 } 19453 19454 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 19455 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 19456 if (mOverlay != null) { 19457 mOverlay.getOverlayView().setRight(newWidth); 19458 mOverlay.getOverlayView().setBottom(newHeight); 19459 } 19460 rebuildOutline(); 19461 } 19462 19463 /** 19464 * Finalize inflating a view from XML. This is called as the last phase 19465 * of inflation, after all child views have been added. 19466 * 19467 * <p>Even if the subclass overrides onFinishInflate, they should always be 19468 * sure to call the super method, so that we get called. 19469 */ 19470 @CallSuper 19471 protected void onFinishInflate() { 19472 } 19473 19474 /** 19475 * Returns the resources associated with this view. 19476 * 19477 * @return Resources object. 19478 */ 19479 public Resources getResources() { 19480 return mResources; 19481 } 19482 19483 /** 19484 * Invalidates the specified Drawable. 19485 * 19486 * @param drawable the drawable to invalidate 19487 */ 19488 @Override 19489 public void invalidateDrawable(@NonNull Drawable drawable) { 19490 if (verifyDrawable(drawable)) { 19491 final Rect dirty = drawable.getDirtyBounds(); 19492 final int scrollX = mScrollX; 19493 final int scrollY = mScrollY; 19494 19495 invalidate(dirty.left + scrollX, dirty.top + scrollY, 19496 dirty.right + scrollX, dirty.bottom + scrollY); 19497 rebuildOutline(); 19498 } 19499 } 19500 19501 /** 19502 * Schedules an action on a drawable to occur at a specified time. 19503 * 19504 * @param who the recipient of the action 19505 * @param what the action to run on the drawable 19506 * @param when the time at which the action must occur. Uses the 19507 * {@link SystemClock#uptimeMillis} timebase. 19508 */ 19509 @Override 19510 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 19511 if (verifyDrawable(who) && what != null) { 19512 final long delay = when - SystemClock.uptimeMillis(); 19513 if (mAttachInfo != null) { 19514 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 19515 Choreographer.CALLBACK_ANIMATION, what, who, 19516 Choreographer.subtractFrameDelay(delay)); 19517 } else { 19518 // Postpone the runnable until we know 19519 // on which thread it needs to run. 19520 getRunQueue().postDelayed(what, delay); 19521 } 19522 } 19523 } 19524 19525 /** 19526 * Cancels a scheduled action on a drawable. 19527 * 19528 * @param who the recipient of the action 19529 * @param what the action to cancel 19530 */ 19531 @Override 19532 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 19533 if (verifyDrawable(who) && what != null) { 19534 if (mAttachInfo != null) { 19535 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19536 Choreographer.CALLBACK_ANIMATION, what, who); 19537 } 19538 getRunQueue().removeCallbacks(what); 19539 } 19540 } 19541 19542 /** 19543 * Unschedule any events associated with the given Drawable. This can be 19544 * used when selecting a new Drawable into a view, so that the previous 19545 * one is completely unscheduled. 19546 * 19547 * @param who The Drawable to unschedule. 19548 * 19549 * @see #drawableStateChanged 19550 */ 19551 public void unscheduleDrawable(Drawable who) { 19552 if (mAttachInfo != null && who != null) { 19553 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19554 Choreographer.CALLBACK_ANIMATION, null, who); 19555 } 19556 } 19557 19558 /** 19559 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 19560 * that the View directionality can and will be resolved before its Drawables. 19561 * 19562 * Will call {@link View#onResolveDrawables} when resolution is done. 19563 * 19564 * @hide 19565 */ 19566 protected void resolveDrawables() { 19567 // Drawables resolution may need to happen before resolving the layout direction (which is 19568 // done only during the measure() call). 19569 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 19570 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 19571 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 19572 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 19573 // direction to be resolved as its resolved value will be the same as its raw value. 19574 if (!isLayoutDirectionResolved() && 19575 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 19576 return; 19577 } 19578 19579 final int layoutDirection = isLayoutDirectionResolved() ? 19580 getLayoutDirection() : getRawLayoutDirection(); 19581 19582 if (mBackground != null) { 19583 mBackground.setLayoutDirection(layoutDirection); 19584 } 19585 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19586 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 19587 } 19588 if (mDefaultFocusHighlight != null) { 19589 mDefaultFocusHighlight.setLayoutDirection(layoutDirection); 19590 } 19591 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 19592 onResolveDrawables(layoutDirection); 19593 } 19594 19595 boolean areDrawablesResolved() { 19596 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 19597 } 19598 19599 /** 19600 * Called when layout direction has been resolved. 19601 * 19602 * The default implementation does nothing. 19603 * 19604 * @param layoutDirection The resolved layout direction. 19605 * 19606 * @see #LAYOUT_DIRECTION_LTR 19607 * @see #LAYOUT_DIRECTION_RTL 19608 * 19609 * @hide 19610 */ 19611 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 19612 } 19613 19614 /** 19615 * @hide 19616 */ 19617 protected void resetResolvedDrawables() { 19618 resetResolvedDrawablesInternal(); 19619 } 19620 19621 void resetResolvedDrawablesInternal() { 19622 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 19623 } 19624 19625 /** 19626 * If your view subclass is displaying its own Drawable objects, it should 19627 * override this function and return true for any Drawable it is 19628 * displaying. This allows animations for those drawables to be 19629 * scheduled. 19630 * 19631 * <p>Be sure to call through to the super class when overriding this 19632 * function. 19633 * 19634 * @param who The Drawable to verify. Return true if it is one you are 19635 * displaying, else return the result of calling through to the 19636 * super class. 19637 * 19638 * @return boolean If true than the Drawable is being displayed in the 19639 * view; else false and it is not allowed to animate. 19640 * 19641 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 19642 * @see #drawableStateChanged() 19643 */ 19644 @CallSuper 19645 protected boolean verifyDrawable(@NonNull Drawable who) { 19646 // Avoid verifying the scroll bar drawable so that we don't end up in 19647 // an invalidation loop. This effectively prevents the scroll bar 19648 // drawable from triggering invalidations and scheduling runnables. 19649 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who) 19650 || (mDefaultFocusHighlight == who); 19651 } 19652 19653 /** 19654 * This function is called whenever the state of the view changes in such 19655 * a way that it impacts the state of drawables being shown. 19656 * <p> 19657 * If the View has a StateListAnimator, it will also be called to run necessary state 19658 * change animations. 19659 * <p> 19660 * Be sure to call through to the superclass when overriding this function. 19661 * 19662 * @see Drawable#setState(int[]) 19663 */ 19664 @CallSuper 19665 protected void drawableStateChanged() { 19666 final int[] state = getDrawableState(); 19667 boolean changed = false; 19668 19669 final Drawable bg = mBackground; 19670 if (bg != null && bg.isStateful()) { 19671 changed |= bg.setState(state); 19672 } 19673 19674 final Drawable hl = mDefaultFocusHighlight; 19675 if (hl != null && hl.isStateful()) { 19676 changed |= hl.setState(state); 19677 } 19678 19679 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19680 if (fg != null && fg.isStateful()) { 19681 changed |= fg.setState(state); 19682 } 19683 19684 if (mScrollCache != null) { 19685 final Drawable scrollBar = mScrollCache.scrollBar; 19686 if (scrollBar != null && scrollBar.isStateful()) { 19687 changed |= scrollBar.setState(state) 19688 && mScrollCache.state != ScrollabilityCache.OFF; 19689 } 19690 } 19691 19692 if (mStateListAnimator != null) { 19693 mStateListAnimator.setState(state); 19694 } 19695 19696 if (changed) { 19697 invalidate(); 19698 } 19699 } 19700 19701 /** 19702 * This function is called whenever the view hotspot changes and needs to 19703 * be propagated to drawables or child views managed by the view. 19704 * <p> 19705 * Dispatching to child views is handled by 19706 * {@link #dispatchDrawableHotspotChanged(float, float)}. 19707 * <p> 19708 * Be sure to call through to the superclass when overriding this function. 19709 * 19710 * @param x hotspot x coordinate 19711 * @param y hotspot y coordinate 19712 */ 19713 @CallSuper 19714 public void drawableHotspotChanged(float x, float y) { 19715 if (mBackground != null) { 19716 mBackground.setHotspot(x, y); 19717 } 19718 if (mDefaultFocusHighlight != null) { 19719 mDefaultFocusHighlight.setHotspot(x, y); 19720 } 19721 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19722 mForegroundInfo.mDrawable.setHotspot(x, y); 19723 } 19724 19725 dispatchDrawableHotspotChanged(x, y); 19726 } 19727 19728 /** 19729 * Dispatches drawableHotspotChanged to all of this View's children. 19730 * 19731 * @param x hotspot x coordinate 19732 * @param y hotspot y coordinate 19733 * @see #drawableHotspotChanged(float, float) 19734 */ 19735 public void dispatchDrawableHotspotChanged(float x, float y) { 19736 } 19737 19738 /** 19739 * Call this to force a view to update its drawable state. This will cause 19740 * drawableStateChanged to be called on this view. Views that are interested 19741 * in the new state should call getDrawableState. 19742 * 19743 * @see #drawableStateChanged 19744 * @see #getDrawableState 19745 */ 19746 public void refreshDrawableState() { 19747 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 19748 drawableStateChanged(); 19749 19750 ViewParent parent = mParent; 19751 if (parent != null) { 19752 parent.childDrawableStateChanged(this); 19753 } 19754 } 19755 19756 /** 19757 * Create a default focus highlight if it doesn't exist. 19758 * @return a default focus highlight. 19759 */ 19760 private Drawable getDefaultFocusHighlightDrawable() { 19761 if (mDefaultFocusHighlightCache == null) { 19762 if (mContext != null) { 19763 final int[] attrs = new int[] { android.R.attr.selectableItemBackground }; 19764 final TypedArray ta = mContext.obtainStyledAttributes(attrs); 19765 mDefaultFocusHighlightCache = ta.getDrawable(0); 19766 ta.recycle(); 19767 } 19768 } 19769 return mDefaultFocusHighlightCache; 19770 } 19771 19772 /** 19773 * Set the current default focus highlight. 19774 * @param highlight the highlight drawable, or {@code null} if it's no longer needed. 19775 */ 19776 private void setDefaultFocusHighlight(Drawable highlight) { 19777 mDefaultFocusHighlight = highlight; 19778 mDefaultFocusHighlightSizeChanged = true; 19779 if (highlight != null) { 19780 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 19781 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 19782 } 19783 highlight.setLayoutDirection(getLayoutDirection()); 19784 if (highlight.isStateful()) { 19785 highlight.setState(getDrawableState()); 19786 } 19787 if (isAttachedToWindow()) { 19788 highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 19789 } 19790 // Set callback last, since the view may still be initializing. 19791 highlight.setCallback(this); 19792 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 19793 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 19794 mPrivateFlags |= PFLAG_SKIP_DRAW; 19795 } 19796 requestLayout(); 19797 invalidate(); 19798 } 19799 19800 /** 19801 * Check whether we need to draw a default focus highlight when this view gets focused, 19802 * which requires: 19803 * <ul> 19804 * <li>In the background, {@link android.R.attr#state_focused} is not defined.</li> 19805 * <li>This view is not in touch mode.</li> 19806 * <li>This view doesn't opt out for a default focus highlight, via 19807 * {@link #setDefaultFocusHighlightEnabled(boolean)}.</li> 19808 * <li>This view is attached to window.</li> 19809 * </ul> 19810 * @return {@code true} if a default focus highlight is needed. 19811 */ 19812 private boolean isDefaultFocusHighlightNeeded(Drawable background) { 19813 final boolean hasFocusStateSpecified = background == null || !background.isStateful() 19814 || !background.hasFocusStateSpecified(); 19815 return !isInTouchMode() && getDefaultFocusHighlightEnabled() && hasFocusStateSpecified 19816 && isAttachedToWindow() && sUseDefaultFocusHighlight; 19817 } 19818 19819 /** 19820 * When this view is focused, switches on/off the default focused highlight. 19821 * <p> 19822 * This always happens when this view is focused, and only at this moment the default focus 19823 * highlight can be visible. 19824 */ 19825 private void switchDefaultFocusHighlight() { 19826 if (isFocused()) { 19827 final boolean needed = isDefaultFocusHighlightNeeded(mBackground); 19828 final boolean active = mDefaultFocusHighlight != null; 19829 if (needed && !active) { 19830 setDefaultFocusHighlight(getDefaultFocusHighlightDrawable()); 19831 } else if (!needed && active) { 19832 // The highlight is no longer needed, so tear it down. 19833 setDefaultFocusHighlight(null); 19834 } 19835 } 19836 } 19837 19838 /** 19839 * Draw the default focus highlight onto the canvas. 19840 * @param canvas the canvas where we're drawing the highlight. 19841 */ 19842 private void drawDefaultFocusHighlight(Canvas canvas) { 19843 if (mDefaultFocusHighlight != null) { 19844 if (mDefaultFocusHighlightSizeChanged) { 19845 mDefaultFocusHighlightSizeChanged = false; 19846 final int l = mScrollX; 19847 final int r = l + mRight - mLeft; 19848 final int t = mScrollY; 19849 final int b = t + mBottom - mTop; 19850 mDefaultFocusHighlight.setBounds(l, t, r, b); 19851 } 19852 mDefaultFocusHighlight.draw(canvas); 19853 } 19854 } 19855 19856 /** 19857 * Return an array of resource IDs of the drawable states representing the 19858 * current state of the view. 19859 * 19860 * @return The current drawable state 19861 * 19862 * @see Drawable#setState(int[]) 19863 * @see #drawableStateChanged() 19864 * @see #onCreateDrawableState(int) 19865 */ 19866 public final int[] getDrawableState() { 19867 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 19868 return mDrawableState; 19869 } else { 19870 mDrawableState = onCreateDrawableState(0); 19871 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 19872 return mDrawableState; 19873 } 19874 } 19875 19876 /** 19877 * Generate the new {@link android.graphics.drawable.Drawable} state for 19878 * this view. This is called by the view 19879 * system when the cached Drawable state is determined to be invalid. To 19880 * retrieve the current state, you should use {@link #getDrawableState}. 19881 * 19882 * @param extraSpace if non-zero, this is the number of extra entries you 19883 * would like in the returned array in which you can place your own 19884 * states. 19885 * 19886 * @return Returns an array holding the current {@link Drawable} state of 19887 * the view. 19888 * 19889 * @see #mergeDrawableStates(int[], int[]) 19890 */ 19891 protected int[] onCreateDrawableState(int extraSpace) { 19892 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 19893 mParent instanceof View) { 19894 return ((View) mParent).onCreateDrawableState(extraSpace); 19895 } 19896 19897 int[] drawableState; 19898 19899 int privateFlags = mPrivateFlags; 19900 19901 int viewStateIndex = 0; 19902 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 19903 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 19904 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 19905 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 19906 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 19907 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 19908 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 19909 ThreadedRenderer.isAvailable()) { 19910 // This is set if HW acceleration is requested, even if the current 19911 // process doesn't allow it. This is just to allow app preview 19912 // windows to better match their app. 19913 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 19914 } 19915 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 19916 19917 final int privateFlags2 = mPrivateFlags2; 19918 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 19919 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 19920 } 19921 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 19922 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 19923 } 19924 19925 drawableState = StateSet.get(viewStateIndex); 19926 19927 //noinspection ConstantIfStatement 19928 if (false) { 19929 Log.i("View", "drawableStateIndex=" + viewStateIndex); 19930 Log.i("View", toString() 19931 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 19932 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 19933 + " fo=" + hasFocus() 19934 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 19935 + " wf=" + hasWindowFocus() 19936 + ": " + Arrays.toString(drawableState)); 19937 } 19938 19939 if (extraSpace == 0) { 19940 return drawableState; 19941 } 19942 19943 final int[] fullState; 19944 if (drawableState != null) { 19945 fullState = new int[drawableState.length + extraSpace]; 19946 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 19947 } else { 19948 fullState = new int[extraSpace]; 19949 } 19950 19951 return fullState; 19952 } 19953 19954 /** 19955 * Merge your own state values in <var>additionalState</var> into the base 19956 * state values <var>baseState</var> that were returned by 19957 * {@link #onCreateDrawableState(int)}. 19958 * 19959 * @param baseState The base state values returned by 19960 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 19961 * own additional state values. 19962 * 19963 * @param additionalState The additional state values you would like 19964 * added to <var>baseState</var>; this array is not modified. 19965 * 19966 * @return As a convenience, the <var>baseState</var> array you originally 19967 * passed into the function is returned. 19968 * 19969 * @see #onCreateDrawableState(int) 19970 */ 19971 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 19972 final int N = baseState.length; 19973 int i = N - 1; 19974 while (i >= 0 && baseState[i] == 0) { 19975 i--; 19976 } 19977 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 19978 return baseState; 19979 } 19980 19981 /** 19982 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 19983 * on all Drawable objects associated with this view. 19984 * <p> 19985 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 19986 * attached to this view. 19987 */ 19988 @CallSuper 19989 public void jumpDrawablesToCurrentState() { 19990 if (mBackground != null) { 19991 mBackground.jumpToCurrentState(); 19992 } 19993 if (mStateListAnimator != null) { 19994 mStateListAnimator.jumpToCurrentState(); 19995 } 19996 if (mDefaultFocusHighlight != null) { 19997 mDefaultFocusHighlight.jumpToCurrentState(); 19998 } 19999 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 20000 mForegroundInfo.mDrawable.jumpToCurrentState(); 20001 } 20002 } 20003 20004 /** 20005 * Sets the background color for this view. 20006 * @param color the color of the background 20007 */ 20008 @RemotableViewMethod 20009 public void setBackgroundColor(@ColorInt int color) { 20010 if (mBackground instanceof ColorDrawable) { 20011 ((ColorDrawable) mBackground.mutate()).setColor(color); 20012 computeOpaqueFlags(); 20013 mBackgroundResource = 0; 20014 } else { 20015 setBackground(new ColorDrawable(color)); 20016 } 20017 } 20018 20019 /** 20020 * Set the background to a given resource. The resource should refer to 20021 * a Drawable object or 0 to remove the background. 20022 * @param resid The identifier of the resource. 20023 * 20024 * @attr ref android.R.styleable#View_background 20025 */ 20026 @RemotableViewMethod 20027 public void setBackgroundResource(@DrawableRes int resid) { 20028 if (resid != 0 && resid == mBackgroundResource) { 20029 return; 20030 } 20031 20032 Drawable d = null; 20033 if (resid != 0) { 20034 d = mContext.getDrawable(resid); 20035 } 20036 setBackground(d); 20037 20038 mBackgroundResource = resid; 20039 } 20040 20041 /** 20042 * Set the background to a given Drawable, or remove the background. If the 20043 * background has padding, this View's padding is set to the background's 20044 * padding. However, when a background is removed, this View's padding isn't 20045 * touched. If setting the padding is desired, please use 20046 * {@link #setPadding(int, int, int, int)}. 20047 * 20048 * @param background The Drawable to use as the background, or null to remove the 20049 * background 20050 */ 20051 public void setBackground(Drawable background) { 20052 //noinspection deprecation 20053 setBackgroundDrawable(background); 20054 } 20055 20056 /** 20057 * @deprecated use {@link #setBackground(Drawable)} instead 20058 */ 20059 @Deprecated 20060 public void setBackgroundDrawable(Drawable background) { 20061 computeOpaqueFlags(); 20062 20063 if (background == mBackground) { 20064 return; 20065 } 20066 20067 boolean requestLayout = false; 20068 20069 mBackgroundResource = 0; 20070 20071 /* 20072 * Regardless of whether we're setting a new background or not, we want 20073 * to clear the previous drawable. setVisible first while we still have the callback set. 20074 */ 20075 if (mBackground != null) { 20076 if (isAttachedToWindow()) { 20077 mBackground.setVisible(false, false); 20078 } 20079 mBackground.setCallback(null); 20080 unscheduleDrawable(mBackground); 20081 } 20082 20083 if (background != null) { 20084 Rect padding = sThreadLocal.get(); 20085 if (padding == null) { 20086 padding = new Rect(); 20087 sThreadLocal.set(padding); 20088 } 20089 resetResolvedDrawablesInternal(); 20090 background.setLayoutDirection(getLayoutDirection()); 20091 if (background.getPadding(padding)) { 20092 resetResolvedPaddingInternal(); 20093 switch (background.getLayoutDirection()) { 20094 case LAYOUT_DIRECTION_RTL: 20095 mUserPaddingLeftInitial = padding.right; 20096 mUserPaddingRightInitial = padding.left; 20097 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 20098 break; 20099 case LAYOUT_DIRECTION_LTR: 20100 default: 20101 mUserPaddingLeftInitial = padding.left; 20102 mUserPaddingRightInitial = padding.right; 20103 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 20104 } 20105 mLeftPaddingDefined = false; 20106 mRightPaddingDefined = false; 20107 } 20108 20109 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 20110 // if it has a different minimum size, we should layout again 20111 if (mBackground == null 20112 || mBackground.getMinimumHeight() != background.getMinimumHeight() 20113 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 20114 requestLayout = true; 20115 } 20116 20117 // Set mBackground before we set this as the callback and start making other 20118 // background drawable state change calls. In particular, the setVisible call below 20119 // can result in drawables attempting to start animations or otherwise invalidate, 20120 // which requires the view set as the callback (us) to recognize the drawable as 20121 // belonging to it as per verifyDrawable. 20122 mBackground = background; 20123 if (background.isStateful()) { 20124 background.setState(getDrawableState()); 20125 } 20126 if (isAttachedToWindow()) { 20127 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 20128 } 20129 20130 applyBackgroundTint(); 20131 20132 // Set callback last, since the view may still be initializing. 20133 background.setCallback(this); 20134 20135 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 20136 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 20137 requestLayout = true; 20138 } 20139 } else { 20140 /* Remove the background */ 20141 mBackground = null; 20142 if ((mViewFlags & WILL_NOT_DRAW) != 0 20143 && (mDefaultFocusHighlight == null) 20144 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 20145 mPrivateFlags |= PFLAG_SKIP_DRAW; 20146 } 20147 20148 /* 20149 * When the background is set, we try to apply its padding to this 20150 * View. When the background is removed, we don't touch this View's 20151 * padding. This is noted in the Javadocs. Hence, we don't need to 20152 * requestLayout(), the invalidate() below is sufficient. 20153 */ 20154 20155 // The old background's minimum size could have affected this 20156 // View's layout, so let's requestLayout 20157 requestLayout = true; 20158 } 20159 20160 computeOpaqueFlags(); 20161 20162 if (requestLayout) { 20163 requestLayout(); 20164 } 20165 20166 mBackgroundSizeChanged = true; 20167 invalidate(true); 20168 invalidateOutline(); 20169 } 20170 20171 /** 20172 * Gets the background drawable 20173 * 20174 * @return The drawable used as the background for this view, if any. 20175 * 20176 * @see #setBackground(Drawable) 20177 * 20178 * @attr ref android.R.styleable#View_background 20179 */ 20180 public Drawable getBackground() { 20181 return mBackground; 20182 } 20183 20184 /** 20185 * Applies a tint to the background drawable. Does not modify the current tint 20186 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20187 * <p> 20188 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 20189 * mutate the drawable and apply the specified tint and tint mode using 20190 * {@link Drawable#setTintList(ColorStateList)}. 20191 * 20192 * @param tint the tint to apply, may be {@code null} to clear tint 20193 * 20194 * @attr ref android.R.styleable#View_backgroundTint 20195 * @see #getBackgroundTintList() 20196 * @see Drawable#setTintList(ColorStateList) 20197 */ 20198 public void setBackgroundTintList(@Nullable ColorStateList tint) { 20199 if (mBackgroundTint == null) { 20200 mBackgroundTint = new TintInfo(); 20201 } 20202 mBackgroundTint.mTintList = tint; 20203 mBackgroundTint.mHasTintList = true; 20204 20205 applyBackgroundTint(); 20206 } 20207 20208 /** 20209 * Return the tint applied to the background drawable, if specified. 20210 * 20211 * @return the tint applied to the background drawable 20212 * @attr ref android.R.styleable#View_backgroundTint 20213 * @see #setBackgroundTintList(ColorStateList) 20214 */ 20215 @Nullable 20216 public ColorStateList getBackgroundTintList() { 20217 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 20218 } 20219 20220 /** 20221 * Specifies the blending mode used to apply the tint specified by 20222 * {@link #setBackgroundTintList(ColorStateList)}} to the background 20223 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20224 * 20225 * @param tintMode the blending mode used to apply the tint, may be 20226 * {@code null} to clear tint 20227 * @attr ref android.R.styleable#View_backgroundTintMode 20228 * @see #getBackgroundTintMode() 20229 * @see Drawable#setTintMode(PorterDuff.Mode) 20230 */ 20231 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20232 if (mBackgroundTint == null) { 20233 mBackgroundTint = new TintInfo(); 20234 } 20235 mBackgroundTint.mTintMode = tintMode; 20236 mBackgroundTint.mHasTintMode = true; 20237 20238 applyBackgroundTint(); 20239 } 20240 20241 /** 20242 * Return the blending mode used to apply the tint to the background 20243 * drawable, if specified. 20244 * 20245 * @return the blending mode used to apply the tint to the background 20246 * drawable 20247 * @attr ref android.R.styleable#View_backgroundTintMode 20248 * @see #setBackgroundTintMode(PorterDuff.Mode) 20249 */ 20250 @Nullable 20251 public PorterDuff.Mode getBackgroundTintMode() { 20252 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 20253 } 20254 20255 private void applyBackgroundTint() { 20256 if (mBackground != null && mBackgroundTint != null) { 20257 final TintInfo tintInfo = mBackgroundTint; 20258 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20259 mBackground = mBackground.mutate(); 20260 20261 if (tintInfo.mHasTintList) { 20262 mBackground.setTintList(tintInfo.mTintList); 20263 } 20264 20265 if (tintInfo.mHasTintMode) { 20266 mBackground.setTintMode(tintInfo.mTintMode); 20267 } 20268 20269 // The drawable (or one of its children) may not have been 20270 // stateful before applying the tint, so let's try again. 20271 if (mBackground.isStateful()) { 20272 mBackground.setState(getDrawableState()); 20273 } 20274 } 20275 } 20276 } 20277 20278 /** 20279 * Returns the drawable used as the foreground of this View. The 20280 * foreground drawable, if non-null, is always drawn on top of the view's content. 20281 * 20282 * @return a Drawable or null if no foreground was set 20283 * 20284 * @see #onDrawForeground(Canvas) 20285 */ 20286 public Drawable getForeground() { 20287 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20288 } 20289 20290 /** 20291 * Supply a Drawable that is to be rendered on top of all of the content in the view. 20292 * 20293 * @param foreground the Drawable to be drawn on top of the children 20294 * 20295 * @attr ref android.R.styleable#View_foreground 20296 */ 20297 public void setForeground(Drawable foreground) { 20298 if (mForegroundInfo == null) { 20299 if (foreground == null) { 20300 // Nothing to do. 20301 return; 20302 } 20303 mForegroundInfo = new ForegroundInfo(); 20304 } 20305 20306 if (foreground == mForegroundInfo.mDrawable) { 20307 // Nothing to do 20308 return; 20309 } 20310 20311 if (mForegroundInfo.mDrawable != null) { 20312 if (isAttachedToWindow()) { 20313 mForegroundInfo.mDrawable.setVisible(false, false); 20314 } 20315 mForegroundInfo.mDrawable.setCallback(null); 20316 unscheduleDrawable(mForegroundInfo.mDrawable); 20317 } 20318 20319 mForegroundInfo.mDrawable = foreground; 20320 mForegroundInfo.mBoundsChanged = true; 20321 if (foreground != null) { 20322 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 20323 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 20324 } 20325 foreground.setLayoutDirection(getLayoutDirection()); 20326 if (foreground.isStateful()) { 20327 foreground.setState(getDrawableState()); 20328 } 20329 applyForegroundTint(); 20330 if (isAttachedToWindow()) { 20331 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 20332 } 20333 // Set callback last, since the view may still be initializing. 20334 foreground.setCallback(this); 20335 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 20336 && (mDefaultFocusHighlight == null)) { 20337 mPrivateFlags |= PFLAG_SKIP_DRAW; 20338 } 20339 requestLayout(); 20340 invalidate(); 20341 } 20342 20343 /** 20344 * Magic bit used to support features of framework-internal window decor implementation details. 20345 * This used to live exclusively in FrameLayout. 20346 * 20347 * @return true if the foreground should draw inside the padding region or false 20348 * if it should draw inset by the view's padding 20349 * @hide internal use only; only used by FrameLayout and internal screen layouts. 20350 */ 20351 public boolean isForegroundInsidePadding() { 20352 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 20353 } 20354 20355 /** 20356 * Describes how the foreground is positioned. 20357 * 20358 * @return foreground gravity. 20359 * 20360 * @see #setForegroundGravity(int) 20361 * 20362 * @attr ref android.R.styleable#View_foregroundGravity 20363 */ 20364 public int getForegroundGravity() { 20365 return mForegroundInfo != null ? mForegroundInfo.mGravity 20366 : Gravity.START | Gravity.TOP; 20367 } 20368 20369 /** 20370 * Describes how the foreground is positioned. Defaults to START and TOP. 20371 * 20372 * @param gravity see {@link android.view.Gravity} 20373 * 20374 * @see #getForegroundGravity() 20375 * 20376 * @attr ref android.R.styleable#View_foregroundGravity 20377 */ 20378 public void setForegroundGravity(int gravity) { 20379 if (mForegroundInfo == null) { 20380 mForegroundInfo = new ForegroundInfo(); 20381 } 20382 20383 if (mForegroundInfo.mGravity != gravity) { 20384 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 20385 gravity |= Gravity.START; 20386 } 20387 20388 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 20389 gravity |= Gravity.TOP; 20390 } 20391 20392 mForegroundInfo.mGravity = gravity; 20393 requestLayout(); 20394 } 20395 } 20396 20397 /** 20398 * Applies a tint to the foreground drawable. Does not modify the current tint 20399 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20400 * <p> 20401 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 20402 * mutate the drawable and apply the specified tint and tint mode using 20403 * {@link Drawable#setTintList(ColorStateList)}. 20404 * 20405 * @param tint the tint to apply, may be {@code null} to clear tint 20406 * 20407 * @attr ref android.R.styleable#View_foregroundTint 20408 * @see #getForegroundTintList() 20409 * @see Drawable#setTintList(ColorStateList) 20410 */ 20411 public void setForegroundTintList(@Nullable ColorStateList tint) { 20412 if (mForegroundInfo == null) { 20413 mForegroundInfo = new ForegroundInfo(); 20414 } 20415 if (mForegroundInfo.mTintInfo == null) { 20416 mForegroundInfo.mTintInfo = new TintInfo(); 20417 } 20418 mForegroundInfo.mTintInfo.mTintList = tint; 20419 mForegroundInfo.mTintInfo.mHasTintList = true; 20420 20421 applyForegroundTint(); 20422 } 20423 20424 /** 20425 * Return the tint applied to the foreground drawable, if specified. 20426 * 20427 * @return the tint applied to the foreground drawable 20428 * @attr ref android.R.styleable#View_foregroundTint 20429 * @see #setForegroundTintList(ColorStateList) 20430 */ 20431 @Nullable 20432 public ColorStateList getForegroundTintList() { 20433 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20434 ? mForegroundInfo.mTintInfo.mTintList : null; 20435 } 20436 20437 /** 20438 * Specifies the blending mode used to apply the tint specified by 20439 * {@link #setForegroundTintList(ColorStateList)}} to the background 20440 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20441 * 20442 * @param tintMode the blending mode used to apply the tint, may be 20443 * {@code null} to clear tint 20444 * @attr ref android.R.styleable#View_foregroundTintMode 20445 * @see #getForegroundTintMode() 20446 * @see Drawable#setTintMode(PorterDuff.Mode) 20447 */ 20448 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20449 if (mForegroundInfo == null) { 20450 mForegroundInfo = new ForegroundInfo(); 20451 } 20452 if (mForegroundInfo.mTintInfo == null) { 20453 mForegroundInfo.mTintInfo = new TintInfo(); 20454 } 20455 mForegroundInfo.mTintInfo.mTintMode = tintMode; 20456 mForegroundInfo.mTintInfo.mHasTintMode = true; 20457 20458 applyForegroundTint(); 20459 } 20460 20461 /** 20462 * Return the blending mode used to apply the tint to the foreground 20463 * drawable, if specified. 20464 * 20465 * @return the blending mode used to apply the tint to the foreground 20466 * drawable 20467 * @attr ref android.R.styleable#View_foregroundTintMode 20468 * @see #setForegroundTintMode(PorterDuff.Mode) 20469 */ 20470 @Nullable 20471 public PorterDuff.Mode getForegroundTintMode() { 20472 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20473 ? mForegroundInfo.mTintInfo.mTintMode : null; 20474 } 20475 20476 private void applyForegroundTint() { 20477 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20478 && mForegroundInfo.mTintInfo != null) { 20479 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 20480 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20481 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 20482 20483 if (tintInfo.mHasTintList) { 20484 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 20485 } 20486 20487 if (tintInfo.mHasTintMode) { 20488 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 20489 } 20490 20491 // The drawable (or one of its children) may not have been 20492 // stateful before applying the tint, so let's try again. 20493 if (mForegroundInfo.mDrawable.isStateful()) { 20494 mForegroundInfo.mDrawable.setState(getDrawableState()); 20495 } 20496 } 20497 } 20498 } 20499 20500 /** 20501 * Get the drawable to be overlayed when a view is autofilled 20502 * 20503 * @return The drawable 20504 * 20505 * @throws IllegalStateException if the drawable could not be found. 20506 */ 20507 @Nullable private Drawable getAutofilledDrawable() { 20508 // Lazily load the isAutofilled drawable. 20509 if (mAttachInfo.mAutofilledDrawable == null) { 20510 Context rootContext = getRootView().getContext(); 20511 TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR); 20512 int attributeResourceId = a.getResourceId(0, 0); 20513 mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId); 20514 a.recycle(); 20515 } 20516 20517 return mAttachInfo.mAutofilledDrawable; 20518 } 20519 20520 /** 20521 * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled. 20522 * 20523 * @param canvas The canvas to draw on 20524 */ 20525 private void drawAutofilledHighlight(@NonNull Canvas canvas) { 20526 if (isAutofilled()) { 20527 Drawable autofilledHighlight = getAutofilledDrawable(); 20528 20529 if (autofilledHighlight != null) { 20530 autofilledHighlight.setBounds(0, 0, getWidth(), getHeight()); 20531 autofilledHighlight.draw(canvas); 20532 } 20533 } 20534 } 20535 20536 /** 20537 * Draw any foreground content for this view. 20538 * 20539 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 20540 * drawable or other view-specific decorations. The foreground is drawn on top of the 20541 * primary view content.</p> 20542 * 20543 * @param canvas canvas to draw into 20544 */ 20545 public void onDrawForeground(Canvas canvas) { 20546 onDrawScrollIndicators(canvas); 20547 onDrawScrollBars(canvas); 20548 20549 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20550 if (foreground != null) { 20551 if (mForegroundInfo.mBoundsChanged) { 20552 mForegroundInfo.mBoundsChanged = false; 20553 final Rect selfBounds = mForegroundInfo.mSelfBounds; 20554 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 20555 20556 if (mForegroundInfo.mInsidePadding) { 20557 selfBounds.set(0, 0, getWidth(), getHeight()); 20558 } else { 20559 selfBounds.set(getPaddingLeft(), getPaddingTop(), 20560 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 20561 } 20562 20563 final int ld = getLayoutDirection(); 20564 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 20565 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 20566 foreground.setBounds(overlayBounds); 20567 } 20568 20569 foreground.draw(canvas); 20570 } 20571 } 20572 20573 /** 20574 * Sets the padding. The view may add on the space required to display 20575 * the scrollbars, depending on the style and visibility of the scrollbars. 20576 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 20577 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 20578 * from the values set in this call. 20579 * 20580 * @attr ref android.R.styleable#View_padding 20581 * @attr ref android.R.styleable#View_paddingBottom 20582 * @attr ref android.R.styleable#View_paddingLeft 20583 * @attr ref android.R.styleable#View_paddingRight 20584 * @attr ref android.R.styleable#View_paddingTop 20585 * @param left the left padding in pixels 20586 * @param top the top padding in pixels 20587 * @param right the right padding in pixels 20588 * @param bottom the bottom padding in pixels 20589 */ 20590 public void setPadding(int left, int top, int right, int bottom) { 20591 resetResolvedPaddingInternal(); 20592 20593 mUserPaddingStart = UNDEFINED_PADDING; 20594 mUserPaddingEnd = UNDEFINED_PADDING; 20595 20596 mUserPaddingLeftInitial = left; 20597 mUserPaddingRightInitial = right; 20598 20599 mLeftPaddingDefined = true; 20600 mRightPaddingDefined = true; 20601 20602 internalSetPadding(left, top, right, bottom); 20603 } 20604 20605 /** 20606 * @hide 20607 */ 20608 protected void internalSetPadding(int left, int top, int right, int bottom) { 20609 mUserPaddingLeft = left; 20610 mUserPaddingRight = right; 20611 mUserPaddingBottom = bottom; 20612 20613 final int viewFlags = mViewFlags; 20614 boolean changed = false; 20615 20616 // Common case is there are no scroll bars. 20617 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 20618 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 20619 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 20620 ? 0 : getVerticalScrollbarWidth(); 20621 switch (mVerticalScrollbarPosition) { 20622 case SCROLLBAR_POSITION_DEFAULT: 20623 if (isLayoutRtl()) { 20624 left += offset; 20625 } else { 20626 right += offset; 20627 } 20628 break; 20629 case SCROLLBAR_POSITION_RIGHT: 20630 right += offset; 20631 break; 20632 case SCROLLBAR_POSITION_LEFT: 20633 left += offset; 20634 break; 20635 } 20636 } 20637 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 20638 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 20639 ? 0 : getHorizontalScrollbarHeight(); 20640 } 20641 } 20642 20643 if (mPaddingLeft != left) { 20644 changed = true; 20645 mPaddingLeft = left; 20646 } 20647 if (mPaddingTop != top) { 20648 changed = true; 20649 mPaddingTop = top; 20650 } 20651 if (mPaddingRight != right) { 20652 changed = true; 20653 mPaddingRight = right; 20654 } 20655 if (mPaddingBottom != bottom) { 20656 changed = true; 20657 mPaddingBottom = bottom; 20658 } 20659 20660 if (changed) { 20661 requestLayout(); 20662 invalidateOutline(); 20663 } 20664 } 20665 20666 /** 20667 * Sets the relative padding. The view may add on the space required to display 20668 * the scrollbars, depending on the style and visibility of the scrollbars. 20669 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 20670 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 20671 * from the values set in this call. 20672 * 20673 * @attr ref android.R.styleable#View_padding 20674 * @attr ref android.R.styleable#View_paddingBottom 20675 * @attr ref android.R.styleable#View_paddingStart 20676 * @attr ref android.R.styleable#View_paddingEnd 20677 * @attr ref android.R.styleable#View_paddingTop 20678 * @param start the start padding in pixels 20679 * @param top the top padding in pixels 20680 * @param end the end padding in pixels 20681 * @param bottom the bottom padding in pixels 20682 */ 20683 public void setPaddingRelative(int start, int top, int end, int bottom) { 20684 resetResolvedPaddingInternal(); 20685 20686 mUserPaddingStart = start; 20687 mUserPaddingEnd = end; 20688 mLeftPaddingDefined = true; 20689 mRightPaddingDefined = true; 20690 20691 switch(getLayoutDirection()) { 20692 case LAYOUT_DIRECTION_RTL: 20693 mUserPaddingLeftInitial = end; 20694 mUserPaddingRightInitial = start; 20695 internalSetPadding(end, top, start, bottom); 20696 break; 20697 case LAYOUT_DIRECTION_LTR: 20698 default: 20699 mUserPaddingLeftInitial = start; 20700 mUserPaddingRightInitial = end; 20701 internalSetPadding(start, top, end, bottom); 20702 } 20703 } 20704 20705 /** 20706 * Returns the top padding of this view. 20707 * 20708 * @return the top padding in pixels 20709 */ 20710 public int getPaddingTop() { 20711 return mPaddingTop; 20712 } 20713 20714 /** 20715 * Returns the bottom padding of this view. If there are inset and enabled 20716 * scrollbars, this value may include the space required to display the 20717 * scrollbars as well. 20718 * 20719 * @return the bottom padding in pixels 20720 */ 20721 public int getPaddingBottom() { 20722 return mPaddingBottom; 20723 } 20724 20725 /** 20726 * Returns the left padding of this view. If there are inset and enabled 20727 * scrollbars, this value may include the space required to display the 20728 * scrollbars as well. 20729 * 20730 * @return the left padding in pixels 20731 */ 20732 public int getPaddingLeft() { 20733 if (!isPaddingResolved()) { 20734 resolvePadding(); 20735 } 20736 return mPaddingLeft; 20737 } 20738 20739 /** 20740 * Returns the start padding of this view depending on its resolved layout direction. 20741 * If there are inset and enabled scrollbars, this value may include the space 20742 * required to display the scrollbars as well. 20743 * 20744 * @return the start padding in pixels 20745 */ 20746 public int getPaddingStart() { 20747 if (!isPaddingResolved()) { 20748 resolvePadding(); 20749 } 20750 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20751 mPaddingRight : mPaddingLeft; 20752 } 20753 20754 /** 20755 * Returns the right padding of this view. If there are inset and enabled 20756 * scrollbars, this value may include the space required to display the 20757 * scrollbars as well. 20758 * 20759 * @return the right padding in pixels 20760 */ 20761 public int getPaddingRight() { 20762 if (!isPaddingResolved()) { 20763 resolvePadding(); 20764 } 20765 return mPaddingRight; 20766 } 20767 20768 /** 20769 * Returns the end padding of this view depending on its resolved layout direction. 20770 * If there are inset and enabled scrollbars, this value may include the space 20771 * required to display the scrollbars as well. 20772 * 20773 * @return the end padding in pixels 20774 */ 20775 public int getPaddingEnd() { 20776 if (!isPaddingResolved()) { 20777 resolvePadding(); 20778 } 20779 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20780 mPaddingLeft : mPaddingRight; 20781 } 20782 20783 /** 20784 * Return if the padding has been set through relative values 20785 * {@link #setPaddingRelative(int, int, int, int)} or through 20786 * @attr ref android.R.styleable#View_paddingStart or 20787 * @attr ref android.R.styleable#View_paddingEnd 20788 * 20789 * @return true if the padding is relative or false if it is not. 20790 */ 20791 public boolean isPaddingRelative() { 20792 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 20793 } 20794 20795 Insets computeOpticalInsets() { 20796 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 20797 } 20798 20799 /** 20800 * @hide 20801 */ 20802 public void resetPaddingToInitialValues() { 20803 if (isRtlCompatibilityMode()) { 20804 mPaddingLeft = mUserPaddingLeftInitial; 20805 mPaddingRight = mUserPaddingRightInitial; 20806 return; 20807 } 20808 if (isLayoutRtl()) { 20809 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 20810 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 20811 } else { 20812 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 20813 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 20814 } 20815 } 20816 20817 /** 20818 * @hide 20819 */ 20820 public Insets getOpticalInsets() { 20821 if (mLayoutInsets == null) { 20822 mLayoutInsets = computeOpticalInsets(); 20823 } 20824 return mLayoutInsets; 20825 } 20826 20827 /** 20828 * Set this view's optical insets. 20829 * 20830 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 20831 * property. Views that compute their own optical insets should call it as part of measurement. 20832 * This method does not request layout. If you are setting optical insets outside of 20833 * measure/layout itself you will want to call requestLayout() yourself. 20834 * </p> 20835 * @hide 20836 */ 20837 public void setOpticalInsets(Insets insets) { 20838 mLayoutInsets = insets; 20839 } 20840 20841 /** 20842 * Changes the selection state of this view. A view can be selected or not. 20843 * Note that selection is not the same as focus. Views are typically 20844 * selected in the context of an AdapterView like ListView or GridView; 20845 * the selected view is the view that is highlighted. 20846 * 20847 * @param selected true if the view must be selected, false otherwise 20848 */ 20849 public void setSelected(boolean selected) { 20850 //noinspection DoubleNegation 20851 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 20852 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 20853 if (!selected) resetPressedState(); 20854 invalidate(true); 20855 refreshDrawableState(); 20856 dispatchSetSelected(selected); 20857 if (selected) { 20858 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 20859 } else { 20860 notifyViewAccessibilityStateChangedIfNeeded( 20861 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 20862 } 20863 } 20864 } 20865 20866 /** 20867 * Dispatch setSelected to all of this View's children. 20868 * 20869 * @see #setSelected(boolean) 20870 * 20871 * @param selected The new selected state 20872 */ 20873 protected void dispatchSetSelected(boolean selected) { 20874 } 20875 20876 /** 20877 * Indicates the selection state of this view. 20878 * 20879 * @return true if the view is selected, false otherwise 20880 */ 20881 @ViewDebug.ExportedProperty 20882 public boolean isSelected() { 20883 return (mPrivateFlags & PFLAG_SELECTED) != 0; 20884 } 20885 20886 /** 20887 * Changes the activated state of this view. A view can be activated or not. 20888 * Note that activation is not the same as selection. Selection is 20889 * a transient property, representing the view (hierarchy) the user is 20890 * currently interacting with. Activation is a longer-term state that the 20891 * user can move views in and out of. For example, in a list view with 20892 * single or multiple selection enabled, the views in the current selection 20893 * set are activated. (Um, yeah, we are deeply sorry about the terminology 20894 * here.) The activated state is propagated down to children of the view it 20895 * is set on. 20896 * 20897 * @param activated true if the view must be activated, false otherwise 20898 */ 20899 public void setActivated(boolean activated) { 20900 //noinspection DoubleNegation 20901 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 20902 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 20903 invalidate(true); 20904 refreshDrawableState(); 20905 dispatchSetActivated(activated); 20906 } 20907 } 20908 20909 /** 20910 * Dispatch setActivated to all of this View's children. 20911 * 20912 * @see #setActivated(boolean) 20913 * 20914 * @param activated The new activated state 20915 */ 20916 protected void dispatchSetActivated(boolean activated) { 20917 } 20918 20919 /** 20920 * Indicates the activation state of this view. 20921 * 20922 * @return true if the view is activated, false otherwise 20923 */ 20924 @ViewDebug.ExportedProperty 20925 public boolean isActivated() { 20926 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 20927 } 20928 20929 /** 20930 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 20931 * observer can be used to get notifications when global events, like 20932 * layout, happen. 20933 * 20934 * The returned ViewTreeObserver observer is not guaranteed to remain 20935 * valid for the lifetime of this View. If the caller of this method keeps 20936 * a long-lived reference to ViewTreeObserver, it should always check for 20937 * the return value of {@link ViewTreeObserver#isAlive()}. 20938 * 20939 * @return The ViewTreeObserver for this view's hierarchy. 20940 */ 20941 public ViewTreeObserver getViewTreeObserver() { 20942 if (mAttachInfo != null) { 20943 return mAttachInfo.mTreeObserver; 20944 } 20945 if (mFloatingTreeObserver == null) { 20946 mFloatingTreeObserver = new ViewTreeObserver(mContext); 20947 } 20948 return mFloatingTreeObserver; 20949 } 20950 20951 /** 20952 * <p>Finds the topmost view in the current view hierarchy.</p> 20953 * 20954 * @return the topmost view containing this view 20955 */ 20956 public View getRootView() { 20957 if (mAttachInfo != null) { 20958 final View v = mAttachInfo.mRootView; 20959 if (v != null) { 20960 return v; 20961 } 20962 } 20963 20964 View parent = this; 20965 20966 while (parent.mParent != null && parent.mParent instanceof View) { 20967 parent = (View) parent.mParent; 20968 } 20969 20970 return parent; 20971 } 20972 20973 /** 20974 * Transforms a motion event from view-local coordinates to on-screen 20975 * coordinates. 20976 * 20977 * @param ev the view-local motion event 20978 * @return false if the transformation could not be applied 20979 * @hide 20980 */ 20981 public boolean toGlobalMotionEvent(MotionEvent ev) { 20982 final AttachInfo info = mAttachInfo; 20983 if (info == null) { 20984 return false; 20985 } 20986 20987 final Matrix m = info.mTmpMatrix; 20988 m.set(Matrix.IDENTITY_MATRIX); 20989 transformMatrixToGlobal(m); 20990 ev.transform(m); 20991 return true; 20992 } 20993 20994 /** 20995 * Transforms a motion event from on-screen coordinates to view-local 20996 * coordinates. 20997 * 20998 * @param ev the on-screen motion event 20999 * @return false if the transformation could not be applied 21000 * @hide 21001 */ 21002 public boolean toLocalMotionEvent(MotionEvent ev) { 21003 final AttachInfo info = mAttachInfo; 21004 if (info == null) { 21005 return false; 21006 } 21007 21008 final Matrix m = info.mTmpMatrix; 21009 m.set(Matrix.IDENTITY_MATRIX); 21010 transformMatrixToLocal(m); 21011 ev.transform(m); 21012 return true; 21013 } 21014 21015 /** 21016 * Modifies the input matrix such that it maps view-local coordinates to 21017 * on-screen coordinates. 21018 * 21019 * @param m input matrix to modify 21020 * @hide 21021 */ 21022 public void transformMatrixToGlobal(Matrix m) { 21023 final ViewParent parent = mParent; 21024 if (parent instanceof View) { 21025 final View vp = (View) parent; 21026 vp.transformMatrixToGlobal(m); 21027 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 21028 } else if (parent instanceof ViewRootImpl) { 21029 final ViewRootImpl vr = (ViewRootImpl) parent; 21030 vr.transformMatrixToGlobal(m); 21031 m.preTranslate(0, -vr.mCurScrollY); 21032 } 21033 21034 m.preTranslate(mLeft, mTop); 21035 21036 if (!hasIdentityMatrix()) { 21037 m.preConcat(getMatrix()); 21038 } 21039 } 21040 21041 /** 21042 * Modifies the input matrix such that it maps on-screen coordinates to 21043 * view-local coordinates. 21044 * 21045 * @param m input matrix to modify 21046 * @hide 21047 */ 21048 public void transformMatrixToLocal(Matrix m) { 21049 final ViewParent parent = mParent; 21050 if (parent instanceof View) { 21051 final View vp = (View) parent; 21052 vp.transformMatrixToLocal(m); 21053 m.postTranslate(vp.mScrollX, vp.mScrollY); 21054 } else if (parent instanceof ViewRootImpl) { 21055 final ViewRootImpl vr = (ViewRootImpl) parent; 21056 vr.transformMatrixToLocal(m); 21057 m.postTranslate(0, vr.mCurScrollY); 21058 } 21059 21060 m.postTranslate(-mLeft, -mTop); 21061 21062 if (!hasIdentityMatrix()) { 21063 m.postConcat(getInverseMatrix()); 21064 } 21065 } 21066 21067 /** 21068 * @hide 21069 */ 21070 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 21071 @ViewDebug.IntToString(from = 0, to = "x"), 21072 @ViewDebug.IntToString(from = 1, to = "y") 21073 }) 21074 public int[] getLocationOnScreen() { 21075 int[] location = new int[2]; 21076 getLocationOnScreen(location); 21077 return location; 21078 } 21079 21080 /** 21081 * <p>Computes the coordinates of this view on the screen. The argument 21082 * must be an array of two integers. After the method returns, the array 21083 * contains the x and y location in that order.</p> 21084 * 21085 * @param outLocation an array of two integers in which to hold the coordinates 21086 */ 21087 public void getLocationOnScreen(@Size(2) int[] outLocation) { 21088 getLocationInWindow(outLocation); 21089 21090 final AttachInfo info = mAttachInfo; 21091 if (info != null) { 21092 outLocation[0] += info.mWindowLeft; 21093 outLocation[1] += info.mWindowTop; 21094 } 21095 } 21096 21097 /** 21098 * <p>Computes the coordinates of this view in its window. The argument 21099 * must be an array of two integers. After the method returns, the array 21100 * contains the x and y location in that order.</p> 21101 * 21102 * @param outLocation an array of two integers in which to hold the coordinates 21103 */ 21104 public void getLocationInWindow(@Size(2) int[] outLocation) { 21105 if (outLocation == null || outLocation.length < 2) { 21106 throw new IllegalArgumentException("outLocation must be an array of two integers"); 21107 } 21108 21109 outLocation[0] = 0; 21110 outLocation[1] = 0; 21111 21112 transformFromViewToWindowSpace(outLocation); 21113 } 21114 21115 /** @hide */ 21116 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 21117 if (inOutLocation == null || inOutLocation.length < 2) { 21118 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 21119 } 21120 21121 if (mAttachInfo == null) { 21122 // When the view is not attached to a window, this method does not make sense 21123 inOutLocation[0] = inOutLocation[1] = 0; 21124 return; 21125 } 21126 21127 float position[] = mAttachInfo.mTmpTransformLocation; 21128 position[0] = inOutLocation[0]; 21129 position[1] = inOutLocation[1]; 21130 21131 if (!hasIdentityMatrix()) { 21132 getMatrix().mapPoints(position); 21133 } 21134 21135 position[0] += mLeft; 21136 position[1] += mTop; 21137 21138 ViewParent viewParent = mParent; 21139 while (viewParent instanceof View) { 21140 final View view = (View) viewParent; 21141 21142 position[0] -= view.mScrollX; 21143 position[1] -= view.mScrollY; 21144 21145 if (!view.hasIdentityMatrix()) { 21146 view.getMatrix().mapPoints(position); 21147 } 21148 21149 position[0] += view.mLeft; 21150 position[1] += view.mTop; 21151 21152 viewParent = view.mParent; 21153 } 21154 21155 if (viewParent instanceof ViewRootImpl) { 21156 // *cough* 21157 final ViewRootImpl vr = (ViewRootImpl) viewParent; 21158 position[1] -= vr.mCurScrollY; 21159 } 21160 21161 inOutLocation[0] = Math.round(position[0]); 21162 inOutLocation[1] = Math.round(position[1]); 21163 } 21164 21165 /** 21166 * @param id the id of the view to be found 21167 * @return the view of the specified id, null if cannot be found 21168 * @hide 21169 */ 21170 protected <T extends View> T findViewTraversal(@IdRes int id) { 21171 if (id == mID) { 21172 return (T) this; 21173 } 21174 return null; 21175 } 21176 21177 /** 21178 * @param tag the tag of the view to be found 21179 * @return the view of specified tag, null if cannot be found 21180 * @hide 21181 */ 21182 protected <T extends View> T findViewWithTagTraversal(Object tag) { 21183 if (tag != null && tag.equals(mTag)) { 21184 return (T) this; 21185 } 21186 return null; 21187 } 21188 21189 /** 21190 * @param predicate The predicate to evaluate. 21191 * @param childToSkip If not null, ignores this child during the recursive traversal. 21192 * @return The first view that matches the predicate or null. 21193 * @hide 21194 */ 21195 protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate, 21196 View childToSkip) { 21197 if (predicate.test(this)) { 21198 return (T) this; 21199 } 21200 return null; 21201 } 21202 21203 /** 21204 * Finds the first descendant view with the given ID, the view itself if 21205 * the ID matches {@link #getId()}, or {@code null} if the ID is invalid 21206 * (< 0) or there is no matching view in the hierarchy. 21207 * <p> 21208 * <strong>Note:</strong> In most cases -- depending on compiler support -- 21209 * the resulting view is automatically cast to the target class type. If 21210 * the target class type is unconstrained, an explicit cast may be 21211 * necessary. 21212 * 21213 * @param id the ID to search for 21214 * @return a view with given ID if found, or {@code null} otherwise 21215 * @see View#findViewById(int) 21216 */ 21217 @Nullable 21218 public final <T extends View> T findViewById(@IdRes int id) { 21219 if (id == NO_ID) { 21220 return null; 21221 } 21222 return findViewTraversal(id); 21223 } 21224 21225 /** 21226 * Finds a view by its unuque and stable accessibility id. 21227 * 21228 * @param accessibilityId The searched accessibility id. 21229 * @return The found view. 21230 */ 21231 final <T extends View> T findViewByAccessibilityId(int accessibilityId) { 21232 if (accessibilityId < 0) { 21233 return null; 21234 } 21235 T view = findViewByAccessibilityIdTraversal(accessibilityId); 21236 if (view != null) { 21237 return view.includeForAccessibility() ? view : null; 21238 } 21239 return null; 21240 } 21241 21242 /** 21243 * Performs the traversal to find a view by its unuque and stable accessibility id. 21244 * 21245 * <strong>Note:</strong>This method does not stop at the root namespace 21246 * boundary since the user can touch the screen at an arbitrary location 21247 * potentially crossing the root namespace bounday which will send an 21248 * accessibility event to accessibility services and they should be able 21249 * to obtain the event source. Also accessibility ids are guaranteed to be 21250 * unique in the window. 21251 * 21252 * @param accessibilityId The accessibility id. 21253 * @return The found view. 21254 * @hide 21255 */ 21256 public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) { 21257 if (getAccessibilityViewId() == accessibilityId) { 21258 return (T) this; 21259 } 21260 return null; 21261 } 21262 21263 /** 21264 * Look for a child view with the given tag. If this view has the given 21265 * tag, return this view. 21266 * 21267 * @param tag The tag to search for, using "tag.equals(getTag())". 21268 * @return The View that has the given tag in the hierarchy or null 21269 */ 21270 public final <T extends View> T findViewWithTag(Object tag) { 21271 if (tag == null) { 21272 return null; 21273 } 21274 return findViewWithTagTraversal(tag); 21275 } 21276 21277 /** 21278 * Look for a child view that matches the specified predicate. 21279 * If this view matches the predicate, return this view. 21280 * 21281 * @param predicate The predicate to evaluate. 21282 * @return The first view that matches the predicate or null. 21283 * @hide 21284 */ 21285 public final <T extends View> T findViewByPredicate(Predicate<View> predicate) { 21286 return findViewByPredicateTraversal(predicate, null); 21287 } 21288 21289 /** 21290 * Look for a child view that matches the specified predicate, 21291 * starting with the specified view and its descendents and then 21292 * recusively searching the ancestors and siblings of that view 21293 * until this view is reached. 21294 * 21295 * This method is useful in cases where the predicate does not match 21296 * a single unique view (perhaps multiple views use the same id) 21297 * and we are trying to find the view that is "closest" in scope to the 21298 * starting view. 21299 * 21300 * @param start The view to start from. 21301 * @param predicate The predicate to evaluate. 21302 * @return The first view that matches the predicate or null. 21303 * @hide 21304 */ 21305 public final <T extends View> T findViewByPredicateInsideOut( 21306 View start, Predicate<View> predicate) { 21307 View childToSkip = null; 21308 for (;;) { 21309 T view = start.findViewByPredicateTraversal(predicate, childToSkip); 21310 if (view != null || start == this) { 21311 return view; 21312 } 21313 21314 ViewParent parent = start.getParent(); 21315 if (parent == null || !(parent instanceof View)) { 21316 return null; 21317 } 21318 21319 childToSkip = start; 21320 start = (View) parent; 21321 } 21322 } 21323 21324 /** 21325 * Sets the identifier for this view. The identifier does not have to be 21326 * unique in this view's hierarchy. The identifier should be a positive 21327 * number. 21328 * 21329 * @see #NO_ID 21330 * @see #getId() 21331 * @see #findViewById(int) 21332 * 21333 * @param id a number used to identify the view 21334 * 21335 * @attr ref android.R.styleable#View_id 21336 */ 21337 public void setId(@IdRes int id) { 21338 mID = id; 21339 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 21340 mID = generateViewId(); 21341 } 21342 } 21343 21344 /** 21345 * {@hide} 21346 * 21347 * @param isRoot true if the view belongs to the root namespace, false 21348 * otherwise 21349 */ 21350 public void setIsRootNamespace(boolean isRoot) { 21351 if (isRoot) { 21352 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 21353 } else { 21354 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 21355 } 21356 } 21357 21358 /** 21359 * {@hide} 21360 * 21361 * @return true if the view belongs to the root namespace, false otherwise 21362 */ 21363 public boolean isRootNamespace() { 21364 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 21365 } 21366 21367 /** 21368 * Returns this view's identifier. 21369 * 21370 * @return a positive integer used to identify the view or {@link #NO_ID} 21371 * if the view has no ID 21372 * 21373 * @see #setId(int) 21374 * @see #findViewById(int) 21375 * @attr ref android.R.styleable#View_id 21376 */ 21377 @IdRes 21378 @ViewDebug.CapturedViewProperty 21379 public int getId() { 21380 return mID; 21381 } 21382 21383 /** 21384 * Returns this view's tag. 21385 * 21386 * @return the Object stored in this view as a tag, or {@code null} if not 21387 * set 21388 * 21389 * @see #setTag(Object) 21390 * @see #getTag(int) 21391 */ 21392 @ViewDebug.ExportedProperty 21393 public Object getTag() { 21394 return mTag; 21395 } 21396 21397 /** 21398 * Sets the tag associated with this view. A tag can be used to mark 21399 * a view in its hierarchy and does not have to be unique within the 21400 * hierarchy. Tags can also be used to store data within a view without 21401 * resorting to another data structure. 21402 * 21403 * @param tag an Object to tag the view with 21404 * 21405 * @see #getTag() 21406 * @see #setTag(int, Object) 21407 */ 21408 public void setTag(final Object tag) { 21409 mTag = tag; 21410 } 21411 21412 /** 21413 * Returns the tag associated with this view and the specified key. 21414 * 21415 * @param key The key identifying the tag 21416 * 21417 * @return the Object stored in this view as a tag, or {@code null} if not 21418 * set 21419 * 21420 * @see #setTag(int, Object) 21421 * @see #getTag() 21422 */ 21423 public Object getTag(int key) { 21424 if (mKeyedTags != null) return mKeyedTags.get(key); 21425 return null; 21426 } 21427 21428 /** 21429 * Sets a tag associated with this view and a key. A tag can be used 21430 * to mark a view in its hierarchy and does not have to be unique within 21431 * the hierarchy. Tags can also be used to store data within a view 21432 * without resorting to another data structure. 21433 * 21434 * The specified key should be an id declared in the resources of the 21435 * application to ensure it is unique (see the <a 21436 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 21437 * Keys identified as belonging to 21438 * the Android framework or not associated with any package will cause 21439 * an {@link IllegalArgumentException} to be thrown. 21440 * 21441 * @param key The key identifying the tag 21442 * @param tag An Object to tag the view with 21443 * 21444 * @throws IllegalArgumentException If they specified key is not valid 21445 * 21446 * @see #setTag(Object) 21447 * @see #getTag(int) 21448 */ 21449 public void setTag(int key, final Object tag) { 21450 // If the package id is 0x00 or 0x01, it's either an undefined package 21451 // or a framework id 21452 if ((key >>> 24) < 2) { 21453 throw new IllegalArgumentException("The key must be an application-specific " 21454 + "resource id."); 21455 } 21456 21457 setKeyedTag(key, tag); 21458 } 21459 21460 /** 21461 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 21462 * framework id. 21463 * 21464 * @hide 21465 */ 21466 public void setTagInternal(int key, Object tag) { 21467 if ((key >>> 24) != 0x1) { 21468 throw new IllegalArgumentException("The key must be a framework-specific " 21469 + "resource id."); 21470 } 21471 21472 setKeyedTag(key, tag); 21473 } 21474 21475 private void setKeyedTag(int key, Object tag) { 21476 if (mKeyedTags == null) { 21477 mKeyedTags = new SparseArray<Object>(2); 21478 } 21479 21480 mKeyedTags.put(key, tag); 21481 } 21482 21483 /** 21484 * Prints information about this view in the log output, with the tag 21485 * {@link #VIEW_LOG_TAG}. 21486 * 21487 * @hide 21488 */ 21489 public void debug() { 21490 debug(0); 21491 } 21492 21493 /** 21494 * Prints information about this view in the log output, with the tag 21495 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 21496 * indentation defined by the <code>depth</code>. 21497 * 21498 * @param depth the indentation level 21499 * 21500 * @hide 21501 */ 21502 protected void debug(int depth) { 21503 String output = debugIndent(depth - 1); 21504 21505 output += "+ " + this; 21506 int id = getId(); 21507 if (id != -1) { 21508 output += " (id=" + id + ")"; 21509 } 21510 Object tag = getTag(); 21511 if (tag != null) { 21512 output += " (tag=" + tag + ")"; 21513 } 21514 Log.d(VIEW_LOG_TAG, output); 21515 21516 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 21517 output = debugIndent(depth) + " FOCUSED"; 21518 Log.d(VIEW_LOG_TAG, output); 21519 } 21520 21521 output = debugIndent(depth); 21522 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 21523 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 21524 + "} "; 21525 Log.d(VIEW_LOG_TAG, output); 21526 21527 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 21528 || mPaddingBottom != 0) { 21529 output = debugIndent(depth); 21530 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 21531 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 21532 Log.d(VIEW_LOG_TAG, output); 21533 } 21534 21535 output = debugIndent(depth); 21536 output += "mMeasureWidth=" + mMeasuredWidth + 21537 " mMeasureHeight=" + mMeasuredHeight; 21538 Log.d(VIEW_LOG_TAG, output); 21539 21540 output = debugIndent(depth); 21541 if (mLayoutParams == null) { 21542 output += "BAD! no layout params"; 21543 } else { 21544 output = mLayoutParams.debug(output); 21545 } 21546 Log.d(VIEW_LOG_TAG, output); 21547 21548 output = debugIndent(depth); 21549 output += "flags={"; 21550 output += View.printFlags(mViewFlags); 21551 output += "}"; 21552 Log.d(VIEW_LOG_TAG, output); 21553 21554 output = debugIndent(depth); 21555 output += "privateFlags={"; 21556 output += View.printPrivateFlags(mPrivateFlags); 21557 output += "}"; 21558 Log.d(VIEW_LOG_TAG, output); 21559 } 21560 21561 /** 21562 * Creates a string of whitespaces used for indentation. 21563 * 21564 * @param depth the indentation level 21565 * @return a String containing (depth * 2 + 3) * 2 white spaces 21566 * 21567 * @hide 21568 */ 21569 protected static String debugIndent(int depth) { 21570 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 21571 for (int i = 0; i < (depth * 2) + 3; i++) { 21572 spaces.append(' ').append(' '); 21573 } 21574 return spaces.toString(); 21575 } 21576 21577 /** 21578 * <p>Return the offset of the widget's text baseline from the widget's top 21579 * boundary. If this widget does not support baseline alignment, this 21580 * method returns -1. </p> 21581 * 21582 * @return the offset of the baseline within the widget's bounds or -1 21583 * if baseline alignment is not supported 21584 */ 21585 @ViewDebug.ExportedProperty(category = "layout") 21586 public int getBaseline() { 21587 return -1; 21588 } 21589 21590 /** 21591 * Returns whether the view hierarchy is currently undergoing a layout pass. This 21592 * information is useful to avoid situations such as calling {@link #requestLayout()} during 21593 * a layout pass. 21594 * 21595 * @return whether the view hierarchy is currently undergoing a layout pass 21596 */ 21597 public boolean isInLayout() { 21598 ViewRootImpl viewRoot = getViewRootImpl(); 21599 return (viewRoot != null && viewRoot.isInLayout()); 21600 } 21601 21602 /** 21603 * Call this when something has changed which has invalidated the 21604 * layout of this view. This will schedule a layout pass of the view 21605 * tree. This should not be called while the view hierarchy is currently in a layout 21606 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 21607 * end of the current layout pass (and then layout will run again) or after the current 21608 * frame is drawn and the next layout occurs. 21609 * 21610 * <p>Subclasses which override this method should call the superclass method to 21611 * handle possible request-during-layout errors correctly.</p> 21612 */ 21613 @CallSuper 21614 public void requestLayout() { 21615 if (mMeasureCache != null) mMeasureCache.clear(); 21616 21617 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 21618 // Only trigger request-during-layout logic if this is the view requesting it, 21619 // not the views in its parent hierarchy 21620 ViewRootImpl viewRoot = getViewRootImpl(); 21621 if (viewRoot != null && viewRoot.isInLayout()) { 21622 if (!viewRoot.requestLayoutDuringLayout(this)) { 21623 return; 21624 } 21625 } 21626 mAttachInfo.mViewRequestingLayout = this; 21627 } 21628 21629 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21630 mPrivateFlags |= PFLAG_INVALIDATED; 21631 21632 if (mParent != null && !mParent.isLayoutRequested()) { 21633 mParent.requestLayout(); 21634 } 21635 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 21636 mAttachInfo.mViewRequestingLayout = null; 21637 } 21638 } 21639 21640 /** 21641 * Forces this view to be laid out during the next layout pass. 21642 * This method does not call requestLayout() or forceLayout() 21643 * on the parent. 21644 */ 21645 public void forceLayout() { 21646 if (mMeasureCache != null) mMeasureCache.clear(); 21647 21648 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21649 mPrivateFlags |= PFLAG_INVALIDATED; 21650 } 21651 21652 /** 21653 * <p> 21654 * This is called to find out how big a view should be. The parent 21655 * supplies constraint information in the width and height parameters. 21656 * </p> 21657 * 21658 * <p> 21659 * The actual measurement work of a view is performed in 21660 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 21661 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 21662 * </p> 21663 * 21664 * 21665 * @param widthMeasureSpec Horizontal space requirements as imposed by the 21666 * parent 21667 * @param heightMeasureSpec Vertical space requirements as imposed by the 21668 * parent 21669 * 21670 * @see #onMeasure(int, int) 21671 */ 21672 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 21673 boolean optical = isLayoutModeOptical(this); 21674 if (optical != isLayoutModeOptical(mParent)) { 21675 Insets insets = getOpticalInsets(); 21676 int oWidth = insets.left + insets.right; 21677 int oHeight = insets.top + insets.bottom; 21678 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 21679 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 21680 } 21681 21682 // Suppress sign extension for the low bytes 21683 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 21684 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 21685 21686 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 21687 21688 // Optimize layout by avoiding an extra EXACTLY pass when the view is 21689 // already measured as the correct size. In API 23 and below, this 21690 // extra pass is required to make LinearLayout re-distribute weight. 21691 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 21692 || heightMeasureSpec != mOldHeightMeasureSpec; 21693 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 21694 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 21695 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 21696 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 21697 final boolean needsLayout = specChanged 21698 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 21699 21700 if (forceLayout || needsLayout) { 21701 // first clears the measured dimension flag 21702 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 21703 21704 resolveRtlPropertiesIfNeeded(); 21705 21706 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 21707 if (cacheIndex < 0 || sIgnoreMeasureCache) { 21708 // measure ourselves, this should set the measured dimension flag back 21709 onMeasure(widthMeasureSpec, heightMeasureSpec); 21710 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21711 } else { 21712 long value = mMeasureCache.valueAt(cacheIndex); 21713 // Casting a long to int drops the high 32 bits, no mask needed 21714 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 21715 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21716 } 21717 21718 // flag not set, setMeasuredDimension() was not invoked, we raise 21719 // an exception to warn the developer 21720 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 21721 throw new IllegalStateException("View with id " + getId() + ": " 21722 + getClass().getName() + "#onMeasure() did not set the" 21723 + " measured dimension by calling" 21724 + " setMeasuredDimension()"); 21725 } 21726 21727 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 21728 } 21729 21730 mOldWidthMeasureSpec = widthMeasureSpec; 21731 mOldHeightMeasureSpec = heightMeasureSpec; 21732 21733 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 21734 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 21735 } 21736 21737 /** 21738 * <p> 21739 * Measure the view and its content to determine the measured width and the 21740 * measured height. This method is invoked by {@link #measure(int, int)} and 21741 * should be overridden by subclasses to provide accurate and efficient 21742 * measurement of their contents. 21743 * </p> 21744 * 21745 * <p> 21746 * <strong>CONTRACT:</strong> When overriding this method, you 21747 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 21748 * measured width and height of this view. Failure to do so will trigger an 21749 * <code>IllegalStateException</code>, thrown by 21750 * {@link #measure(int, int)}. Calling the superclass' 21751 * {@link #onMeasure(int, int)} is a valid use. 21752 * </p> 21753 * 21754 * <p> 21755 * The base class implementation of measure defaults to the background size, 21756 * unless a larger size is allowed by the MeasureSpec. Subclasses should 21757 * override {@link #onMeasure(int, int)} to provide better measurements of 21758 * their content. 21759 * </p> 21760 * 21761 * <p> 21762 * If this method is overridden, it is the subclass's responsibility to make 21763 * sure the measured height and width are at least the view's minimum height 21764 * and width ({@link #getSuggestedMinimumHeight()} and 21765 * {@link #getSuggestedMinimumWidth()}). 21766 * </p> 21767 * 21768 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 21769 * The requirements are encoded with 21770 * {@link android.view.View.MeasureSpec}. 21771 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 21772 * The requirements are encoded with 21773 * {@link android.view.View.MeasureSpec}. 21774 * 21775 * @see #getMeasuredWidth() 21776 * @see #getMeasuredHeight() 21777 * @see #setMeasuredDimension(int, int) 21778 * @see #getSuggestedMinimumHeight() 21779 * @see #getSuggestedMinimumWidth() 21780 * @see android.view.View.MeasureSpec#getMode(int) 21781 * @see android.view.View.MeasureSpec#getSize(int) 21782 */ 21783 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 21784 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 21785 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 21786 } 21787 21788 /** 21789 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 21790 * measured width and measured height. Failing to do so will trigger an 21791 * exception at measurement time.</p> 21792 * 21793 * @param measuredWidth The measured width of this view. May be a complex 21794 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21795 * {@link #MEASURED_STATE_TOO_SMALL}. 21796 * @param measuredHeight The measured height of this view. May be a complex 21797 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21798 * {@link #MEASURED_STATE_TOO_SMALL}. 21799 */ 21800 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 21801 boolean optical = isLayoutModeOptical(this); 21802 if (optical != isLayoutModeOptical(mParent)) { 21803 Insets insets = getOpticalInsets(); 21804 int opticalWidth = insets.left + insets.right; 21805 int opticalHeight = insets.top + insets.bottom; 21806 21807 measuredWidth += optical ? opticalWidth : -opticalWidth; 21808 measuredHeight += optical ? opticalHeight : -opticalHeight; 21809 } 21810 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 21811 } 21812 21813 /** 21814 * Sets the measured dimension without extra processing for things like optical bounds. 21815 * Useful for reapplying consistent values that have already been cooked with adjustments 21816 * for optical bounds, etc. such as those from the measurement cache. 21817 * 21818 * @param measuredWidth The measured width of this view. May be a complex 21819 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21820 * {@link #MEASURED_STATE_TOO_SMALL}. 21821 * @param measuredHeight The measured height of this view. May be a complex 21822 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21823 * {@link #MEASURED_STATE_TOO_SMALL}. 21824 */ 21825 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 21826 mMeasuredWidth = measuredWidth; 21827 mMeasuredHeight = measuredHeight; 21828 21829 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 21830 } 21831 21832 /** 21833 * Merge two states as returned by {@link #getMeasuredState()}. 21834 * @param curState The current state as returned from a view or the result 21835 * of combining multiple views. 21836 * @param newState The new view state to combine. 21837 * @return Returns a new integer reflecting the combination of the two 21838 * states. 21839 */ 21840 public static int combineMeasuredStates(int curState, int newState) { 21841 return curState | newState; 21842 } 21843 21844 /** 21845 * Version of {@link #resolveSizeAndState(int, int, int)} 21846 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 21847 */ 21848 public static int resolveSize(int size, int measureSpec) { 21849 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 21850 } 21851 21852 /** 21853 * Utility to reconcile a desired size and state, with constraints imposed 21854 * by a MeasureSpec. Will take the desired size, unless a different size 21855 * is imposed by the constraints. The returned value is a compound integer, 21856 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 21857 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 21858 * resulting size is smaller than the size the view wants to be. 21859 * 21860 * @param size How big the view wants to be. 21861 * @param measureSpec Constraints imposed by the parent. 21862 * @param childMeasuredState Size information bit mask for the view's 21863 * children. 21864 * @return Size information bit mask as defined by 21865 * {@link #MEASURED_SIZE_MASK} and 21866 * {@link #MEASURED_STATE_TOO_SMALL}. 21867 */ 21868 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 21869 final int specMode = MeasureSpec.getMode(measureSpec); 21870 final int specSize = MeasureSpec.getSize(measureSpec); 21871 final int result; 21872 switch (specMode) { 21873 case MeasureSpec.AT_MOST: 21874 if (specSize < size) { 21875 result = specSize | MEASURED_STATE_TOO_SMALL; 21876 } else { 21877 result = size; 21878 } 21879 break; 21880 case MeasureSpec.EXACTLY: 21881 result = specSize; 21882 break; 21883 case MeasureSpec.UNSPECIFIED: 21884 default: 21885 result = size; 21886 } 21887 return result | (childMeasuredState & MEASURED_STATE_MASK); 21888 } 21889 21890 /** 21891 * Utility to return a default size. Uses the supplied size if the 21892 * MeasureSpec imposed no constraints. Will get larger if allowed 21893 * by the MeasureSpec. 21894 * 21895 * @param size Default size for this view 21896 * @param measureSpec Constraints imposed by the parent 21897 * @return The size this view should be. 21898 */ 21899 public static int getDefaultSize(int size, int measureSpec) { 21900 int result = size; 21901 int specMode = MeasureSpec.getMode(measureSpec); 21902 int specSize = MeasureSpec.getSize(measureSpec); 21903 21904 switch (specMode) { 21905 case MeasureSpec.UNSPECIFIED: 21906 result = size; 21907 break; 21908 case MeasureSpec.AT_MOST: 21909 case MeasureSpec.EXACTLY: 21910 result = specSize; 21911 break; 21912 } 21913 return result; 21914 } 21915 21916 /** 21917 * Returns the suggested minimum height that the view should use. This 21918 * returns the maximum of the view's minimum height 21919 * and the background's minimum height 21920 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 21921 * <p> 21922 * When being used in {@link #onMeasure(int, int)}, the caller should still 21923 * ensure the returned height is within the requirements of the parent. 21924 * 21925 * @return The suggested minimum height of the view. 21926 */ 21927 protected int getSuggestedMinimumHeight() { 21928 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 21929 21930 } 21931 21932 /** 21933 * Returns the suggested minimum width that the view should use. This 21934 * returns the maximum of the view's minimum width 21935 * and the background's minimum width 21936 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 21937 * <p> 21938 * When being used in {@link #onMeasure(int, int)}, the caller should still 21939 * ensure the returned width is within the requirements of the parent. 21940 * 21941 * @return The suggested minimum width of the view. 21942 */ 21943 protected int getSuggestedMinimumWidth() { 21944 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 21945 } 21946 21947 /** 21948 * Returns the minimum height of the view. 21949 * 21950 * @return the minimum height the view will try to be, in pixels 21951 * 21952 * @see #setMinimumHeight(int) 21953 * 21954 * @attr ref android.R.styleable#View_minHeight 21955 */ 21956 public int getMinimumHeight() { 21957 return mMinHeight; 21958 } 21959 21960 /** 21961 * Sets the minimum height of the view. It is not guaranteed the view will 21962 * be able to achieve this minimum height (for example, if its parent layout 21963 * constrains it with less available height). 21964 * 21965 * @param minHeight The minimum height the view will try to be, in pixels 21966 * 21967 * @see #getMinimumHeight() 21968 * 21969 * @attr ref android.R.styleable#View_minHeight 21970 */ 21971 @RemotableViewMethod 21972 public void setMinimumHeight(int minHeight) { 21973 mMinHeight = minHeight; 21974 requestLayout(); 21975 } 21976 21977 /** 21978 * Returns the minimum width of the view. 21979 * 21980 * @return the minimum width the view will try to be, in pixels 21981 * 21982 * @see #setMinimumWidth(int) 21983 * 21984 * @attr ref android.R.styleable#View_minWidth 21985 */ 21986 public int getMinimumWidth() { 21987 return mMinWidth; 21988 } 21989 21990 /** 21991 * Sets the minimum width of the view. It is not guaranteed the view will 21992 * be able to achieve this minimum width (for example, if its parent layout 21993 * constrains it with less available width). 21994 * 21995 * @param minWidth The minimum width the view will try to be, in pixels 21996 * 21997 * @see #getMinimumWidth() 21998 * 21999 * @attr ref android.R.styleable#View_minWidth 22000 */ 22001 public void setMinimumWidth(int minWidth) { 22002 mMinWidth = minWidth; 22003 requestLayout(); 22004 22005 } 22006 22007 /** 22008 * Get the animation currently associated with this view. 22009 * 22010 * @return The animation that is currently playing or 22011 * scheduled to play for this view. 22012 */ 22013 public Animation getAnimation() { 22014 return mCurrentAnimation; 22015 } 22016 22017 /** 22018 * Start the specified animation now. 22019 * 22020 * @param animation the animation to start now 22021 */ 22022 public void startAnimation(Animation animation) { 22023 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 22024 setAnimation(animation); 22025 invalidateParentCaches(); 22026 invalidate(true); 22027 } 22028 22029 /** 22030 * Cancels any animations for this view. 22031 */ 22032 public void clearAnimation() { 22033 if (mCurrentAnimation != null) { 22034 mCurrentAnimation.detach(); 22035 } 22036 mCurrentAnimation = null; 22037 invalidateParentIfNeeded(); 22038 } 22039 22040 /** 22041 * Sets the next animation to play for this view. 22042 * If you want the animation to play immediately, use 22043 * {@link #startAnimation(android.view.animation.Animation)} instead. 22044 * This method provides allows fine-grained 22045 * control over the start time and invalidation, but you 22046 * must make sure that 1) the animation has a start time set, and 22047 * 2) the view's parent (which controls animations on its children) 22048 * will be invalidated when the animation is supposed to 22049 * start. 22050 * 22051 * @param animation The next animation, or null. 22052 */ 22053 public void setAnimation(Animation animation) { 22054 mCurrentAnimation = animation; 22055 22056 if (animation != null) { 22057 // If the screen is off assume the animation start time is now instead of 22058 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 22059 // would cause the animation to start when the screen turns back on 22060 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 22061 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 22062 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 22063 } 22064 animation.reset(); 22065 } 22066 } 22067 22068 /** 22069 * Invoked by a parent ViewGroup to notify the start of the animation 22070 * currently associated with this view. If you override this method, 22071 * always call super.onAnimationStart(); 22072 * 22073 * @see #setAnimation(android.view.animation.Animation) 22074 * @see #getAnimation() 22075 */ 22076 @CallSuper 22077 protected void onAnimationStart() { 22078 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 22079 } 22080 22081 /** 22082 * Invoked by a parent ViewGroup to notify the end of the animation 22083 * currently associated with this view. If you override this method, 22084 * always call super.onAnimationEnd(); 22085 * 22086 * @see #setAnimation(android.view.animation.Animation) 22087 * @see #getAnimation() 22088 */ 22089 @CallSuper 22090 protected void onAnimationEnd() { 22091 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 22092 } 22093 22094 /** 22095 * Invoked if there is a Transform that involves alpha. Subclass that can 22096 * draw themselves with the specified alpha should return true, and then 22097 * respect that alpha when their onDraw() is called. If this returns false 22098 * then the view may be redirected to draw into an offscreen buffer to 22099 * fulfill the request, which will look fine, but may be slower than if the 22100 * subclass handles it internally. The default implementation returns false. 22101 * 22102 * @param alpha The alpha (0..255) to apply to the view's drawing 22103 * @return true if the view can draw with the specified alpha. 22104 */ 22105 protected boolean onSetAlpha(int alpha) { 22106 return false; 22107 } 22108 22109 /** 22110 * This is used by the RootView to perform an optimization when 22111 * the view hierarchy contains one or several SurfaceView. 22112 * SurfaceView is always considered transparent, but its children are not, 22113 * therefore all View objects remove themselves from the global transparent 22114 * region (passed as a parameter to this function). 22115 * 22116 * @param region The transparent region for this ViewAncestor (window). 22117 * 22118 * @return Returns true if the effective visibility of the view at this 22119 * point is opaque, regardless of the transparent region; returns false 22120 * if it is possible for underlying windows to be seen behind the view. 22121 * 22122 * {@hide} 22123 */ 22124 public boolean gatherTransparentRegion(Region region) { 22125 final AttachInfo attachInfo = mAttachInfo; 22126 if (region != null && attachInfo != null) { 22127 final int pflags = mPrivateFlags; 22128 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 22129 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 22130 // remove it from the transparent region. 22131 final int[] location = attachInfo.mTransparentLocation; 22132 getLocationInWindow(location); 22133 // When a view has Z value, then it will be better to leave some area below the view 22134 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 22135 // the bottom part needs more offset than the left, top and right parts due to the 22136 // spot light effects. 22137 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 22138 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 22139 location[0] + mRight - mLeft + shadowOffset, 22140 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 22141 } else { 22142 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 22143 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 22144 // the background drawable's non-transparent parts from this transparent region. 22145 applyDrawableToTransparentRegion(mBackground, region); 22146 } 22147 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 22148 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 22149 // Similarly, we remove the foreground drawable's non-transparent parts. 22150 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 22151 } 22152 if (mDefaultFocusHighlight != null 22153 && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) { 22154 // Similarly, we remove the default focus highlight's non-transparent parts. 22155 applyDrawableToTransparentRegion(mDefaultFocusHighlight, region); 22156 } 22157 } 22158 } 22159 return true; 22160 } 22161 22162 /** 22163 * Play a sound effect for this view. 22164 * 22165 * <p>The framework will play sound effects for some built in actions, such as 22166 * clicking, but you may wish to play these effects in your widget, 22167 * for instance, for internal navigation. 22168 * 22169 * <p>The sound effect will only be played if sound effects are enabled by the user, and 22170 * {@link #isSoundEffectsEnabled()} is true. 22171 * 22172 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 22173 */ 22174 public void playSoundEffect(int soundConstant) { 22175 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 22176 return; 22177 } 22178 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 22179 } 22180 22181 /** 22182 * BZZZTT!!1! 22183 * 22184 * <p>Provide haptic feedback to the user for this view. 22185 * 22186 * <p>The framework will provide haptic feedback for some built in actions, 22187 * such as long presses, but you may wish to provide feedback for your 22188 * own widget. 22189 * 22190 * <p>The feedback will only be performed if 22191 * {@link #isHapticFeedbackEnabled()} is true. 22192 * 22193 * @param feedbackConstant One of the constants defined in 22194 * {@link HapticFeedbackConstants} 22195 */ 22196 public boolean performHapticFeedback(int feedbackConstant) { 22197 return performHapticFeedback(feedbackConstant, 0); 22198 } 22199 22200 /** 22201 * BZZZTT!!1! 22202 * 22203 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 22204 * 22205 * @param feedbackConstant One of the constants defined in 22206 * {@link HapticFeedbackConstants} 22207 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 22208 */ 22209 public boolean performHapticFeedback(int feedbackConstant, int flags) { 22210 if (mAttachInfo == null) { 22211 return false; 22212 } 22213 //noinspection SimplifiableIfStatement 22214 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 22215 && !isHapticFeedbackEnabled()) { 22216 return false; 22217 } 22218 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 22219 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 22220 } 22221 22222 /** 22223 * Request that the visibility of the status bar or other screen/window 22224 * decorations be changed. 22225 * 22226 * <p>This method is used to put the over device UI into temporary modes 22227 * where the user's attention is focused more on the application content, 22228 * by dimming or hiding surrounding system affordances. This is typically 22229 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 22230 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 22231 * to be placed behind the action bar (and with these flags other system 22232 * affordances) so that smooth transitions between hiding and showing them 22233 * can be done. 22234 * 22235 * <p>Two representative examples of the use of system UI visibility is 22236 * implementing a content browsing application (like a magazine reader) 22237 * and a video playing application. 22238 * 22239 * <p>The first code shows a typical implementation of a View in a content 22240 * browsing application. In this implementation, the application goes 22241 * into a content-oriented mode by hiding the status bar and action bar, 22242 * and putting the navigation elements into lights out mode. The user can 22243 * then interact with content while in this mode. Such an application should 22244 * provide an easy way for the user to toggle out of the mode (such as to 22245 * check information in the status bar or access notifications). In the 22246 * implementation here, this is done simply by tapping on the content. 22247 * 22248 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 22249 * content} 22250 * 22251 * <p>This second code sample shows a typical implementation of a View 22252 * in a video playing application. In this situation, while the video is 22253 * playing the application would like to go into a complete full-screen mode, 22254 * to use as much of the display as possible for the video. When in this state 22255 * the user can not interact with the application; the system intercepts 22256 * touching on the screen to pop the UI out of full screen mode. See 22257 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 22258 * 22259 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 22260 * content} 22261 * 22262 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22263 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22264 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22265 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22266 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22267 */ 22268 public void setSystemUiVisibility(int visibility) { 22269 if (visibility != mSystemUiVisibility) { 22270 mSystemUiVisibility = visibility; 22271 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22272 mParent.recomputeViewAttributes(this); 22273 } 22274 } 22275 } 22276 22277 /** 22278 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 22279 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22280 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22281 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22282 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22283 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22284 */ 22285 public int getSystemUiVisibility() { 22286 return mSystemUiVisibility; 22287 } 22288 22289 /** 22290 * Returns the current system UI visibility that is currently set for 22291 * the entire window. This is the combination of the 22292 * {@link #setSystemUiVisibility(int)} values supplied by all of the 22293 * views in the window. 22294 */ 22295 public int getWindowSystemUiVisibility() { 22296 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 22297 } 22298 22299 /** 22300 * Override to find out when the window's requested system UI visibility 22301 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 22302 * This is different from the callbacks received through 22303 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 22304 * in that this is only telling you about the local request of the window, 22305 * not the actual values applied by the system. 22306 */ 22307 public void onWindowSystemUiVisibilityChanged(int visible) { 22308 } 22309 22310 /** 22311 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 22312 * the view hierarchy. 22313 */ 22314 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 22315 onWindowSystemUiVisibilityChanged(visible); 22316 } 22317 22318 /** 22319 * Set a listener to receive callbacks when the visibility of the system bar changes. 22320 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 22321 */ 22322 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 22323 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 22324 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22325 mParent.recomputeViewAttributes(this); 22326 } 22327 } 22328 22329 /** 22330 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 22331 * the view hierarchy. 22332 */ 22333 public void dispatchSystemUiVisibilityChanged(int visibility) { 22334 ListenerInfo li = mListenerInfo; 22335 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 22336 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 22337 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 22338 } 22339 } 22340 22341 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 22342 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 22343 if (val != mSystemUiVisibility) { 22344 setSystemUiVisibility(val); 22345 return true; 22346 } 22347 return false; 22348 } 22349 22350 /** @hide */ 22351 public void setDisabledSystemUiVisibility(int flags) { 22352 if (mAttachInfo != null) { 22353 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 22354 mAttachInfo.mDisabledSystemUiVisibility = flags; 22355 if (mParent != null) { 22356 mParent.recomputeViewAttributes(this); 22357 } 22358 } 22359 } 22360 } 22361 22362 /** 22363 * Creates an image that the system displays during the drag and drop 22364 * operation. This is called a "drag shadow". The default implementation 22365 * for a DragShadowBuilder based on a View returns an image that has exactly the same 22366 * appearance as the given View. The default also positions the center of the drag shadow 22367 * directly under the touch point. If no View is provided (the constructor with no parameters 22368 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 22369 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 22370 * default is an invisible drag shadow. 22371 * <p> 22372 * You are not required to use the View you provide to the constructor as the basis of the 22373 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 22374 * anything you want as the drag shadow. 22375 * </p> 22376 * <p> 22377 * You pass a DragShadowBuilder object to the system when you start the drag. The system 22378 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 22379 * size and position of the drag shadow. It uses this data to construct a 22380 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 22381 * so that your application can draw the shadow image in the Canvas. 22382 * </p> 22383 * 22384 * <div class="special reference"> 22385 * <h3>Developer Guides</h3> 22386 * <p>For a guide to implementing drag and drop features, read the 22387 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22388 * </div> 22389 */ 22390 public static class DragShadowBuilder { 22391 private final WeakReference<View> mView; 22392 22393 /** 22394 * Constructs a shadow image builder based on a View. By default, the resulting drag 22395 * shadow will have the same appearance and dimensions as the View, with the touch point 22396 * over the center of the View. 22397 * @param view A View. Any View in scope can be used. 22398 */ 22399 public DragShadowBuilder(View view) { 22400 mView = new WeakReference<View>(view); 22401 } 22402 22403 /** 22404 * Construct a shadow builder object with no associated View. This 22405 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 22406 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 22407 * to supply the drag shadow's dimensions and appearance without 22408 * reference to any View object. If they are not overridden, then the result is an 22409 * invisible drag shadow. 22410 */ 22411 public DragShadowBuilder() { 22412 mView = new WeakReference<View>(null); 22413 } 22414 22415 /** 22416 * Returns the View object that had been passed to the 22417 * {@link #View.DragShadowBuilder(View)} 22418 * constructor. If that View parameter was {@code null} or if the 22419 * {@link #View.DragShadowBuilder()} 22420 * constructor was used to instantiate the builder object, this method will return 22421 * null. 22422 * 22423 * @return The View object associate with this builder object. 22424 */ 22425 @SuppressWarnings({"JavadocReference"}) 22426 final public View getView() { 22427 return mView.get(); 22428 } 22429 22430 /** 22431 * Provides the metrics for the shadow image. These include the dimensions of 22432 * the shadow image, and the point within that shadow that should 22433 * be centered under the touch location while dragging. 22434 * <p> 22435 * The default implementation sets the dimensions of the shadow to be the 22436 * same as the dimensions of the View itself and centers the shadow under 22437 * the touch point. 22438 * </p> 22439 * 22440 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 22441 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 22442 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 22443 * image. 22444 * 22445 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 22446 * shadow image that should be underneath the touch point during the drag and drop 22447 * operation. Your application must set {@link android.graphics.Point#x} to the 22448 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 22449 */ 22450 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 22451 final View view = mView.get(); 22452 if (view != null) { 22453 outShadowSize.set(view.getWidth(), view.getHeight()); 22454 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 22455 } else { 22456 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 22457 } 22458 } 22459 22460 /** 22461 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 22462 * based on the dimensions it received from the 22463 * {@link #onProvideShadowMetrics(Point, Point)} callback. 22464 * 22465 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 22466 */ 22467 public void onDrawShadow(Canvas canvas) { 22468 final View view = mView.get(); 22469 if (view != null) { 22470 view.draw(canvas); 22471 } else { 22472 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 22473 } 22474 } 22475 } 22476 22477 /** 22478 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 22479 * startDragAndDrop()} for newer platform versions. 22480 */ 22481 @Deprecated 22482 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 22483 Object myLocalState, int flags) { 22484 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 22485 } 22486 22487 /** 22488 * Starts a drag and drop operation. When your application calls this method, it passes a 22489 * {@link android.view.View.DragShadowBuilder} object to the system. The 22490 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 22491 * to get metrics for the drag shadow, and then calls the object's 22492 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 22493 * <p> 22494 * Once the system has the drag shadow, it begins the drag and drop operation by sending 22495 * drag events to all the View objects in your application that are currently visible. It does 22496 * this either by calling the View object's drag listener (an implementation of 22497 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 22498 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 22499 * Both are passed a {@link android.view.DragEvent} object that has a 22500 * {@link android.view.DragEvent#getAction()} value of 22501 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 22502 * </p> 22503 * <p> 22504 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 22505 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 22506 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 22507 * to the View the user selected for dragging. 22508 * </p> 22509 * @param data A {@link android.content.ClipData} object pointing to the data to be 22510 * transferred by the drag and drop operation. 22511 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22512 * drag shadow. 22513 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 22514 * drop operation. When dispatching drag events to views in the same activity this object 22515 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 22516 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 22517 * will return null). 22518 * <p> 22519 * myLocalState is a lightweight mechanism for the sending information from the dragged View 22520 * to the target Views. For example, it can contain flags that differentiate between a 22521 * a copy operation and a move operation. 22522 * </p> 22523 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 22524 * flags, or any combination of the following: 22525 * <ul> 22526 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 22527 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 22528 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 22529 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 22530 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 22531 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 22532 * </ul> 22533 * @return {@code true} if the method completes successfully, or 22534 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 22535 * do a drag, and so no drag operation is in progress. 22536 */ 22537 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 22538 Object myLocalState, int flags) { 22539 if (ViewDebug.DEBUG_DRAG) { 22540 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 22541 } 22542 if (mAttachInfo == null) { 22543 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 22544 return false; 22545 } 22546 22547 if (data != null) { 22548 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 22549 } 22550 22551 boolean okay = false; 22552 22553 Point shadowSize = new Point(); 22554 Point shadowTouchPoint = new Point(); 22555 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 22556 22557 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 22558 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 22559 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 22560 } 22561 22562 if (ViewDebug.DEBUG_DRAG) { 22563 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 22564 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 22565 } 22566 if (mAttachInfo.mDragSurface != null) { 22567 mAttachInfo.mDragSurface.release(); 22568 } 22569 mAttachInfo.mDragSurface = new Surface(); 22570 try { 22571 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 22572 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 22573 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 22574 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 22575 if (mAttachInfo.mDragToken != null) { 22576 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22577 try { 22578 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22579 shadowBuilder.onDrawShadow(canvas); 22580 } finally { 22581 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22582 } 22583 22584 final ViewRootImpl root = getViewRootImpl(); 22585 22586 // Cache the local state object for delivery with DragEvents 22587 root.setLocalDragState(myLocalState); 22588 22589 // repurpose 'shadowSize' for the last touch point 22590 root.getLastTouchPoint(shadowSize); 22591 22592 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 22593 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 22594 shadowTouchPoint.x, shadowTouchPoint.y, data); 22595 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 22596 } 22597 } catch (Exception e) { 22598 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 22599 mAttachInfo.mDragSurface.destroy(); 22600 mAttachInfo.mDragSurface = null; 22601 } 22602 22603 return okay; 22604 } 22605 22606 /** 22607 * Cancels an ongoing drag and drop operation. 22608 * <p> 22609 * A {@link android.view.DragEvent} object with 22610 * {@link android.view.DragEvent#getAction()} value of 22611 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 22612 * {@link android.view.DragEvent#getResult()} value of {@code false} 22613 * will be sent to every 22614 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 22615 * even if they are not currently visible. 22616 * </p> 22617 * <p> 22618 * This method can be called on any View in the same window as the View on which 22619 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 22620 * was called. 22621 * </p> 22622 */ 22623 public final void cancelDragAndDrop() { 22624 if (ViewDebug.DEBUG_DRAG) { 22625 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 22626 } 22627 if (mAttachInfo == null) { 22628 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 22629 return; 22630 } 22631 if (mAttachInfo.mDragToken != null) { 22632 try { 22633 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 22634 } catch (Exception e) { 22635 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 22636 } 22637 mAttachInfo.mDragToken = null; 22638 } else { 22639 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 22640 } 22641 } 22642 22643 /** 22644 * Updates the drag shadow for the ongoing drag and drop operation. 22645 * 22646 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22647 * new drag shadow. 22648 */ 22649 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 22650 if (ViewDebug.DEBUG_DRAG) { 22651 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 22652 } 22653 if (mAttachInfo == null) { 22654 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 22655 return; 22656 } 22657 if (mAttachInfo.mDragToken != null) { 22658 try { 22659 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22660 try { 22661 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22662 shadowBuilder.onDrawShadow(canvas); 22663 } finally { 22664 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22665 } 22666 } catch (Exception e) { 22667 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 22668 } 22669 } else { 22670 Log.e(VIEW_LOG_TAG, "No active drag"); 22671 } 22672 } 22673 22674 /** 22675 * Starts a move from {startX, startY}, the amount of the movement will be the offset 22676 * between {startX, startY} and the new cursor positon. 22677 * @param startX horizontal coordinate where the move started. 22678 * @param startY vertical coordinate where the move started. 22679 * @return whether moving was started successfully. 22680 * @hide 22681 */ 22682 public final boolean startMovingTask(float startX, float startY) { 22683 if (ViewDebug.DEBUG_POSITIONING) { 22684 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 22685 } 22686 try { 22687 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 22688 } catch (RemoteException e) { 22689 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 22690 } 22691 return false; 22692 } 22693 22694 /** 22695 * Handles drag events sent by the system following a call to 22696 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 22697 * startDragAndDrop()}. 22698 *<p> 22699 * When the system calls this method, it passes a 22700 * {@link android.view.DragEvent} object. A call to 22701 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 22702 * in DragEvent. The method uses these to determine what is happening in the drag and drop 22703 * operation. 22704 * @param event The {@link android.view.DragEvent} sent by the system. 22705 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 22706 * in DragEvent, indicating the type of drag event represented by this object. 22707 * @return {@code true} if the method was successful, otherwise {@code false}. 22708 * <p> 22709 * The method should return {@code true} in response to an action type of 22710 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 22711 * operation. 22712 * </p> 22713 * <p> 22714 * The method should also return {@code true} in response to an action type of 22715 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 22716 * {@code false} if it didn't. 22717 * </p> 22718 * <p> 22719 * For all other events, the return value is ignored. 22720 * </p> 22721 */ 22722 public boolean onDragEvent(DragEvent event) { 22723 return false; 22724 } 22725 22726 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 22727 boolean dispatchDragEnterExitInPreN(DragEvent event) { 22728 return callDragEventHandler(event); 22729 } 22730 22731 /** 22732 * Detects if this View is enabled and has a drag event listener. 22733 * If both are true, then it calls the drag event listener with the 22734 * {@link android.view.DragEvent} it received. If the drag event listener returns 22735 * {@code true}, then dispatchDragEvent() returns {@code true}. 22736 * <p> 22737 * For all other cases, the method calls the 22738 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 22739 * method and returns its result. 22740 * </p> 22741 * <p> 22742 * This ensures that a drag event is always consumed, even if the View does not have a drag 22743 * event listener. However, if the View has a listener and the listener returns true, then 22744 * onDragEvent() is not called. 22745 * </p> 22746 */ 22747 public boolean dispatchDragEvent(DragEvent event) { 22748 event.mEventHandlerWasCalled = true; 22749 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 22750 event.mAction == DragEvent.ACTION_DROP) { 22751 // About to deliver an event with coordinates to this view. Notify that now this view 22752 // has drag focus. This will send exit/enter events as needed. 22753 getViewRootImpl().setDragFocus(this, event); 22754 } 22755 return callDragEventHandler(event); 22756 } 22757 22758 final boolean callDragEventHandler(DragEvent event) { 22759 final boolean result; 22760 22761 ListenerInfo li = mListenerInfo; 22762 //noinspection SimplifiableIfStatement 22763 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 22764 && li.mOnDragListener.onDrag(this, event)) { 22765 result = true; 22766 } else { 22767 result = onDragEvent(event); 22768 } 22769 22770 switch (event.mAction) { 22771 case DragEvent.ACTION_DRAG_ENTERED: { 22772 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 22773 refreshDrawableState(); 22774 } break; 22775 case DragEvent.ACTION_DRAG_EXITED: { 22776 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 22777 refreshDrawableState(); 22778 } break; 22779 case DragEvent.ACTION_DRAG_ENDED: { 22780 mPrivateFlags2 &= ~View.DRAG_MASK; 22781 refreshDrawableState(); 22782 } break; 22783 } 22784 22785 return result; 22786 } 22787 22788 boolean canAcceptDrag() { 22789 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 22790 } 22791 22792 /** 22793 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 22794 * it is ever exposed at all. 22795 * @hide 22796 */ 22797 public void onCloseSystemDialogs(String reason) { 22798 } 22799 22800 /** 22801 * Given a Drawable whose bounds have been set to draw into this view, 22802 * update a Region being computed for 22803 * {@link #gatherTransparentRegion(android.graphics.Region)} so 22804 * that any non-transparent parts of the Drawable are removed from the 22805 * given transparent region. 22806 * 22807 * @param dr The Drawable whose transparency is to be applied to the region. 22808 * @param region A Region holding the current transparency information, 22809 * where any parts of the region that are set are considered to be 22810 * transparent. On return, this region will be modified to have the 22811 * transparency information reduced by the corresponding parts of the 22812 * Drawable that are not transparent. 22813 * {@hide} 22814 */ 22815 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 22816 if (DBG) { 22817 Log.i("View", "Getting transparent region for: " + this); 22818 } 22819 final Region r = dr.getTransparentRegion(); 22820 final Rect db = dr.getBounds(); 22821 final AttachInfo attachInfo = mAttachInfo; 22822 if (r != null && attachInfo != null) { 22823 final int w = getRight()-getLeft(); 22824 final int h = getBottom()-getTop(); 22825 if (db.left > 0) { 22826 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 22827 r.op(0, 0, db.left, h, Region.Op.UNION); 22828 } 22829 if (db.right < w) { 22830 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 22831 r.op(db.right, 0, w, h, Region.Op.UNION); 22832 } 22833 if (db.top > 0) { 22834 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 22835 r.op(0, 0, w, db.top, Region.Op.UNION); 22836 } 22837 if (db.bottom < h) { 22838 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 22839 r.op(0, db.bottom, w, h, Region.Op.UNION); 22840 } 22841 final int[] location = attachInfo.mTransparentLocation; 22842 getLocationInWindow(location); 22843 r.translate(location[0], location[1]); 22844 region.op(r, Region.Op.INTERSECT); 22845 } else { 22846 region.op(db, Region.Op.DIFFERENCE); 22847 } 22848 } 22849 22850 private void checkForLongClick(int delayOffset, float x, float y) { 22851 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) { 22852 mHasPerformedLongPress = false; 22853 22854 if (mPendingCheckForLongPress == null) { 22855 mPendingCheckForLongPress = new CheckForLongPress(); 22856 } 22857 mPendingCheckForLongPress.setAnchor(x, y); 22858 mPendingCheckForLongPress.rememberWindowAttachCount(); 22859 mPendingCheckForLongPress.rememberPressedState(); 22860 postDelayed(mPendingCheckForLongPress, 22861 ViewConfiguration.getLongPressTimeout() - delayOffset); 22862 } 22863 } 22864 22865 /** 22866 * Inflate a view from an XML resource. This convenience method wraps the {@link 22867 * LayoutInflater} class, which provides a full range of options for view inflation. 22868 * 22869 * @param context The Context object for your activity or application. 22870 * @param resource The resource ID to inflate 22871 * @param root A view group that will be the parent. Used to properly inflate the 22872 * layout_* parameters. 22873 * @see LayoutInflater 22874 */ 22875 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 22876 LayoutInflater factory = LayoutInflater.from(context); 22877 return factory.inflate(resource, root); 22878 } 22879 22880 /** 22881 * Scroll the view with standard behavior for scrolling beyond the normal 22882 * content boundaries. Views that call this method should override 22883 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 22884 * results of an over-scroll operation. 22885 * 22886 * Views can use this method to handle any touch or fling-based scrolling. 22887 * 22888 * @param deltaX Change in X in pixels 22889 * @param deltaY Change in Y in pixels 22890 * @param scrollX Current X scroll value in pixels before applying deltaX 22891 * @param scrollY Current Y scroll value in pixels before applying deltaY 22892 * @param scrollRangeX Maximum content scroll range along the X axis 22893 * @param scrollRangeY Maximum content scroll range along the Y axis 22894 * @param maxOverScrollX Number of pixels to overscroll by in either direction 22895 * along the X axis. 22896 * @param maxOverScrollY Number of pixels to overscroll by in either direction 22897 * along the Y axis. 22898 * @param isTouchEvent true if this scroll operation is the result of a touch event. 22899 * @return true if scrolling was clamped to an over-scroll boundary along either 22900 * axis, false otherwise. 22901 */ 22902 @SuppressWarnings({"UnusedParameters"}) 22903 protected boolean overScrollBy(int deltaX, int deltaY, 22904 int scrollX, int scrollY, 22905 int scrollRangeX, int scrollRangeY, 22906 int maxOverScrollX, int maxOverScrollY, 22907 boolean isTouchEvent) { 22908 final int overScrollMode = mOverScrollMode; 22909 final boolean canScrollHorizontal = 22910 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 22911 final boolean canScrollVertical = 22912 computeVerticalScrollRange() > computeVerticalScrollExtent(); 22913 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 22914 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 22915 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 22916 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 22917 22918 int newScrollX = scrollX + deltaX; 22919 if (!overScrollHorizontal) { 22920 maxOverScrollX = 0; 22921 } 22922 22923 int newScrollY = scrollY + deltaY; 22924 if (!overScrollVertical) { 22925 maxOverScrollY = 0; 22926 } 22927 22928 // Clamp values if at the limits and record 22929 final int left = -maxOverScrollX; 22930 final int right = maxOverScrollX + scrollRangeX; 22931 final int top = -maxOverScrollY; 22932 final int bottom = maxOverScrollY + scrollRangeY; 22933 22934 boolean clampedX = false; 22935 if (newScrollX > right) { 22936 newScrollX = right; 22937 clampedX = true; 22938 } else if (newScrollX < left) { 22939 newScrollX = left; 22940 clampedX = true; 22941 } 22942 22943 boolean clampedY = false; 22944 if (newScrollY > bottom) { 22945 newScrollY = bottom; 22946 clampedY = true; 22947 } else if (newScrollY < top) { 22948 newScrollY = top; 22949 clampedY = true; 22950 } 22951 22952 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 22953 22954 return clampedX || clampedY; 22955 } 22956 22957 /** 22958 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 22959 * respond to the results of an over-scroll operation. 22960 * 22961 * @param scrollX New X scroll value in pixels 22962 * @param scrollY New Y scroll value in pixels 22963 * @param clampedX True if scrollX was clamped to an over-scroll boundary 22964 * @param clampedY True if scrollY was clamped to an over-scroll boundary 22965 */ 22966 protected void onOverScrolled(int scrollX, int scrollY, 22967 boolean clampedX, boolean clampedY) { 22968 // Intentionally empty. 22969 } 22970 22971 /** 22972 * Returns the over-scroll mode for this view. The result will be 22973 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22974 * (allow over-scrolling only if the view content is larger than the container), 22975 * or {@link #OVER_SCROLL_NEVER}. 22976 * 22977 * @return This view's over-scroll mode. 22978 */ 22979 public int getOverScrollMode() { 22980 return mOverScrollMode; 22981 } 22982 22983 /** 22984 * Set the over-scroll mode for this view. Valid over-scroll modes are 22985 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22986 * (allow over-scrolling only if the view content is larger than the container), 22987 * or {@link #OVER_SCROLL_NEVER}. 22988 * 22989 * Setting the over-scroll mode of a view will have an effect only if the 22990 * view is capable of scrolling. 22991 * 22992 * @param overScrollMode The new over-scroll mode for this view. 22993 */ 22994 public void setOverScrollMode(int overScrollMode) { 22995 if (overScrollMode != OVER_SCROLL_ALWAYS && 22996 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 22997 overScrollMode != OVER_SCROLL_NEVER) { 22998 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 22999 } 23000 mOverScrollMode = overScrollMode; 23001 } 23002 23003 /** 23004 * Enable or disable nested scrolling for this view. 23005 * 23006 * <p>If this property is set to true the view will be permitted to initiate nested 23007 * scrolling operations with a compatible parent view in the current hierarchy. If this 23008 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 23009 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 23010 * the nested scroll.</p> 23011 * 23012 * @param enabled true to enable nested scrolling, false to disable 23013 * 23014 * @see #isNestedScrollingEnabled() 23015 */ 23016 public void setNestedScrollingEnabled(boolean enabled) { 23017 if (enabled) { 23018 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 23019 } else { 23020 stopNestedScroll(); 23021 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 23022 } 23023 } 23024 23025 /** 23026 * Returns true if nested scrolling is enabled for this view. 23027 * 23028 * <p>If nested scrolling is enabled and this View class implementation supports it, 23029 * this view will act as a nested scrolling child view when applicable, forwarding data 23030 * about the scroll operation in progress to a compatible and cooperating nested scrolling 23031 * parent.</p> 23032 * 23033 * @return true if nested scrolling is enabled 23034 * 23035 * @see #setNestedScrollingEnabled(boolean) 23036 */ 23037 public boolean isNestedScrollingEnabled() { 23038 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 23039 PFLAG3_NESTED_SCROLLING_ENABLED; 23040 } 23041 23042 /** 23043 * Begin a nestable scroll operation along the given axes. 23044 * 23045 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 23046 * 23047 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 23048 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 23049 * In the case of touch scrolling the nested scroll will be terminated automatically in 23050 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 23051 * In the event of programmatic scrolling the caller must explicitly call 23052 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 23053 * 23054 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 23055 * If it returns false the caller may ignore the rest of this contract until the next scroll. 23056 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 23057 * 23058 * <p>At each incremental step of the scroll the caller should invoke 23059 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 23060 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 23061 * parent at least partially consumed the scroll and the caller should adjust the amount it 23062 * scrolls by.</p> 23063 * 23064 * <p>After applying the remainder of the scroll delta the caller should invoke 23065 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 23066 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 23067 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 23068 * </p> 23069 * 23070 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 23071 * {@link #SCROLL_AXIS_VERTICAL}. 23072 * @return true if a cooperative parent was found and nested scrolling has been enabled for 23073 * the current gesture. 23074 * 23075 * @see #stopNestedScroll() 23076 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 23077 * @see #dispatchNestedScroll(int, int, int, int, int[]) 23078 */ 23079 public boolean startNestedScroll(int axes) { 23080 if (hasNestedScrollingParent()) { 23081 // Already in progress 23082 return true; 23083 } 23084 if (isNestedScrollingEnabled()) { 23085 ViewParent p = getParent(); 23086 View child = this; 23087 while (p != null) { 23088 try { 23089 if (p.onStartNestedScroll(child, this, axes)) { 23090 mNestedScrollingParent = p; 23091 p.onNestedScrollAccepted(child, this, axes); 23092 return true; 23093 } 23094 } catch (AbstractMethodError e) { 23095 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 23096 "method onStartNestedScroll", e); 23097 // Allow the search upward to continue 23098 } 23099 if (p instanceof View) { 23100 child = (View) p; 23101 } 23102 p = p.getParent(); 23103 } 23104 } 23105 return false; 23106 } 23107 23108 /** 23109 * Stop a nested scroll in progress. 23110 * 23111 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 23112 * 23113 * @see #startNestedScroll(int) 23114 */ 23115 public void stopNestedScroll() { 23116 if (mNestedScrollingParent != null) { 23117 mNestedScrollingParent.onStopNestedScroll(this); 23118 mNestedScrollingParent = null; 23119 } 23120 } 23121 23122 /** 23123 * Returns true if this view has a nested scrolling parent. 23124 * 23125 * <p>The presence of a nested scrolling parent indicates that this view has initiated 23126 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 23127 * 23128 * @return whether this view has a nested scrolling parent 23129 */ 23130 public boolean hasNestedScrollingParent() { 23131 return mNestedScrollingParent != null; 23132 } 23133 23134 /** 23135 * Dispatch one step of a nested scroll in progress. 23136 * 23137 * <p>Implementations of views that support nested scrolling should call this to report 23138 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 23139 * is not currently in progress or nested scrolling is not 23140 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 23141 * 23142 * <p>Compatible View implementations should also call 23143 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 23144 * consuming a component of the scroll event themselves.</p> 23145 * 23146 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 23147 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 23148 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 23149 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 23150 * @param offsetInWindow Optional. If not null, on return this will contain the offset 23151 * in local view coordinates of this view from before this operation 23152 * to after it completes. View implementations may use this to adjust 23153 * expected input coordinate tracking. 23154 * @return true if the event was dispatched, false if it could not be dispatched. 23155 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 23156 */ 23157 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 23158 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 23159 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23160 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 23161 int startX = 0; 23162 int startY = 0; 23163 if (offsetInWindow != null) { 23164 getLocationInWindow(offsetInWindow); 23165 startX = offsetInWindow[0]; 23166 startY = offsetInWindow[1]; 23167 } 23168 23169 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 23170 dxUnconsumed, dyUnconsumed); 23171 23172 if (offsetInWindow != null) { 23173 getLocationInWindow(offsetInWindow); 23174 offsetInWindow[0] -= startX; 23175 offsetInWindow[1] -= startY; 23176 } 23177 return true; 23178 } else if (offsetInWindow != null) { 23179 // No motion, no dispatch. Keep offsetInWindow up to date. 23180 offsetInWindow[0] = 0; 23181 offsetInWindow[1] = 0; 23182 } 23183 } 23184 return false; 23185 } 23186 23187 /** 23188 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 23189 * 23190 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 23191 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 23192 * scrolling operation to consume some or all of the scroll operation before the child view 23193 * consumes it.</p> 23194 * 23195 * @param dx Horizontal scroll distance in pixels 23196 * @param dy Vertical scroll distance in pixels 23197 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 23198 * and consumed[1] the consumed dy. 23199 * @param offsetInWindow Optional. If not null, on return this will contain the offset 23200 * in local view coordinates of this view from before this operation 23201 * to after it completes. View implementations may use this to adjust 23202 * expected input coordinate tracking. 23203 * @return true if the parent consumed some or all of the scroll delta 23204 * @see #dispatchNestedScroll(int, int, int, int, int[]) 23205 */ 23206 public boolean dispatchNestedPreScroll(int dx, int dy, 23207 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 23208 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23209 if (dx != 0 || dy != 0) { 23210 int startX = 0; 23211 int startY = 0; 23212 if (offsetInWindow != null) { 23213 getLocationInWindow(offsetInWindow); 23214 startX = offsetInWindow[0]; 23215 startY = offsetInWindow[1]; 23216 } 23217 23218 if (consumed == null) { 23219 if (mTempNestedScrollConsumed == null) { 23220 mTempNestedScrollConsumed = new int[2]; 23221 } 23222 consumed = mTempNestedScrollConsumed; 23223 } 23224 consumed[0] = 0; 23225 consumed[1] = 0; 23226 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 23227 23228 if (offsetInWindow != null) { 23229 getLocationInWindow(offsetInWindow); 23230 offsetInWindow[0] -= startX; 23231 offsetInWindow[1] -= startY; 23232 } 23233 return consumed[0] != 0 || consumed[1] != 0; 23234 } else if (offsetInWindow != null) { 23235 offsetInWindow[0] = 0; 23236 offsetInWindow[1] = 0; 23237 } 23238 } 23239 return false; 23240 } 23241 23242 /** 23243 * Dispatch a fling to a nested scrolling parent. 23244 * 23245 * <p>This method should be used to indicate that a nested scrolling child has detected 23246 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 23247 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 23248 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 23249 * along a scrollable axis.</p> 23250 * 23251 * <p>If a nested scrolling child view would normally fling but it is at the edge of 23252 * its own content, it can use this method to delegate the fling to its nested scrolling 23253 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 23254 * 23255 * @param velocityX Horizontal fling velocity in pixels per second 23256 * @param velocityY Vertical fling velocity in pixels per second 23257 * @param consumed true if the child consumed the fling, false otherwise 23258 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 23259 */ 23260 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 23261 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23262 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 23263 } 23264 return false; 23265 } 23266 23267 /** 23268 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 23269 * 23270 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 23271 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 23272 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 23273 * before the child view consumes it. If this method returns <code>true</code>, a nested 23274 * parent view consumed the fling and this view should not scroll as a result.</p> 23275 * 23276 * <p>For a better user experience, only one view in a nested scrolling chain should consume 23277 * the fling at a time. If a parent view consumed the fling this method will return false. 23278 * Custom view implementations should account for this in two ways:</p> 23279 * 23280 * <ul> 23281 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 23282 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 23283 * position regardless.</li> 23284 * <li>If a nested parent does consume the fling, this view should not scroll at all, 23285 * even to settle back to a valid idle position.</li> 23286 * </ul> 23287 * 23288 * <p>Views should also not offer fling velocities to nested parent views along an axis 23289 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 23290 * should not offer a horizontal fling velocity to its parents since scrolling along that 23291 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 23292 * 23293 * @param velocityX Horizontal fling velocity in pixels per second 23294 * @param velocityY Vertical fling velocity in pixels per second 23295 * @return true if a nested scrolling parent consumed the fling 23296 */ 23297 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 23298 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23299 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 23300 } 23301 return false; 23302 } 23303 23304 /** 23305 * Gets a scale factor that determines the distance the view should scroll 23306 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 23307 * @return The vertical scroll scale factor. 23308 * @hide 23309 */ 23310 protected float getVerticalScrollFactor() { 23311 if (mVerticalScrollFactor == 0) { 23312 TypedValue outValue = new TypedValue(); 23313 if (!mContext.getTheme().resolveAttribute( 23314 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 23315 throw new IllegalStateException( 23316 "Expected theme to define listPreferredItemHeight."); 23317 } 23318 mVerticalScrollFactor = outValue.getDimension( 23319 mContext.getResources().getDisplayMetrics()); 23320 } 23321 return mVerticalScrollFactor; 23322 } 23323 23324 /** 23325 * Gets a scale factor that determines the distance the view should scroll 23326 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 23327 * @return The horizontal scroll scale factor. 23328 * @hide 23329 */ 23330 protected float getHorizontalScrollFactor() { 23331 // TODO: Should use something else. 23332 return getVerticalScrollFactor(); 23333 } 23334 23335 /** 23336 * Return the value specifying the text direction or policy that was set with 23337 * {@link #setTextDirection(int)}. 23338 * 23339 * @return the defined text direction. It can be one of: 23340 * 23341 * {@link #TEXT_DIRECTION_INHERIT}, 23342 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23343 * {@link #TEXT_DIRECTION_ANY_RTL}, 23344 * {@link #TEXT_DIRECTION_LTR}, 23345 * {@link #TEXT_DIRECTION_RTL}, 23346 * {@link #TEXT_DIRECTION_LOCALE}, 23347 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23348 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23349 * 23350 * @attr ref android.R.styleable#View_textDirection 23351 * 23352 * @hide 23353 */ 23354 @ViewDebug.ExportedProperty(category = "text", mapping = { 23355 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23356 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23357 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23358 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23359 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23360 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23361 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23362 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23363 }) 23364 public int getRawTextDirection() { 23365 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 23366 } 23367 23368 /** 23369 * Set the text direction. 23370 * 23371 * @param textDirection the direction to set. Should be one of: 23372 * 23373 * {@link #TEXT_DIRECTION_INHERIT}, 23374 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23375 * {@link #TEXT_DIRECTION_ANY_RTL}, 23376 * {@link #TEXT_DIRECTION_LTR}, 23377 * {@link #TEXT_DIRECTION_RTL}, 23378 * {@link #TEXT_DIRECTION_LOCALE} 23379 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23380 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 23381 * 23382 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 23383 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 23384 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 23385 * 23386 * @attr ref android.R.styleable#View_textDirection 23387 */ 23388 public void setTextDirection(int textDirection) { 23389 if (getRawTextDirection() != textDirection) { 23390 // Reset the current text direction and the resolved one 23391 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 23392 resetResolvedTextDirection(); 23393 // Set the new text direction 23394 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 23395 // Do resolution 23396 resolveTextDirection(); 23397 // Notify change 23398 onRtlPropertiesChanged(getLayoutDirection()); 23399 // Refresh 23400 requestLayout(); 23401 invalidate(true); 23402 } 23403 } 23404 23405 /** 23406 * Return the resolved text direction. 23407 * 23408 * @return the resolved text direction. Returns one of: 23409 * 23410 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23411 * {@link #TEXT_DIRECTION_ANY_RTL}, 23412 * {@link #TEXT_DIRECTION_LTR}, 23413 * {@link #TEXT_DIRECTION_RTL}, 23414 * {@link #TEXT_DIRECTION_LOCALE}, 23415 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23416 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23417 * 23418 * @attr ref android.R.styleable#View_textDirection 23419 */ 23420 @ViewDebug.ExportedProperty(category = "text", mapping = { 23421 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23422 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23423 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23424 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23425 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23426 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23427 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23428 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23429 }) 23430 public int getTextDirection() { 23431 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 23432 } 23433 23434 /** 23435 * Resolve the text direction. 23436 * 23437 * @return true if resolution has been done, false otherwise. 23438 * 23439 * @hide 23440 */ 23441 public boolean resolveTextDirection() { 23442 // Reset any previous text direction resolution 23443 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23444 23445 if (hasRtlSupport()) { 23446 // Set resolved text direction flag depending on text direction flag 23447 final int textDirection = getRawTextDirection(); 23448 switch(textDirection) { 23449 case TEXT_DIRECTION_INHERIT: 23450 if (!canResolveTextDirection()) { 23451 // We cannot do the resolution if there is no parent, so use the default one 23452 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23453 // Resolution will need to happen again later 23454 return false; 23455 } 23456 23457 // Parent has not yet resolved, so we still return the default 23458 try { 23459 if (!mParent.isTextDirectionResolved()) { 23460 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23461 // Resolution will need to happen again later 23462 return false; 23463 } 23464 } catch (AbstractMethodError e) { 23465 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23466 " does not fully implement ViewParent", e); 23467 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 23468 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23469 return true; 23470 } 23471 23472 // Set current resolved direction to the same value as the parent's one 23473 int parentResolvedDirection; 23474 try { 23475 parentResolvedDirection = mParent.getTextDirection(); 23476 } catch (AbstractMethodError e) { 23477 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23478 " does not fully implement ViewParent", e); 23479 parentResolvedDirection = TEXT_DIRECTION_LTR; 23480 } 23481 switch (parentResolvedDirection) { 23482 case TEXT_DIRECTION_FIRST_STRONG: 23483 case TEXT_DIRECTION_ANY_RTL: 23484 case TEXT_DIRECTION_LTR: 23485 case TEXT_DIRECTION_RTL: 23486 case TEXT_DIRECTION_LOCALE: 23487 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23488 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23489 mPrivateFlags2 |= 23490 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23491 break; 23492 default: 23493 // Default resolved direction is "first strong" heuristic 23494 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23495 } 23496 break; 23497 case TEXT_DIRECTION_FIRST_STRONG: 23498 case TEXT_DIRECTION_ANY_RTL: 23499 case TEXT_DIRECTION_LTR: 23500 case TEXT_DIRECTION_RTL: 23501 case TEXT_DIRECTION_LOCALE: 23502 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23503 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23504 // Resolved direction is the same as text direction 23505 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23506 break; 23507 default: 23508 // Default resolved direction is "first strong" heuristic 23509 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23510 } 23511 } else { 23512 // Default resolved direction is "first strong" heuristic 23513 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23514 } 23515 23516 // Set to resolved 23517 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 23518 return true; 23519 } 23520 23521 /** 23522 * Check if text direction resolution can be done. 23523 * 23524 * @return true if text direction resolution can be done otherwise return false. 23525 */ 23526 public boolean canResolveTextDirection() { 23527 switch (getRawTextDirection()) { 23528 case TEXT_DIRECTION_INHERIT: 23529 if (mParent != null) { 23530 try { 23531 return mParent.canResolveTextDirection(); 23532 } catch (AbstractMethodError e) { 23533 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23534 " does not fully implement ViewParent", e); 23535 } 23536 } 23537 return false; 23538 23539 default: 23540 return true; 23541 } 23542 } 23543 23544 /** 23545 * Reset resolved text direction. Text direction will be resolved during a call to 23546 * {@link #onMeasure(int, int)}. 23547 * 23548 * @hide 23549 */ 23550 public void resetResolvedTextDirection() { 23551 // Reset any previous text direction resolution 23552 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23553 // Set to default value 23554 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23555 } 23556 23557 /** 23558 * @return true if text direction is inherited. 23559 * 23560 * @hide 23561 */ 23562 public boolean isTextDirectionInherited() { 23563 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 23564 } 23565 23566 /** 23567 * @return true if text direction is resolved. 23568 */ 23569 public boolean isTextDirectionResolved() { 23570 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 23571 } 23572 23573 /** 23574 * Return the value specifying the text alignment or policy that was set with 23575 * {@link #setTextAlignment(int)}. 23576 * 23577 * @return the defined text alignment. It can be one of: 23578 * 23579 * {@link #TEXT_ALIGNMENT_INHERIT}, 23580 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23581 * {@link #TEXT_ALIGNMENT_CENTER}, 23582 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23583 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23584 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23585 * {@link #TEXT_ALIGNMENT_VIEW_END} 23586 * 23587 * @attr ref android.R.styleable#View_textAlignment 23588 * 23589 * @hide 23590 */ 23591 @ViewDebug.ExportedProperty(category = "text", mapping = { 23592 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23593 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23594 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23595 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23596 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23597 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23598 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23599 }) 23600 @TextAlignment 23601 public int getRawTextAlignment() { 23602 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 23603 } 23604 23605 /** 23606 * Set the text alignment. 23607 * 23608 * @param textAlignment The text alignment to set. Should be one of 23609 * 23610 * {@link #TEXT_ALIGNMENT_INHERIT}, 23611 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23612 * {@link #TEXT_ALIGNMENT_CENTER}, 23613 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23614 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23615 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23616 * {@link #TEXT_ALIGNMENT_VIEW_END} 23617 * 23618 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 23619 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 23620 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 23621 * 23622 * @attr ref android.R.styleable#View_textAlignment 23623 */ 23624 public void setTextAlignment(@TextAlignment int textAlignment) { 23625 if (textAlignment != getRawTextAlignment()) { 23626 // Reset the current and resolved text alignment 23627 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 23628 resetResolvedTextAlignment(); 23629 // Set the new text alignment 23630 mPrivateFlags2 |= 23631 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 23632 // Do resolution 23633 resolveTextAlignment(); 23634 // Notify change 23635 onRtlPropertiesChanged(getLayoutDirection()); 23636 // Refresh 23637 requestLayout(); 23638 invalidate(true); 23639 } 23640 } 23641 23642 /** 23643 * Return the resolved text alignment. 23644 * 23645 * @return the resolved text alignment. Returns one of: 23646 * 23647 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23648 * {@link #TEXT_ALIGNMENT_CENTER}, 23649 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23650 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23651 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23652 * {@link #TEXT_ALIGNMENT_VIEW_END} 23653 * 23654 * @attr ref android.R.styleable#View_textAlignment 23655 */ 23656 @ViewDebug.ExportedProperty(category = "text", mapping = { 23657 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23658 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23659 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23660 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23661 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23662 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23663 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23664 }) 23665 @TextAlignment 23666 public int getTextAlignment() { 23667 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 23668 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 23669 } 23670 23671 /** 23672 * Resolve the text alignment. 23673 * 23674 * @return true if resolution has been done, false otherwise. 23675 * 23676 * @hide 23677 */ 23678 public boolean resolveTextAlignment() { 23679 // Reset any previous text alignment resolution 23680 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23681 23682 if (hasRtlSupport()) { 23683 // Set resolved text alignment flag depending on text alignment flag 23684 final int textAlignment = getRawTextAlignment(); 23685 switch (textAlignment) { 23686 case TEXT_ALIGNMENT_INHERIT: 23687 // Check if we can resolve the text alignment 23688 if (!canResolveTextAlignment()) { 23689 // We cannot do the resolution if there is no parent so use the default 23690 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23691 // Resolution will need to happen again later 23692 return false; 23693 } 23694 23695 // Parent has not yet resolved, so we still return the default 23696 try { 23697 if (!mParent.isTextAlignmentResolved()) { 23698 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23699 // Resolution will need to happen again later 23700 return false; 23701 } 23702 } catch (AbstractMethodError e) { 23703 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23704 " does not fully implement ViewParent", e); 23705 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 23706 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23707 return true; 23708 } 23709 23710 int parentResolvedTextAlignment; 23711 try { 23712 parentResolvedTextAlignment = mParent.getTextAlignment(); 23713 } catch (AbstractMethodError e) { 23714 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23715 " does not fully implement ViewParent", e); 23716 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 23717 } 23718 switch (parentResolvedTextAlignment) { 23719 case TEXT_ALIGNMENT_GRAVITY: 23720 case TEXT_ALIGNMENT_TEXT_START: 23721 case TEXT_ALIGNMENT_TEXT_END: 23722 case TEXT_ALIGNMENT_CENTER: 23723 case TEXT_ALIGNMENT_VIEW_START: 23724 case TEXT_ALIGNMENT_VIEW_END: 23725 // Resolved text alignment is the same as the parent resolved 23726 // text alignment 23727 mPrivateFlags2 |= 23728 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23729 break; 23730 default: 23731 // Use default resolved text alignment 23732 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23733 } 23734 break; 23735 case TEXT_ALIGNMENT_GRAVITY: 23736 case TEXT_ALIGNMENT_TEXT_START: 23737 case TEXT_ALIGNMENT_TEXT_END: 23738 case TEXT_ALIGNMENT_CENTER: 23739 case TEXT_ALIGNMENT_VIEW_START: 23740 case TEXT_ALIGNMENT_VIEW_END: 23741 // Resolved text alignment is the same as text alignment 23742 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23743 break; 23744 default: 23745 // Use default resolved text alignment 23746 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23747 } 23748 } else { 23749 // Use default resolved text alignment 23750 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23751 } 23752 23753 // Set the resolved 23754 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23755 return true; 23756 } 23757 23758 /** 23759 * Check if text alignment resolution can be done. 23760 * 23761 * @return true if text alignment resolution can be done otherwise return false. 23762 */ 23763 public boolean canResolveTextAlignment() { 23764 switch (getRawTextAlignment()) { 23765 case TEXT_DIRECTION_INHERIT: 23766 if (mParent != null) { 23767 try { 23768 return mParent.canResolveTextAlignment(); 23769 } catch (AbstractMethodError e) { 23770 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23771 " does not fully implement ViewParent", e); 23772 } 23773 } 23774 return false; 23775 23776 default: 23777 return true; 23778 } 23779 } 23780 23781 /** 23782 * Reset resolved text alignment. Text alignment will be resolved during a call to 23783 * {@link #onMeasure(int, int)}. 23784 * 23785 * @hide 23786 */ 23787 public void resetResolvedTextAlignment() { 23788 // Reset any previous text alignment resolution 23789 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23790 // Set to default 23791 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23792 } 23793 23794 /** 23795 * @return true if text alignment is inherited. 23796 * 23797 * @hide 23798 */ 23799 public boolean isTextAlignmentInherited() { 23800 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 23801 } 23802 23803 /** 23804 * @return true if text alignment is resolved. 23805 */ 23806 public boolean isTextAlignmentResolved() { 23807 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23808 } 23809 23810 /** 23811 * Generate a value suitable for use in {@link #setId(int)}. 23812 * This value will not collide with ID values generated at build time by aapt for R.id. 23813 * 23814 * @return a generated ID value 23815 */ 23816 public static int generateViewId() { 23817 for (;;) { 23818 final int result = sNextGeneratedId.get(); 23819 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 23820 int newValue = result + 1; 23821 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 23822 if (sNextGeneratedId.compareAndSet(result, newValue)) { 23823 return result; 23824 } 23825 } 23826 } 23827 23828 private static boolean isViewIdGenerated(int id) { 23829 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0; 23830 } 23831 23832 /** 23833 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 23834 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 23835 * a normal View or a ViewGroup with 23836 * {@link android.view.ViewGroup#isTransitionGroup()} true. 23837 * @hide 23838 */ 23839 public void captureTransitioningViews(List<View> transitioningViews) { 23840 if (getVisibility() == View.VISIBLE) { 23841 transitioningViews.add(this); 23842 } 23843 } 23844 23845 /** 23846 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 23847 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 23848 * @hide 23849 */ 23850 public void findNamedViews(Map<String, View> namedElements) { 23851 if (getVisibility() == VISIBLE || mGhostView != null) { 23852 String transitionName = getTransitionName(); 23853 if (transitionName != null) { 23854 namedElements.put(transitionName, this); 23855 } 23856 } 23857 } 23858 23859 /** 23860 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 23861 * The default implementation does not care the location or event types, but some subclasses 23862 * may use it (such as WebViews). 23863 * @param event The MotionEvent from a mouse 23864 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 23865 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 23866 * @see PointerIcon 23867 */ 23868 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 23869 final float x = event.getX(pointerIndex); 23870 final float y = event.getY(pointerIndex); 23871 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 23872 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 23873 } 23874 return mPointerIcon; 23875 } 23876 23877 /** 23878 * Set the pointer icon for the current view. 23879 * Passing {@code null} will restore the pointer icon to its default value. 23880 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 23881 */ 23882 public void setPointerIcon(PointerIcon pointerIcon) { 23883 mPointerIcon = pointerIcon; 23884 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 23885 return; 23886 } 23887 try { 23888 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 23889 } catch (RemoteException e) { 23890 } 23891 } 23892 23893 /** 23894 * Gets the pointer icon for the current view. 23895 */ 23896 public PointerIcon getPointerIcon() { 23897 return mPointerIcon; 23898 } 23899 23900 /** 23901 * Checks pointer capture status. 23902 * 23903 * @return true if the view has pointer capture. 23904 * @see #requestPointerCapture() 23905 * @see #hasPointerCapture() 23906 */ 23907 public boolean hasPointerCapture() { 23908 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23909 if (viewRootImpl == null) { 23910 return false; 23911 } 23912 return viewRootImpl.hasPointerCapture(); 23913 } 23914 23915 /** 23916 * Requests pointer capture mode. 23917 * <p> 23918 * When the window has pointer capture, the mouse pointer icon will disappear and will not 23919 * change its position. Further mouse will be dispatched with the source 23920 * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available 23921 * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events 23922 * (touchscreens, or stylus) will not be affected. 23923 * <p> 23924 * If the window already has pointer capture, this call does nothing. 23925 * <p> 23926 * The capture may be released through {@link #releasePointerCapture()}, or will be lost 23927 * automatically when the window loses focus. 23928 * 23929 * @see #releasePointerCapture() 23930 * @see #hasPointerCapture() 23931 */ 23932 public void requestPointerCapture() { 23933 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23934 if (viewRootImpl != null) { 23935 viewRootImpl.requestPointerCapture(true); 23936 } 23937 } 23938 23939 23940 /** 23941 * Releases the pointer capture. 23942 * <p> 23943 * If the window does not have pointer capture, this call will do nothing. 23944 * @see #requestPointerCapture() 23945 * @see #hasPointerCapture() 23946 */ 23947 public void releasePointerCapture() { 23948 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23949 if (viewRootImpl != null) { 23950 viewRootImpl.requestPointerCapture(false); 23951 } 23952 } 23953 23954 /** 23955 * Called when the window has just acquired or lost pointer capture. 23956 * 23957 * @param hasCapture True if the view now has pointerCapture, false otherwise. 23958 */ 23959 @CallSuper 23960 public void onPointerCaptureChange(boolean hasCapture) { 23961 } 23962 23963 /** 23964 * @see #onPointerCaptureChange 23965 */ 23966 public void dispatchPointerCaptureChanged(boolean hasCapture) { 23967 onPointerCaptureChange(hasCapture); 23968 } 23969 23970 /** 23971 * Implement this method to handle captured pointer events 23972 * 23973 * @param event The captured pointer event. 23974 * @return True if the event was handled, false otherwise. 23975 * @see #requestPointerCapture() 23976 */ 23977 public boolean onCapturedPointerEvent(MotionEvent event) { 23978 return false; 23979 } 23980 23981 /** 23982 * Interface definition for a callback to be invoked when a captured pointer event 23983 * is being dispatched this view. The callback will be invoked before the event is 23984 * given to the view. 23985 */ 23986 public interface OnCapturedPointerListener { 23987 /** 23988 * Called when a captured pointer event is dispatched to a view. 23989 * @param view The view this event has been dispatched to. 23990 * @param event The captured event. 23991 * @return True if the listener has consumed the event, false otherwise. 23992 */ 23993 boolean onCapturedPointer(View view, MotionEvent event); 23994 } 23995 23996 /** 23997 * Set a listener to receive callbacks when the pointer capture state of a view changes. 23998 * @param l The {@link OnCapturedPointerListener} to receive callbacks. 23999 */ 24000 public void setOnCapturedPointerListener(OnCapturedPointerListener l) { 24001 getListenerInfo().mOnCapturedPointerListener = l; 24002 } 24003 24004 // Properties 24005 // 24006 /** 24007 * A Property wrapper around the <code>alpha</code> functionality handled by the 24008 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 24009 */ 24010 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 24011 @Override 24012 public void setValue(View object, float value) { 24013 object.setAlpha(value); 24014 } 24015 24016 @Override 24017 public Float get(View object) { 24018 return object.getAlpha(); 24019 } 24020 }; 24021 24022 /** 24023 * A Property wrapper around the <code>translationX</code> functionality handled by the 24024 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 24025 */ 24026 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 24027 @Override 24028 public void setValue(View object, float value) { 24029 object.setTranslationX(value); 24030 } 24031 24032 @Override 24033 public Float get(View object) { 24034 return object.getTranslationX(); 24035 } 24036 }; 24037 24038 /** 24039 * A Property wrapper around the <code>translationY</code> functionality handled by the 24040 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 24041 */ 24042 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 24043 @Override 24044 public void setValue(View object, float value) { 24045 object.setTranslationY(value); 24046 } 24047 24048 @Override 24049 public Float get(View object) { 24050 return object.getTranslationY(); 24051 } 24052 }; 24053 24054 /** 24055 * A Property wrapper around the <code>translationZ</code> functionality handled by the 24056 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 24057 */ 24058 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 24059 @Override 24060 public void setValue(View object, float value) { 24061 object.setTranslationZ(value); 24062 } 24063 24064 @Override 24065 public Float get(View object) { 24066 return object.getTranslationZ(); 24067 } 24068 }; 24069 24070 /** 24071 * A Property wrapper around the <code>x</code> functionality handled by the 24072 * {@link View#setX(float)} and {@link View#getX()} methods. 24073 */ 24074 public static final Property<View, Float> X = new FloatProperty<View>("x") { 24075 @Override 24076 public void setValue(View object, float value) { 24077 object.setX(value); 24078 } 24079 24080 @Override 24081 public Float get(View object) { 24082 return object.getX(); 24083 } 24084 }; 24085 24086 /** 24087 * A Property wrapper around the <code>y</code> functionality handled by the 24088 * {@link View#setY(float)} and {@link View#getY()} methods. 24089 */ 24090 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 24091 @Override 24092 public void setValue(View object, float value) { 24093 object.setY(value); 24094 } 24095 24096 @Override 24097 public Float get(View object) { 24098 return object.getY(); 24099 } 24100 }; 24101 24102 /** 24103 * A Property wrapper around the <code>z</code> functionality handled by the 24104 * {@link View#setZ(float)} and {@link View#getZ()} methods. 24105 */ 24106 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 24107 @Override 24108 public void setValue(View object, float value) { 24109 object.setZ(value); 24110 } 24111 24112 @Override 24113 public Float get(View object) { 24114 return object.getZ(); 24115 } 24116 }; 24117 24118 /** 24119 * A Property wrapper around the <code>rotation</code> functionality handled by the 24120 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 24121 */ 24122 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 24123 @Override 24124 public void setValue(View object, float value) { 24125 object.setRotation(value); 24126 } 24127 24128 @Override 24129 public Float get(View object) { 24130 return object.getRotation(); 24131 } 24132 }; 24133 24134 /** 24135 * A Property wrapper around the <code>rotationX</code> functionality handled by the 24136 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 24137 */ 24138 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 24139 @Override 24140 public void setValue(View object, float value) { 24141 object.setRotationX(value); 24142 } 24143 24144 @Override 24145 public Float get(View object) { 24146 return object.getRotationX(); 24147 } 24148 }; 24149 24150 /** 24151 * A Property wrapper around the <code>rotationY</code> functionality handled by the 24152 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 24153 */ 24154 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 24155 @Override 24156 public void setValue(View object, float value) { 24157 object.setRotationY(value); 24158 } 24159 24160 @Override 24161 public Float get(View object) { 24162 return object.getRotationY(); 24163 } 24164 }; 24165 24166 /** 24167 * A Property wrapper around the <code>scaleX</code> functionality handled by the 24168 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 24169 */ 24170 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 24171 @Override 24172 public void setValue(View object, float value) { 24173 object.setScaleX(value); 24174 } 24175 24176 @Override 24177 public Float get(View object) { 24178 return object.getScaleX(); 24179 } 24180 }; 24181 24182 /** 24183 * A Property wrapper around the <code>scaleY</code> functionality handled by the 24184 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 24185 */ 24186 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 24187 @Override 24188 public void setValue(View object, float value) { 24189 object.setScaleY(value); 24190 } 24191 24192 @Override 24193 public Float get(View object) { 24194 return object.getScaleY(); 24195 } 24196 }; 24197 24198 /** 24199 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 24200 * Each MeasureSpec represents a requirement for either the width or the height. 24201 * A MeasureSpec is comprised of a size and a mode. There are three possible 24202 * modes: 24203 * <dl> 24204 * <dt>UNSPECIFIED</dt> 24205 * <dd> 24206 * The parent has not imposed any constraint on the child. It can be whatever size 24207 * it wants. 24208 * </dd> 24209 * 24210 * <dt>EXACTLY</dt> 24211 * <dd> 24212 * The parent has determined an exact size for the child. The child is going to be 24213 * given those bounds regardless of how big it wants to be. 24214 * </dd> 24215 * 24216 * <dt>AT_MOST</dt> 24217 * <dd> 24218 * The child can be as large as it wants up to the specified size. 24219 * </dd> 24220 * </dl> 24221 * 24222 * MeasureSpecs are implemented as ints to reduce object allocation. This class 24223 * is provided to pack and unpack the <size, mode> tuple into the int. 24224 */ 24225 public static class MeasureSpec { 24226 private static final int MODE_SHIFT = 30; 24227 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 24228 24229 /** @hide */ 24230 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 24231 @Retention(RetentionPolicy.SOURCE) 24232 public @interface MeasureSpecMode {} 24233 24234 /** 24235 * Measure specification mode: The parent has not imposed any constraint 24236 * on the child. It can be whatever size it wants. 24237 */ 24238 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 24239 24240 /** 24241 * Measure specification mode: The parent has determined an exact size 24242 * for the child. The child is going to be given those bounds regardless 24243 * of how big it wants to be. 24244 */ 24245 public static final int EXACTLY = 1 << MODE_SHIFT; 24246 24247 /** 24248 * Measure specification mode: The child can be as large as it wants up 24249 * to the specified size. 24250 */ 24251 public static final int AT_MOST = 2 << MODE_SHIFT; 24252 24253 /** 24254 * Creates a measure specification based on the supplied size and mode. 24255 * 24256 * The mode must always be one of the following: 24257 * <ul> 24258 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 24259 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 24260 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 24261 * </ul> 24262 * 24263 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 24264 * implementation was such that the order of arguments did not matter 24265 * and overflow in either value could impact the resulting MeasureSpec. 24266 * {@link android.widget.RelativeLayout} was affected by this bug. 24267 * Apps targeting API levels greater than 17 will get the fixed, more strict 24268 * behavior.</p> 24269 * 24270 * @param size the size of the measure specification 24271 * @param mode the mode of the measure specification 24272 * @return the measure specification based on size and mode 24273 */ 24274 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 24275 @MeasureSpecMode int mode) { 24276 if (sUseBrokenMakeMeasureSpec) { 24277 return size + mode; 24278 } else { 24279 return (size & ~MODE_MASK) | (mode & MODE_MASK); 24280 } 24281 } 24282 24283 /** 24284 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 24285 * will automatically get a size of 0. Older apps expect this. 24286 * 24287 * @hide internal use only for compatibility with system widgets and older apps 24288 */ 24289 public static int makeSafeMeasureSpec(int size, int mode) { 24290 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 24291 return 0; 24292 } 24293 return makeMeasureSpec(size, mode); 24294 } 24295 24296 /** 24297 * Extracts the mode from the supplied measure specification. 24298 * 24299 * @param measureSpec the measure specification to extract the mode from 24300 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 24301 * {@link android.view.View.MeasureSpec#AT_MOST} or 24302 * {@link android.view.View.MeasureSpec#EXACTLY} 24303 */ 24304 @MeasureSpecMode 24305 public static int getMode(int measureSpec) { 24306 //noinspection ResourceType 24307 return (measureSpec & MODE_MASK); 24308 } 24309 24310 /** 24311 * Extracts the size from the supplied measure specification. 24312 * 24313 * @param measureSpec the measure specification to extract the size from 24314 * @return the size in pixels defined in the supplied measure specification 24315 */ 24316 public static int getSize(int measureSpec) { 24317 return (measureSpec & ~MODE_MASK); 24318 } 24319 24320 static int adjust(int measureSpec, int delta) { 24321 final int mode = getMode(measureSpec); 24322 int size = getSize(measureSpec); 24323 if (mode == UNSPECIFIED) { 24324 // No need to adjust size for UNSPECIFIED mode. 24325 return makeMeasureSpec(size, UNSPECIFIED); 24326 } 24327 size += delta; 24328 if (size < 0) { 24329 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 24330 ") spec: " + toString(measureSpec) + " delta: " + delta); 24331 size = 0; 24332 } 24333 return makeMeasureSpec(size, mode); 24334 } 24335 24336 /** 24337 * Returns a String representation of the specified measure 24338 * specification. 24339 * 24340 * @param measureSpec the measure specification to convert to a String 24341 * @return a String with the following format: "MeasureSpec: MODE SIZE" 24342 */ 24343 public static String toString(int measureSpec) { 24344 int mode = getMode(measureSpec); 24345 int size = getSize(measureSpec); 24346 24347 StringBuilder sb = new StringBuilder("MeasureSpec: "); 24348 24349 if (mode == UNSPECIFIED) 24350 sb.append("UNSPECIFIED "); 24351 else if (mode == EXACTLY) 24352 sb.append("EXACTLY "); 24353 else if (mode == AT_MOST) 24354 sb.append("AT_MOST "); 24355 else 24356 sb.append(mode).append(" "); 24357 24358 sb.append(size); 24359 return sb.toString(); 24360 } 24361 } 24362 24363 private final class CheckForLongPress implements Runnable { 24364 private int mOriginalWindowAttachCount; 24365 private float mX; 24366 private float mY; 24367 private boolean mOriginalPressedState; 24368 24369 @Override 24370 public void run() { 24371 if ((mOriginalPressedState == isPressed()) && (mParent != null) 24372 && mOriginalWindowAttachCount == mWindowAttachCount) { 24373 if (performLongClick(mX, mY)) { 24374 mHasPerformedLongPress = true; 24375 } 24376 } 24377 } 24378 24379 public void setAnchor(float x, float y) { 24380 mX = x; 24381 mY = y; 24382 } 24383 24384 public void rememberWindowAttachCount() { 24385 mOriginalWindowAttachCount = mWindowAttachCount; 24386 } 24387 24388 public void rememberPressedState() { 24389 mOriginalPressedState = isPressed(); 24390 } 24391 } 24392 24393 private final class CheckForTap implements Runnable { 24394 public float x; 24395 public float y; 24396 24397 @Override 24398 public void run() { 24399 mPrivateFlags &= ~PFLAG_PREPRESSED; 24400 setPressed(true, x, y); 24401 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 24402 } 24403 } 24404 24405 private final class PerformClick implements Runnable { 24406 @Override 24407 public void run() { 24408 performClick(); 24409 } 24410 } 24411 24412 /** 24413 * This method returns a ViewPropertyAnimator object, which can be used to animate 24414 * specific properties on this View. 24415 * 24416 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 24417 */ 24418 public ViewPropertyAnimator animate() { 24419 if (mAnimator == null) { 24420 mAnimator = new ViewPropertyAnimator(this); 24421 } 24422 return mAnimator; 24423 } 24424 24425 /** 24426 * Sets the name of the View to be used to identify Views in Transitions. 24427 * Names should be unique in the View hierarchy. 24428 * 24429 * @param transitionName The name of the View to uniquely identify it for Transitions. 24430 */ 24431 public final void setTransitionName(String transitionName) { 24432 mTransitionName = transitionName; 24433 } 24434 24435 /** 24436 * Returns the name of the View to be used to identify Views in Transitions. 24437 * Names should be unique in the View hierarchy. 24438 * 24439 * <p>This returns null if the View has not been given a name.</p> 24440 * 24441 * @return The name used of the View to be used to identify Views in Transitions or null 24442 * if no name has been given. 24443 */ 24444 @ViewDebug.ExportedProperty 24445 public String getTransitionName() { 24446 return mTransitionName; 24447 } 24448 24449 /** 24450 * @hide 24451 */ 24452 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 24453 // Do nothing. 24454 } 24455 24456 /** 24457 * Interface definition for a callback to be invoked when a hardware key event is 24458 * dispatched to this view. The callback will be invoked before the key event is 24459 * given to the view. This is only useful for hardware keyboards; a software input 24460 * method has no obligation to trigger this listener. 24461 */ 24462 public interface OnKeyListener { 24463 /** 24464 * Called when a hardware key is dispatched to a view. This allows listeners to 24465 * get a chance to respond before the target view. 24466 * <p>Key presses in software keyboards will generally NOT trigger this method, 24467 * although some may elect to do so in some situations. Do not assume a 24468 * software input method has to be key-based; even if it is, it may use key presses 24469 * in a different way than you expect, so there is no way to reliably catch soft 24470 * input key presses. 24471 * 24472 * @param v The view the key has been dispatched to. 24473 * @param keyCode The code for the physical key that was pressed 24474 * @param event The KeyEvent object containing full information about 24475 * the event. 24476 * @return True if the listener has consumed the event, false otherwise. 24477 */ 24478 boolean onKey(View v, int keyCode, KeyEvent event); 24479 } 24480 24481 /** 24482 * Interface definition for a callback to be invoked when a touch event is 24483 * dispatched to this view. The callback will be invoked before the touch 24484 * event is given to the view. 24485 */ 24486 public interface OnTouchListener { 24487 /** 24488 * Called when a touch event is dispatched to a view. This allows listeners to 24489 * get a chance to respond before the target view. 24490 * 24491 * @param v The view the touch event has been dispatched to. 24492 * @param event The MotionEvent object containing full information about 24493 * the event. 24494 * @return True if the listener has consumed the event, false otherwise. 24495 */ 24496 boolean onTouch(View v, MotionEvent event); 24497 } 24498 24499 /** 24500 * Interface definition for a callback to be invoked when a hover event is 24501 * dispatched to this view. The callback will be invoked before the hover 24502 * event is given to the view. 24503 */ 24504 public interface OnHoverListener { 24505 /** 24506 * Called when a hover event is dispatched to a view. This allows listeners to 24507 * get a chance to respond before the target view. 24508 * 24509 * @param v The view the hover event has been dispatched to. 24510 * @param event The MotionEvent object containing full information about 24511 * the event. 24512 * @return True if the listener has consumed the event, false otherwise. 24513 */ 24514 boolean onHover(View v, MotionEvent event); 24515 } 24516 24517 /** 24518 * Interface definition for a callback to be invoked when a generic motion event is 24519 * dispatched to this view. The callback will be invoked before the generic motion 24520 * event is given to the view. 24521 */ 24522 public interface OnGenericMotionListener { 24523 /** 24524 * Called when a generic motion event is dispatched to a view. This allows listeners to 24525 * get a chance to respond before the target view. 24526 * 24527 * @param v The view the generic motion event has been dispatched to. 24528 * @param event The MotionEvent object containing full information about 24529 * the event. 24530 * @return True if the listener has consumed the event, false otherwise. 24531 */ 24532 boolean onGenericMotion(View v, MotionEvent event); 24533 } 24534 24535 /** 24536 * Interface definition for a callback to be invoked when a view has been clicked and held. 24537 */ 24538 public interface OnLongClickListener { 24539 /** 24540 * Called when a view has been clicked and held. 24541 * 24542 * @param v The view that was clicked and held. 24543 * 24544 * @return true if the callback consumed the long click, false otherwise. 24545 */ 24546 boolean onLongClick(View v); 24547 } 24548 24549 /** 24550 * Interface definition for a callback to be invoked when a drag is being dispatched 24551 * to this view. The callback will be invoked before the hosting view's own 24552 * onDrag(event) method. If the listener wants to fall back to the hosting view's 24553 * onDrag(event) behavior, it should return 'false' from this callback. 24554 * 24555 * <div class="special reference"> 24556 * <h3>Developer Guides</h3> 24557 * <p>For a guide to implementing drag and drop features, read the 24558 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 24559 * </div> 24560 */ 24561 public interface OnDragListener { 24562 /** 24563 * Called when a drag event is dispatched to a view. This allows listeners 24564 * to get a chance to override base View behavior. 24565 * 24566 * @param v The View that received the drag event. 24567 * @param event The {@link android.view.DragEvent} object for the drag event. 24568 * @return {@code true} if the drag event was handled successfully, or {@code false} 24569 * if the drag event was not handled. Note that {@code false} will trigger the View 24570 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 24571 */ 24572 boolean onDrag(View v, DragEvent event); 24573 } 24574 24575 /** 24576 * Interface definition for a callback to be invoked when the focus state of 24577 * a view changed. 24578 */ 24579 public interface OnFocusChangeListener { 24580 /** 24581 * Called when the focus state of a view has changed. 24582 * 24583 * @param v The view whose state has changed. 24584 * @param hasFocus The new focus state of v. 24585 */ 24586 void onFocusChange(View v, boolean hasFocus); 24587 } 24588 24589 /** 24590 * Interface definition for a callback to be invoked when a view is clicked. 24591 */ 24592 public interface OnClickListener { 24593 /** 24594 * Called when a view has been clicked. 24595 * 24596 * @param v The view that was clicked. 24597 */ 24598 void onClick(View v); 24599 } 24600 24601 /** 24602 * Interface definition for a callback to be invoked when a view is context clicked. 24603 */ 24604 public interface OnContextClickListener { 24605 /** 24606 * Called when a view is context clicked. 24607 * 24608 * @param v The view that has been context clicked. 24609 * @return true if the callback consumed the context click, false otherwise. 24610 */ 24611 boolean onContextClick(View v); 24612 } 24613 24614 /** 24615 * Interface definition for a callback to be invoked when the context menu 24616 * for this view is being built. 24617 */ 24618 public interface OnCreateContextMenuListener { 24619 /** 24620 * Called when the context menu for this view is being built. It is not 24621 * safe to hold onto the menu after this method returns. 24622 * 24623 * @param menu The context menu that is being built 24624 * @param v The view for which the context menu is being built 24625 * @param menuInfo Extra information about the item for which the 24626 * context menu should be shown. This information will vary 24627 * depending on the class of v. 24628 */ 24629 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 24630 } 24631 24632 /** 24633 * Interface definition for a callback to be invoked when the status bar changes 24634 * visibility. This reports <strong>global</strong> changes to the system UI 24635 * state, not what the application is requesting. 24636 * 24637 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 24638 */ 24639 public interface OnSystemUiVisibilityChangeListener { 24640 /** 24641 * Called when the status bar changes visibility because of a call to 24642 * {@link View#setSystemUiVisibility(int)}. 24643 * 24644 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 24645 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 24646 * This tells you the <strong>global</strong> state of these UI visibility 24647 * flags, not what your app is currently applying. 24648 */ 24649 public void onSystemUiVisibilityChange(int visibility); 24650 } 24651 24652 /** 24653 * Interface definition for a callback to be invoked when this view is attached 24654 * or detached from its window. 24655 */ 24656 public interface OnAttachStateChangeListener { 24657 /** 24658 * Called when the view is attached to a window. 24659 * @param v The view that was attached 24660 */ 24661 public void onViewAttachedToWindow(View v); 24662 /** 24663 * Called when the view is detached from a window. 24664 * @param v The view that was detached 24665 */ 24666 public void onViewDetachedFromWindow(View v); 24667 } 24668 24669 /** 24670 * Listener for applying window insets on a view in a custom way. 24671 * 24672 * <p>Apps may choose to implement this interface if they want to apply custom policy 24673 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 24674 * is set, its 24675 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 24676 * method will be called instead of the View's own 24677 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 24678 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 24679 * the View's normal behavior as part of its own.</p> 24680 */ 24681 public interface OnApplyWindowInsetsListener { 24682 /** 24683 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 24684 * on a View, this listener method will be called instead of the view's own 24685 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 24686 * 24687 * @param v The view applying window insets 24688 * @param insets The insets to apply 24689 * @return The insets supplied, minus any insets that were consumed 24690 */ 24691 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 24692 } 24693 24694 private final class UnsetPressedState implements Runnable { 24695 @Override 24696 public void run() { 24697 setPressed(false); 24698 } 24699 } 24700 24701 /** 24702 * When a view becomes invisible checks if autofill considers the view invisible too. This 24703 * happens after the regular removal operation to make sure the operation is finished by the 24704 * time this is called. 24705 */ 24706 private static class VisibilityChangeForAutofillHandler extends Handler { 24707 private final AutofillManager mAfm; 24708 private final View mView; 24709 24710 private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm, 24711 @NonNull View view) { 24712 mAfm = afm; 24713 mView = view; 24714 } 24715 24716 @Override 24717 public void handleMessage(Message msg) { 24718 mAfm.notifyViewVisibilityChange(mView, mView.isShown()); 24719 } 24720 } 24721 24722 /** 24723 * Base class for derived classes that want to save and restore their own 24724 * state in {@link android.view.View#onSaveInstanceState()}. 24725 */ 24726 public static class BaseSavedState extends AbsSavedState { 24727 static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1; 24728 static final int IS_AUTOFILLED = 0b10; 24729 static final int ACCESSIBILITY_ID = 0b100; 24730 24731 // Flags that describe what data in this state is valid 24732 int mSavedData; 24733 String mStartActivityRequestWhoSaved; 24734 boolean mIsAutofilled; 24735 int mAccessibilityViewId; 24736 24737 /** 24738 * Constructor used when reading from a parcel. Reads the state of the superclass. 24739 * 24740 * @param source parcel to read from 24741 */ 24742 public BaseSavedState(Parcel source) { 24743 this(source, null); 24744 } 24745 24746 /** 24747 * Constructor used when reading from a parcel using a given class loader. 24748 * Reads the state of the superclass. 24749 * 24750 * @param source parcel to read from 24751 * @param loader ClassLoader to use for reading 24752 */ 24753 public BaseSavedState(Parcel source, ClassLoader loader) { 24754 super(source, loader); 24755 mSavedData = source.readInt(); 24756 mStartActivityRequestWhoSaved = source.readString(); 24757 mIsAutofilled = source.readBoolean(); 24758 mAccessibilityViewId = source.readInt(); 24759 } 24760 24761 /** 24762 * Constructor called by derived classes when creating their SavedState objects 24763 * 24764 * @param superState The state of the superclass of this view 24765 */ 24766 public BaseSavedState(Parcelable superState) { 24767 super(superState); 24768 } 24769 24770 @Override 24771 public void writeToParcel(Parcel out, int flags) { 24772 super.writeToParcel(out, flags); 24773 24774 out.writeInt(mSavedData); 24775 out.writeString(mStartActivityRequestWhoSaved); 24776 out.writeBoolean(mIsAutofilled); 24777 out.writeInt(mAccessibilityViewId); 24778 } 24779 24780 public static final Parcelable.Creator<BaseSavedState> CREATOR 24781 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 24782 @Override 24783 public BaseSavedState createFromParcel(Parcel in) { 24784 return new BaseSavedState(in); 24785 } 24786 24787 @Override 24788 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 24789 return new BaseSavedState(in, loader); 24790 } 24791 24792 @Override 24793 public BaseSavedState[] newArray(int size) { 24794 return new BaseSavedState[size]; 24795 } 24796 }; 24797 } 24798 24799 /** 24800 * A set of information given to a view when it is attached to its parent 24801 * window. 24802 */ 24803 final static class AttachInfo { 24804 interface Callbacks { 24805 void playSoundEffect(int effectId); 24806 boolean performHapticFeedback(int effectId, boolean always); 24807 } 24808 24809 /** 24810 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 24811 * to a Handler. This class contains the target (View) to invalidate and 24812 * the coordinates of the dirty rectangle. 24813 * 24814 * For performance purposes, this class also implements a pool of up to 24815 * POOL_LIMIT objects that get reused. This reduces memory allocations 24816 * whenever possible. 24817 */ 24818 static class InvalidateInfo { 24819 private static final int POOL_LIMIT = 10; 24820 24821 private static final SynchronizedPool<InvalidateInfo> sPool = 24822 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 24823 24824 View target; 24825 24826 int left; 24827 int top; 24828 int right; 24829 int bottom; 24830 24831 public static InvalidateInfo obtain() { 24832 InvalidateInfo instance = sPool.acquire(); 24833 return (instance != null) ? instance : new InvalidateInfo(); 24834 } 24835 24836 public void recycle() { 24837 target = null; 24838 sPool.release(this); 24839 } 24840 } 24841 24842 final IWindowSession mSession; 24843 24844 final IWindow mWindow; 24845 24846 final IBinder mWindowToken; 24847 24848 Display mDisplay; 24849 24850 final Callbacks mRootCallbacks; 24851 24852 IWindowId mIWindowId; 24853 WindowId mWindowId; 24854 24855 /** 24856 * The top view of the hierarchy. 24857 */ 24858 View mRootView; 24859 24860 IBinder mPanelParentWindowToken; 24861 24862 boolean mHardwareAccelerated; 24863 boolean mHardwareAccelerationRequested; 24864 ThreadedRenderer mThreadedRenderer; 24865 List<RenderNode> mPendingAnimatingRenderNodes; 24866 24867 /** 24868 * The state of the display to which the window is attached, as reported 24869 * by {@link Display#getState()}. Note that the display state constants 24870 * declared by {@link Display} do not exactly line up with the screen state 24871 * constants declared by {@link View} (there are more display states than 24872 * screen states). 24873 */ 24874 int mDisplayState = Display.STATE_UNKNOWN; 24875 24876 /** 24877 * Scale factor used by the compatibility mode 24878 */ 24879 float mApplicationScale; 24880 24881 /** 24882 * Indicates whether the application is in compatibility mode 24883 */ 24884 boolean mScalingRequired; 24885 24886 /** 24887 * Left position of this view's window 24888 */ 24889 int mWindowLeft; 24890 24891 /** 24892 * Top position of this view's window 24893 */ 24894 int mWindowTop; 24895 24896 /** 24897 * Indicates whether views need to use 32-bit drawing caches 24898 */ 24899 boolean mUse32BitDrawingCache; 24900 24901 /** 24902 * For windows that are full-screen but using insets to layout inside 24903 * of the screen areas, these are the current insets to appear inside 24904 * the overscan area of the display. 24905 */ 24906 final Rect mOverscanInsets = new Rect(); 24907 24908 /** 24909 * For windows that are full-screen but using insets to layout inside 24910 * of the screen decorations, these are the current insets for the 24911 * content of the window. 24912 */ 24913 final Rect mContentInsets = new Rect(); 24914 24915 /** 24916 * For windows that are full-screen but using insets to layout inside 24917 * of the screen decorations, these are the current insets for the 24918 * actual visible parts of the window. 24919 */ 24920 final Rect mVisibleInsets = new Rect(); 24921 24922 /** 24923 * For windows that are full-screen but using insets to layout inside 24924 * of the screen decorations, these are the current insets for the 24925 * stable system windows. 24926 */ 24927 final Rect mStableInsets = new Rect(); 24928 24929 /** 24930 * For windows that include areas that are not covered by real surface these are the outsets 24931 * for real surface. 24932 */ 24933 final Rect mOutsets = new Rect(); 24934 24935 /** 24936 * In multi-window we force show the navigation bar. Because we don't want that the surface 24937 * size changes in this mode, we instead have a flag whether the navigation bar size should 24938 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 24939 */ 24940 boolean mAlwaysConsumeNavBar; 24941 24942 /** 24943 * The internal insets given by this window. This value is 24944 * supplied by the client (through 24945 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 24946 * be given to the window manager when changed to be used in laying 24947 * out windows behind it. 24948 */ 24949 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 24950 = new ViewTreeObserver.InternalInsetsInfo(); 24951 24952 /** 24953 * Set to true when mGivenInternalInsets is non-empty. 24954 */ 24955 boolean mHasNonEmptyGivenInternalInsets; 24956 24957 /** 24958 * All views in the window's hierarchy that serve as scroll containers, 24959 * used to determine if the window can be resized or must be panned 24960 * to adjust for a soft input area. 24961 */ 24962 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 24963 24964 final KeyEvent.DispatcherState mKeyDispatchState 24965 = new KeyEvent.DispatcherState(); 24966 24967 /** 24968 * Indicates whether the view's window currently has the focus. 24969 */ 24970 boolean mHasWindowFocus; 24971 24972 /** 24973 * The current visibility of the window. 24974 */ 24975 int mWindowVisibility; 24976 24977 /** 24978 * Indicates the time at which drawing started to occur. 24979 */ 24980 long mDrawingTime; 24981 24982 /** 24983 * Indicates whether or not ignoring the DIRTY_MASK flags. 24984 */ 24985 boolean mIgnoreDirtyState; 24986 24987 /** 24988 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 24989 * to avoid clearing that flag prematurely. 24990 */ 24991 boolean mSetIgnoreDirtyState = false; 24992 24993 /** 24994 * Indicates whether the view's window is currently in touch mode. 24995 */ 24996 boolean mInTouchMode; 24997 24998 /** 24999 * Indicates whether the view has requested unbuffered input dispatching for the current 25000 * event stream. 25001 */ 25002 boolean mUnbufferedDispatchRequested; 25003 25004 /** 25005 * Indicates that ViewAncestor should trigger a global layout change 25006 * the next time it performs a traversal 25007 */ 25008 boolean mRecomputeGlobalAttributes; 25009 25010 /** 25011 * Always report new attributes at next traversal. 25012 */ 25013 boolean mForceReportNewAttributes; 25014 25015 /** 25016 * Set during a traveral if any views want to keep the screen on. 25017 */ 25018 boolean mKeepScreenOn; 25019 25020 /** 25021 * Set during a traveral if the light center needs to be updated. 25022 */ 25023 boolean mNeedsUpdateLightCenter; 25024 25025 /** 25026 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 25027 */ 25028 int mSystemUiVisibility; 25029 25030 /** 25031 * Hack to force certain system UI visibility flags to be cleared. 25032 */ 25033 int mDisabledSystemUiVisibility; 25034 25035 /** 25036 * Last global system UI visibility reported by the window manager. 25037 */ 25038 int mGlobalSystemUiVisibility = -1; 25039 25040 /** 25041 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 25042 * attached. 25043 */ 25044 boolean mHasSystemUiListeners; 25045 25046 /** 25047 * Set if the window has requested to extend into the overscan region 25048 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 25049 */ 25050 boolean mOverscanRequested; 25051 25052 /** 25053 * Set if the visibility of any views has changed. 25054 */ 25055 boolean mViewVisibilityChanged; 25056 25057 /** 25058 * Set to true if a view has been scrolled. 25059 */ 25060 boolean mViewScrollChanged; 25061 25062 /** 25063 * Set to true if high contrast mode enabled 25064 */ 25065 boolean mHighContrastText; 25066 25067 /** 25068 * Set to true if a pointer event is currently being handled. 25069 */ 25070 boolean mHandlingPointerEvent; 25071 25072 /** 25073 * Global to the view hierarchy used as a temporary for dealing with 25074 * x/y points in the transparent region computations. 25075 */ 25076 final int[] mTransparentLocation = new int[2]; 25077 25078 /** 25079 * Global to the view hierarchy used as a temporary for dealing with 25080 * x/y points in the ViewGroup.invalidateChild implementation. 25081 */ 25082 final int[] mInvalidateChildLocation = new int[2]; 25083 25084 /** 25085 * Global to the view hierarchy used as a temporary for dealing with 25086 * computing absolute on-screen location. 25087 */ 25088 final int[] mTmpLocation = new int[2]; 25089 25090 /** 25091 * Global to the view hierarchy used as a temporary for dealing with 25092 * x/y location when view is transformed. 25093 */ 25094 final float[] mTmpTransformLocation = new float[2]; 25095 25096 /** 25097 * The view tree observer used to dispatch global events like 25098 * layout, pre-draw, touch mode change, etc. 25099 */ 25100 final ViewTreeObserver mTreeObserver; 25101 25102 /** 25103 * A Canvas used by the view hierarchy to perform bitmap caching. 25104 */ 25105 Canvas mCanvas; 25106 25107 /** 25108 * The view root impl. 25109 */ 25110 final ViewRootImpl mViewRootImpl; 25111 25112 /** 25113 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 25114 * handler can be used to pump events in the UI events queue. 25115 */ 25116 final Handler mHandler; 25117 25118 /** 25119 * Temporary for use in computing invalidate rectangles while 25120 * calling up the hierarchy. 25121 */ 25122 final Rect mTmpInvalRect = new Rect(); 25123 25124 /** 25125 * Temporary for use in computing hit areas with transformed views 25126 */ 25127 final RectF mTmpTransformRect = new RectF(); 25128 25129 /** 25130 * Temporary for use in computing hit areas with transformed views 25131 */ 25132 final RectF mTmpTransformRect1 = new RectF(); 25133 25134 /** 25135 * Temporary list of rectanges. 25136 */ 25137 final List<RectF> mTmpRectList = new ArrayList<>(); 25138 25139 /** 25140 * Temporary for use in transforming invalidation rect 25141 */ 25142 final Matrix mTmpMatrix = new Matrix(); 25143 25144 /** 25145 * Temporary for use in transforming invalidation rect 25146 */ 25147 final Transformation mTmpTransformation = new Transformation(); 25148 25149 /** 25150 * Temporary for use in querying outlines from OutlineProviders 25151 */ 25152 final Outline mTmpOutline = new Outline(); 25153 25154 /** 25155 * Temporary list for use in collecting focusable descendents of a view. 25156 */ 25157 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 25158 25159 /** 25160 * The id of the window for accessibility purposes. 25161 */ 25162 int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 25163 25164 /** 25165 * Flags related to accessibility processing. 25166 * 25167 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 25168 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 25169 */ 25170 int mAccessibilityFetchFlags; 25171 25172 /** 25173 * The drawable for highlighting accessibility focus. 25174 */ 25175 Drawable mAccessibilityFocusDrawable; 25176 25177 /** 25178 * The drawable for highlighting autofilled views. 25179 * 25180 * @see #isAutofilled() 25181 */ 25182 Drawable mAutofilledDrawable; 25183 25184 /** 25185 * Show where the margins, bounds and layout bounds are for each view. 25186 */ 25187 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 25188 25189 /** 25190 * Point used to compute visible regions. 25191 */ 25192 final Point mPoint = new Point(); 25193 25194 /** 25195 * Used to track which View originated a requestLayout() call, used when 25196 * requestLayout() is called during layout. 25197 */ 25198 View mViewRequestingLayout; 25199 25200 /** 25201 * Used to track views that need (at least) a partial relayout at their current size 25202 * during the next traversal. 25203 */ 25204 List<View> mPartialLayoutViews = new ArrayList<>(); 25205 25206 /** 25207 * Swapped with mPartialLayoutViews during layout to avoid concurrent 25208 * modification. Lazily assigned during ViewRootImpl layout. 25209 */ 25210 List<View> mEmptyPartialLayoutViews; 25211 25212 /** 25213 * Used to track the identity of the current drag operation. 25214 */ 25215 IBinder mDragToken; 25216 25217 /** 25218 * The drag shadow surface for the current drag operation. 25219 */ 25220 public Surface mDragSurface; 25221 25222 25223 /** 25224 * The view that currently has a tooltip displayed. 25225 */ 25226 View mTooltipHost; 25227 25228 /** 25229 * Creates a new set of attachment information with the specified 25230 * events handler and thread. 25231 * 25232 * @param handler the events handler the view must use 25233 */ 25234 AttachInfo(IWindowSession session, IWindow window, Display display, 25235 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 25236 Context context) { 25237 mSession = session; 25238 mWindow = window; 25239 mWindowToken = window.asBinder(); 25240 mDisplay = display; 25241 mViewRootImpl = viewRootImpl; 25242 mHandler = handler; 25243 mRootCallbacks = effectPlayer; 25244 mTreeObserver = new ViewTreeObserver(context); 25245 } 25246 } 25247 25248 /** 25249 * <p>ScrollabilityCache holds various fields used by a View when scrolling 25250 * is supported. This avoids keeping too many unused fields in most 25251 * instances of View.</p> 25252 */ 25253 private static class ScrollabilityCache implements Runnable { 25254 25255 /** 25256 * Scrollbars are not visible 25257 */ 25258 public static final int OFF = 0; 25259 25260 /** 25261 * Scrollbars are visible 25262 */ 25263 public static final int ON = 1; 25264 25265 /** 25266 * Scrollbars are fading away 25267 */ 25268 public static final int FADING = 2; 25269 25270 public boolean fadeScrollBars; 25271 25272 public int fadingEdgeLength; 25273 public int scrollBarDefaultDelayBeforeFade; 25274 public int scrollBarFadeDuration; 25275 25276 public int scrollBarSize; 25277 public int scrollBarMinTouchTarget; 25278 public ScrollBarDrawable scrollBar; 25279 public float[] interpolatorValues; 25280 public View host; 25281 25282 public final Paint paint; 25283 public final Matrix matrix; 25284 public Shader shader; 25285 25286 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 25287 25288 private static final float[] OPAQUE = { 255 }; 25289 private static final float[] TRANSPARENT = { 0.0f }; 25290 25291 /** 25292 * When fading should start. This time moves into the future every time 25293 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 25294 */ 25295 public long fadeStartTime; 25296 25297 25298 /** 25299 * The current state of the scrollbars: ON, OFF, or FADING 25300 */ 25301 public int state = OFF; 25302 25303 private int mLastColor; 25304 25305 public final Rect mScrollBarBounds = new Rect(); 25306 public final Rect mScrollBarTouchBounds = new Rect(); 25307 25308 public static final int NOT_DRAGGING = 0; 25309 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 25310 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 25311 public int mScrollBarDraggingState = NOT_DRAGGING; 25312 25313 public float mScrollBarDraggingPos = 0; 25314 25315 public ScrollabilityCache(ViewConfiguration configuration, View host) { 25316 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 25317 scrollBarSize = configuration.getScaledScrollBarSize(); 25318 scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget(); 25319 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 25320 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 25321 25322 paint = new Paint(); 25323 matrix = new Matrix(); 25324 // use use a height of 1, and then wack the matrix each time we 25325 // actually use it. 25326 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25327 paint.setShader(shader); 25328 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25329 25330 this.host = host; 25331 } 25332 25333 public void setFadeColor(int color) { 25334 if (color != mLastColor) { 25335 mLastColor = color; 25336 25337 if (color != 0) { 25338 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 25339 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 25340 paint.setShader(shader); 25341 // Restore the default transfer mode (src_over) 25342 paint.setXfermode(null); 25343 } else { 25344 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25345 paint.setShader(shader); 25346 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25347 } 25348 } 25349 } 25350 25351 public void run() { 25352 long now = AnimationUtils.currentAnimationTimeMillis(); 25353 if (now >= fadeStartTime) { 25354 25355 // the animation fades the scrollbars out by changing 25356 // the opacity (alpha) from fully opaque to fully 25357 // transparent 25358 int nextFrame = (int) now; 25359 int framesCount = 0; 25360 25361 Interpolator interpolator = scrollBarInterpolator; 25362 25363 // Start opaque 25364 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 25365 25366 // End transparent 25367 nextFrame += scrollBarFadeDuration; 25368 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 25369 25370 state = FADING; 25371 25372 // Kick off the fade animation 25373 host.invalidate(true); 25374 } 25375 } 25376 } 25377 25378 /** 25379 * Resuable callback for sending 25380 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 25381 */ 25382 private class SendViewScrolledAccessibilityEvent implements Runnable { 25383 public volatile boolean mIsPending; 25384 25385 public void run() { 25386 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 25387 mIsPending = false; 25388 } 25389 } 25390 25391 /** 25392 * <p> 25393 * This class represents a delegate that can be registered in a {@link View} 25394 * to enhance accessibility support via composition rather via inheritance. 25395 * It is specifically targeted to widget developers that extend basic View 25396 * classes i.e. classes in package android.view, that would like their 25397 * applications to be backwards compatible. 25398 * </p> 25399 * <div class="special reference"> 25400 * <h3>Developer Guides</h3> 25401 * <p>For more information about making applications accessible, read the 25402 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 25403 * developer guide.</p> 25404 * </div> 25405 * <p> 25406 * A scenario in which a developer would like to use an accessibility delegate 25407 * is overriding a method introduced in a later API version than the minimal API 25408 * version supported by the application. For example, the method 25409 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 25410 * in API version 4 when the accessibility APIs were first introduced. If a 25411 * developer would like his application to run on API version 4 devices (assuming 25412 * all other APIs used by the application are version 4 or lower) and take advantage 25413 * of this method, instead of overriding the method which would break the application's 25414 * backwards compatibility, he can override the corresponding method in this 25415 * delegate and register the delegate in the target View if the API version of 25416 * the system is high enough, i.e. the API version is the same as or higher than the API 25417 * version that introduced 25418 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 25419 * </p> 25420 * <p> 25421 * Here is an example implementation: 25422 * </p> 25423 * <code><pre><p> 25424 * if (Build.VERSION.SDK_INT >= 14) { 25425 * // If the API version is equal of higher than the version in 25426 * // which onInitializeAccessibilityNodeInfo was introduced we 25427 * // register a delegate with a customized implementation. 25428 * View view = findViewById(R.id.view_id); 25429 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 25430 * public void onInitializeAccessibilityNodeInfo(View host, 25431 * AccessibilityNodeInfo info) { 25432 * // Let the default implementation populate the info. 25433 * super.onInitializeAccessibilityNodeInfo(host, info); 25434 * // Set some other information. 25435 * info.setEnabled(host.isEnabled()); 25436 * } 25437 * }); 25438 * } 25439 * </code></pre></p> 25440 * <p> 25441 * This delegate contains methods that correspond to the accessibility methods 25442 * in View. If a delegate has been specified the implementation in View hands 25443 * off handling to the corresponding method in this delegate. The default 25444 * implementation the delegate methods behaves exactly as the corresponding 25445 * method in View for the case of no accessibility delegate been set. Hence, 25446 * to customize the behavior of a View method, clients can override only the 25447 * corresponding delegate method without altering the behavior of the rest 25448 * accessibility related methods of the host view. 25449 * </p> 25450 * <p> 25451 * <strong>Note:</strong> On platform versions prior to 25452 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 25453 * views in the {@code android.widget.*} package are called <i>before</i> 25454 * host methods. This prevents certain properties such as class name from 25455 * being modified by overriding 25456 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 25457 * as any changes will be overwritten by the host class. 25458 * <p> 25459 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 25460 * methods are called <i>after</i> host methods, which all properties to be 25461 * modified without being overwritten by the host class. 25462 */ 25463 public static class AccessibilityDelegate { 25464 25465 /** 25466 * Sends an accessibility event of the given type. If accessibility is not 25467 * enabled this method has no effect. 25468 * <p> 25469 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 25470 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 25471 * been set. 25472 * </p> 25473 * 25474 * @param host The View hosting the delegate. 25475 * @param eventType The type of the event to send. 25476 * 25477 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 25478 */ 25479 public void sendAccessibilityEvent(View host, int eventType) { 25480 host.sendAccessibilityEventInternal(eventType); 25481 } 25482 25483 /** 25484 * Performs the specified accessibility action on the view. For 25485 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 25486 * <p> 25487 * The default implementation behaves as 25488 * {@link View#performAccessibilityAction(int, Bundle) 25489 * View#performAccessibilityAction(int, Bundle)} for the case of 25490 * no accessibility delegate been set. 25491 * </p> 25492 * 25493 * @param action The action to perform. 25494 * @return Whether the action was performed. 25495 * 25496 * @see View#performAccessibilityAction(int, Bundle) 25497 * View#performAccessibilityAction(int, Bundle) 25498 */ 25499 public boolean performAccessibilityAction(View host, int action, Bundle args) { 25500 return host.performAccessibilityActionInternal(action, args); 25501 } 25502 25503 /** 25504 * Sends an accessibility event. This method behaves exactly as 25505 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 25506 * empty {@link AccessibilityEvent} and does not perform a check whether 25507 * accessibility is enabled. 25508 * <p> 25509 * The default implementation behaves as 25510 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25511 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 25512 * the case of no accessibility delegate been set. 25513 * </p> 25514 * 25515 * @param host The View hosting the delegate. 25516 * @param event The event to send. 25517 * 25518 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25519 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25520 */ 25521 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 25522 host.sendAccessibilityEventUncheckedInternal(event); 25523 } 25524 25525 /** 25526 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 25527 * to its children for adding their text content to the event. 25528 * <p> 25529 * The default implementation behaves as 25530 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25531 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 25532 * the case of no accessibility delegate been set. 25533 * </p> 25534 * 25535 * @param host The View hosting the delegate. 25536 * @param event The event. 25537 * @return True if the event population was completed. 25538 * 25539 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25540 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25541 */ 25542 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25543 return host.dispatchPopulateAccessibilityEventInternal(event); 25544 } 25545 25546 /** 25547 * Gives a chance to the host View to populate the accessibility event with its 25548 * text content. 25549 * <p> 25550 * The default implementation behaves as 25551 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 25552 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 25553 * the case of no accessibility delegate been set. 25554 * </p> 25555 * 25556 * @param host The View hosting the delegate. 25557 * @param event The accessibility event which to populate. 25558 * 25559 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 25560 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 25561 */ 25562 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25563 host.onPopulateAccessibilityEventInternal(event); 25564 } 25565 25566 /** 25567 * Initializes an {@link AccessibilityEvent} with information about the 25568 * the host View which is the event source. 25569 * <p> 25570 * The default implementation behaves as 25571 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 25572 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 25573 * the case of no accessibility delegate been set. 25574 * </p> 25575 * 25576 * @param host The View hosting the delegate. 25577 * @param event The event to initialize. 25578 * 25579 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 25580 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 25581 */ 25582 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 25583 host.onInitializeAccessibilityEventInternal(event); 25584 } 25585 25586 /** 25587 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 25588 * <p> 25589 * The default implementation behaves as 25590 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25591 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 25592 * the case of no accessibility delegate been set. 25593 * </p> 25594 * 25595 * @param host The View hosting the delegate. 25596 * @param info The instance to initialize. 25597 * 25598 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25599 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25600 */ 25601 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 25602 host.onInitializeAccessibilityNodeInfoInternal(info); 25603 } 25604 25605 /** 25606 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 25607 * additional data. 25608 * <p> 25609 * This method only needs to be implemented if the View offers to provide additional data. 25610 * </p> 25611 * <p> 25612 * The default implementation behaves as 25613 * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for 25614 * the case where no accessibility delegate is set. 25615 * </p> 25616 * 25617 * @param host The View hosting the delegate. Never {@code null}. 25618 * @param info The info to which to add the extra data. Never {@code null}. 25619 * @param extraDataKey A key specifying the type of extra data to add to the info. The 25620 * extra data should be added to the {@link Bundle} returned by 25621 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 25622 * {@code null}. 25623 * @param arguments A {@link Bundle} holding any arguments relevant for this request. 25624 * May be {@code null} if the if the service provided no arguments. 25625 * 25626 * @see AccessibilityNodeInfo#setExtraAvailableData 25627 */ 25628 public void addExtraDataToAccessibilityNodeInfo(@NonNull View host, 25629 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 25630 @Nullable Bundle arguments) { 25631 host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments); 25632 } 25633 25634 /** 25635 * Called when a child of the host View has requested sending an 25636 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 25637 * to augment the event. 25638 * <p> 25639 * The default implementation behaves as 25640 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25641 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 25642 * the case of no accessibility delegate been set. 25643 * </p> 25644 * 25645 * @param host The View hosting the delegate. 25646 * @param child The child which requests sending the event. 25647 * @param event The event to be sent. 25648 * @return True if the event should be sent 25649 * 25650 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25651 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25652 */ 25653 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 25654 AccessibilityEvent event) { 25655 return host.onRequestSendAccessibilityEventInternal(child, event); 25656 } 25657 25658 /** 25659 * Gets the provider for managing a virtual view hierarchy rooted at this View 25660 * and reported to {@link android.accessibilityservice.AccessibilityService}s 25661 * that explore the window content. 25662 * <p> 25663 * The default implementation behaves as 25664 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 25665 * the case of no accessibility delegate been set. 25666 * </p> 25667 * 25668 * @return The provider. 25669 * 25670 * @see AccessibilityNodeProvider 25671 */ 25672 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 25673 return null; 25674 } 25675 25676 /** 25677 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 25678 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 25679 * This method is responsible for obtaining an accessibility node info from a 25680 * pool of reusable instances and calling 25681 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 25682 * view to initialize the former. 25683 * <p> 25684 * <strong>Note:</strong> The client is responsible for recycling the obtained 25685 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 25686 * creation. 25687 * </p> 25688 * <p> 25689 * The default implementation behaves as 25690 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 25691 * the case of no accessibility delegate been set. 25692 * </p> 25693 * @return A populated {@link AccessibilityNodeInfo}. 25694 * 25695 * @see AccessibilityNodeInfo 25696 * 25697 * @hide 25698 */ 25699 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 25700 return host.createAccessibilityNodeInfoInternal(); 25701 } 25702 } 25703 25704 private static class MatchIdPredicate implements Predicate<View> { 25705 public int mId; 25706 25707 @Override 25708 public boolean test(View view) { 25709 return (view.mID == mId); 25710 } 25711 } 25712 25713 private static class MatchLabelForPredicate implements Predicate<View> { 25714 private int mLabeledId; 25715 25716 @Override 25717 public boolean test(View view) { 25718 return (view.mLabelForId == mLabeledId); 25719 } 25720 } 25721 25722 private class SendViewStateChangedAccessibilityEvent implements Runnable { 25723 private int mChangeTypes = 0; 25724 private boolean mPosted; 25725 private boolean mPostedWithDelay; 25726 private long mLastEventTimeMillis; 25727 25728 @Override 25729 public void run() { 25730 mPosted = false; 25731 mPostedWithDelay = false; 25732 mLastEventTimeMillis = SystemClock.uptimeMillis(); 25733 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 25734 final AccessibilityEvent event = AccessibilityEvent.obtain(); 25735 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 25736 event.setContentChangeTypes(mChangeTypes); 25737 sendAccessibilityEventUnchecked(event); 25738 } 25739 mChangeTypes = 0; 25740 } 25741 25742 public void runOrPost(int changeType) { 25743 mChangeTypes |= changeType; 25744 25745 // If this is a live region or the child of a live region, collect 25746 // all events from this frame and send them on the next frame. 25747 if (inLiveRegion()) { 25748 // If we're already posted with a delay, remove that. 25749 if (mPostedWithDelay) { 25750 removeCallbacks(this); 25751 mPostedWithDelay = false; 25752 } 25753 // Only post if we're not already posted. 25754 if (!mPosted) { 25755 post(this); 25756 mPosted = true; 25757 } 25758 return; 25759 } 25760 25761 if (mPosted) { 25762 return; 25763 } 25764 25765 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 25766 final long minEventIntevalMillis = 25767 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 25768 if (timeSinceLastMillis >= minEventIntevalMillis) { 25769 removeCallbacks(this); 25770 run(); 25771 } else { 25772 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 25773 mPostedWithDelay = true; 25774 } 25775 } 25776 } 25777 25778 private boolean inLiveRegion() { 25779 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25780 return true; 25781 } 25782 25783 ViewParent parent = getParent(); 25784 while (parent instanceof View) { 25785 if (((View) parent).getAccessibilityLiveRegion() 25786 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25787 return true; 25788 } 25789 parent = parent.getParent(); 25790 } 25791 25792 return false; 25793 } 25794 25795 /** 25796 * Dump all private flags in readable format, useful for documentation and 25797 * sanity checking. 25798 */ 25799 private static void dumpFlags() { 25800 final HashMap<String, String> found = Maps.newHashMap(); 25801 try { 25802 for (Field field : View.class.getDeclaredFields()) { 25803 final int modifiers = field.getModifiers(); 25804 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 25805 if (field.getType().equals(int.class)) { 25806 final int value = field.getInt(null); 25807 dumpFlag(found, field.getName(), value); 25808 } else if (field.getType().equals(int[].class)) { 25809 final int[] values = (int[]) field.get(null); 25810 for (int i = 0; i < values.length; i++) { 25811 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 25812 } 25813 } 25814 } 25815 } 25816 } catch (IllegalAccessException e) { 25817 throw new RuntimeException(e); 25818 } 25819 25820 final ArrayList<String> keys = Lists.newArrayList(); 25821 keys.addAll(found.keySet()); 25822 Collections.sort(keys); 25823 for (String key : keys) { 25824 Log.d(VIEW_LOG_TAG, found.get(key)); 25825 } 25826 } 25827 25828 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 25829 // Sort flags by prefix, then by bits, always keeping unique keys 25830 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 25831 final int prefix = name.indexOf('_'); 25832 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 25833 final String output = bits + " " + name; 25834 found.put(key, output); 25835 } 25836 25837 /** {@hide} */ 25838 public void encode(@NonNull ViewHierarchyEncoder stream) { 25839 stream.beginObject(this); 25840 encodeProperties(stream); 25841 stream.endObject(); 25842 } 25843 25844 /** {@hide} */ 25845 @CallSuper 25846 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 25847 Object resolveId = ViewDebug.resolveId(getContext(), mID); 25848 if (resolveId instanceof String) { 25849 stream.addProperty("id", (String) resolveId); 25850 } else { 25851 stream.addProperty("id", mID); 25852 } 25853 25854 stream.addProperty("misc:transformation.alpha", 25855 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 25856 stream.addProperty("misc:transitionName", getTransitionName()); 25857 25858 // layout 25859 stream.addProperty("layout:left", mLeft); 25860 stream.addProperty("layout:right", mRight); 25861 stream.addProperty("layout:top", mTop); 25862 stream.addProperty("layout:bottom", mBottom); 25863 stream.addProperty("layout:width", getWidth()); 25864 stream.addProperty("layout:height", getHeight()); 25865 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 25866 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 25867 stream.addProperty("layout:hasTransientState", hasTransientState()); 25868 stream.addProperty("layout:baseline", getBaseline()); 25869 25870 // layout params 25871 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 25872 if (layoutParams != null) { 25873 stream.addPropertyKey("layoutParams"); 25874 layoutParams.encode(stream); 25875 } 25876 25877 // scrolling 25878 stream.addProperty("scrolling:scrollX", mScrollX); 25879 stream.addProperty("scrolling:scrollY", mScrollY); 25880 25881 // padding 25882 stream.addProperty("padding:paddingLeft", mPaddingLeft); 25883 stream.addProperty("padding:paddingRight", mPaddingRight); 25884 stream.addProperty("padding:paddingTop", mPaddingTop); 25885 stream.addProperty("padding:paddingBottom", mPaddingBottom); 25886 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 25887 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 25888 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 25889 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 25890 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 25891 25892 // measurement 25893 stream.addProperty("measurement:minHeight", mMinHeight); 25894 stream.addProperty("measurement:minWidth", mMinWidth); 25895 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 25896 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 25897 25898 // drawing 25899 stream.addProperty("drawing:elevation", getElevation()); 25900 stream.addProperty("drawing:translationX", getTranslationX()); 25901 stream.addProperty("drawing:translationY", getTranslationY()); 25902 stream.addProperty("drawing:translationZ", getTranslationZ()); 25903 stream.addProperty("drawing:rotation", getRotation()); 25904 stream.addProperty("drawing:rotationX", getRotationX()); 25905 stream.addProperty("drawing:rotationY", getRotationY()); 25906 stream.addProperty("drawing:scaleX", getScaleX()); 25907 stream.addProperty("drawing:scaleY", getScaleY()); 25908 stream.addProperty("drawing:pivotX", getPivotX()); 25909 stream.addProperty("drawing:pivotY", getPivotY()); 25910 stream.addProperty("drawing:opaque", isOpaque()); 25911 stream.addProperty("drawing:alpha", getAlpha()); 25912 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 25913 stream.addProperty("drawing:shadow", hasShadow()); 25914 stream.addProperty("drawing:solidColor", getSolidColor()); 25915 stream.addProperty("drawing:layerType", mLayerType); 25916 stream.addProperty("drawing:willNotDraw", willNotDraw()); 25917 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 25918 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 25919 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 25920 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 25921 25922 // focus 25923 stream.addProperty("focus:hasFocus", hasFocus()); 25924 stream.addProperty("focus:isFocused", isFocused()); 25925 stream.addProperty("focus:focusable", getFocusable()); 25926 stream.addProperty("focus:isFocusable", isFocusable()); 25927 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 25928 25929 stream.addProperty("misc:clickable", isClickable()); 25930 stream.addProperty("misc:pressed", isPressed()); 25931 stream.addProperty("misc:selected", isSelected()); 25932 stream.addProperty("misc:touchMode", isInTouchMode()); 25933 stream.addProperty("misc:hovered", isHovered()); 25934 stream.addProperty("misc:activated", isActivated()); 25935 25936 stream.addProperty("misc:visibility", getVisibility()); 25937 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 25938 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 25939 25940 stream.addProperty("misc:enabled", isEnabled()); 25941 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 25942 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 25943 25944 // theme attributes 25945 Resources.Theme theme = getContext().getTheme(); 25946 if (theme != null) { 25947 stream.addPropertyKey("theme"); 25948 theme.encode(stream); 25949 } 25950 25951 // view attribute information 25952 int n = mAttributes != null ? mAttributes.length : 0; 25953 stream.addProperty("meta:__attrCount__", n/2); 25954 for (int i = 0; i < n; i += 2) { 25955 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 25956 } 25957 25958 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 25959 25960 // text 25961 stream.addProperty("text:textDirection", getTextDirection()); 25962 stream.addProperty("text:textAlignment", getTextAlignment()); 25963 25964 // accessibility 25965 CharSequence contentDescription = getContentDescription(); 25966 stream.addProperty("accessibility:contentDescription", 25967 contentDescription == null ? "" : contentDescription.toString()); 25968 stream.addProperty("accessibility:labelFor", getLabelFor()); 25969 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 25970 } 25971 25972 /** 25973 * Determine if this view is rendered on a round wearable device and is the main view 25974 * on the screen. 25975 */ 25976 boolean shouldDrawRoundScrollbar() { 25977 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 25978 return false; 25979 } 25980 25981 final View rootView = getRootView(); 25982 final WindowInsets insets = getRootWindowInsets(); 25983 25984 int height = getHeight(); 25985 int width = getWidth(); 25986 int displayHeight = rootView.getHeight(); 25987 int displayWidth = rootView.getWidth(); 25988 25989 if (height != displayHeight || width != displayWidth) { 25990 return false; 25991 } 25992 25993 getLocationInWindow(mAttachInfo.mTmpLocation); 25994 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 25995 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 25996 } 25997 25998 /** 25999 * Sets the tooltip text which will be displayed in a small popup next to the view. 26000 * <p> 26001 * The tooltip will be displayed: 26002 * <ul> 26003 * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context 26004 * menu). </li> 26005 * <li>On hover, after a brief delay since the pointer has stopped moving </li> 26006 * </ul> 26007 * <p> 26008 * <strong>Note:</strong> Do not override this method, as it will have no 26009 * effect on the text displayed in the tooltip. 26010 * 26011 * @param tooltipText the tooltip text, or null if no tooltip is required 26012 * @see #getTooltipText() 26013 * @attr ref android.R.styleable#View_tooltipText 26014 */ 26015 public void setTooltipText(@Nullable CharSequence tooltipText) { 26016 if (TextUtils.isEmpty(tooltipText)) { 26017 setFlags(0, TOOLTIP); 26018 hideTooltip(); 26019 mTooltipInfo = null; 26020 } else { 26021 setFlags(TOOLTIP, TOOLTIP); 26022 if (mTooltipInfo == null) { 26023 mTooltipInfo = new TooltipInfo(); 26024 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip; 26025 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip; 26026 } 26027 mTooltipInfo.mTooltipText = tooltipText; 26028 if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) { 26029 mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText); 26030 } 26031 } 26032 } 26033 26034 /** 26035 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 26036 */ 26037 public void setTooltip(@Nullable CharSequence tooltipText) { 26038 setTooltipText(tooltipText); 26039 } 26040 26041 /** 26042 * Returns the view's tooltip text. 26043 * 26044 * <strong>Note:</strong> Do not override this method, as it will have no 26045 * effect on the text displayed in the tooltip. You must call 26046 * {@link #setTooltipText(CharSequence)} to modify the tooltip text. 26047 * 26048 * @return the tooltip text 26049 * @see #setTooltipText(CharSequence) 26050 * @attr ref android.R.styleable#View_tooltipText 26051 */ 26052 @Nullable 26053 public CharSequence getTooltipText() { 26054 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null; 26055 } 26056 26057 /** 26058 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 26059 */ 26060 @Nullable 26061 public CharSequence getTooltip() { 26062 return getTooltipText(); 26063 } 26064 26065 private boolean showTooltip(int x, int y, boolean fromLongClick) { 26066 if (mAttachInfo == null || mTooltipInfo == null) { 26067 return false; 26068 } 26069 if ((mViewFlags & ENABLED_MASK) != ENABLED) { 26070 return false; 26071 } 26072 if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) { 26073 return false; 26074 } 26075 hideTooltip(); 26076 mTooltipInfo.mTooltipFromLongClick = fromLongClick; 26077 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext()); 26078 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN; 26079 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText); 26080 mAttachInfo.mTooltipHost = this; 26081 return true; 26082 } 26083 26084 void hideTooltip() { 26085 if (mTooltipInfo == null) { 26086 return; 26087 } 26088 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26089 if (mTooltipInfo.mTooltipPopup == null) { 26090 return; 26091 } 26092 mTooltipInfo.mTooltipPopup.hide(); 26093 mTooltipInfo.mTooltipPopup = null; 26094 mTooltipInfo.mTooltipFromLongClick = false; 26095 if (mAttachInfo != null) { 26096 mAttachInfo.mTooltipHost = null; 26097 } 26098 } 26099 26100 private boolean showLongClickTooltip(int x, int y) { 26101 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26102 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26103 return showTooltip(x, y, true); 26104 } 26105 26106 private void showHoverTooltip() { 26107 showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false); 26108 } 26109 26110 boolean dispatchTooltipHoverEvent(MotionEvent event) { 26111 if (mTooltipInfo == null) { 26112 return false; 26113 } 26114 switch(event.getAction()) { 26115 case MotionEvent.ACTION_HOVER_MOVE: 26116 if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) { 26117 break; 26118 } 26119 if (!mTooltipInfo.mTooltipFromLongClick) { 26120 if (mTooltipInfo.mTooltipPopup == null) { 26121 // Schedule showing the tooltip after a timeout. 26122 mTooltipInfo.mAnchorX = (int) event.getX(); 26123 mTooltipInfo.mAnchorY = (int) event.getY(); 26124 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26125 postDelayed(mTooltipInfo.mShowTooltipRunnable, 26126 ViewConfiguration.getHoverTooltipShowTimeout()); 26127 } 26128 26129 // Hide hover-triggered tooltip after a period of inactivity. 26130 // Match the timeout used by NativeInputManager to hide the mouse pointer 26131 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set). 26132 final int timeout; 26133 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE) 26134 == SYSTEM_UI_FLAG_LOW_PROFILE) { 26135 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout(); 26136 } else { 26137 timeout = ViewConfiguration.getHoverTooltipHideTimeout(); 26138 } 26139 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26140 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout); 26141 } 26142 return true; 26143 26144 case MotionEvent.ACTION_HOVER_EXIT: 26145 if (!mTooltipInfo.mTooltipFromLongClick) { 26146 hideTooltip(); 26147 } 26148 break; 26149 } 26150 return false; 26151 } 26152 26153 void handleTooltipKey(KeyEvent event) { 26154 switch (event.getAction()) { 26155 case KeyEvent.ACTION_DOWN: 26156 if (event.getRepeatCount() == 0) { 26157 hideTooltip(); 26158 } 26159 break; 26160 26161 case KeyEvent.ACTION_UP: 26162 handleTooltipUp(); 26163 break; 26164 } 26165 } 26166 26167 private void handleTooltipUp() { 26168 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 26169 return; 26170 } 26171 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26172 postDelayed(mTooltipInfo.mHideTooltipRunnable, 26173 ViewConfiguration.getLongPressTooltipHideTimeout()); 26174 } 26175 26176 private int getFocusableAttribute(TypedArray attributes) { 26177 TypedValue val = new TypedValue(); 26178 if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) { 26179 if (val.type == TypedValue.TYPE_INT_BOOLEAN) { 26180 return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE); 26181 } else { 26182 return val.data; 26183 } 26184 } else { 26185 return FOCUSABLE_AUTO; 26186 } 26187 } 26188 26189 /** 26190 * @return The content view of the tooltip popup currently being shown, or null if the tooltip 26191 * is not showing. 26192 * @hide 26193 */ 26194 @TestApi 26195 public View getTooltipView() { 26196 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 26197 return null; 26198 } 26199 return mTooltipInfo.mTooltipPopup.getContentView(); 26200 } 26201} 26202