View.java revision f14aea9f8ba0c65c1e6924fcbaf1a73f85c1da4c
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. The 17310 * default implementation returns null. 17311 * @see #onRestoreInstanceState(android.os.Parcelable) 17312 * @see #saveHierarchyState(android.util.SparseArray) 17313 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17314 * @see #setSaveEnabled(boolean) 17315 */ 17316 @CallSuper 17317 protected Parcelable onSaveInstanceState() { 17318 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17319 if (mStartActivityRequestWho != null || isAutofilled() 17320 || mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) { 17321 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 17322 17323 if (mStartActivityRequestWho != null) { 17324 state.mSavedData |= BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED; 17325 } 17326 17327 if (isAutofilled()) { 17328 state.mSavedData |= BaseSavedState.IS_AUTOFILLED; 17329 } 17330 17331 if (mAccessibilityViewId > LAST_APP_ACCESSIBILITY_ID) { 17332 state.mSavedData |= BaseSavedState.ACCESSIBILITY_ID; 17333 } 17334 17335 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 17336 state.mIsAutofilled = isAutofilled(); 17337 state.mAccessibilityViewId = mAccessibilityViewId; 17338 return state; 17339 } 17340 return BaseSavedState.EMPTY_STATE; 17341 } 17342 17343 /** 17344 * Restore this view hierarchy's frozen state from the given container. 17345 * 17346 * @param container The SparseArray which holds previously frozen states. 17347 * 17348 * @see #saveHierarchyState(android.util.SparseArray) 17349 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17350 * @see #onRestoreInstanceState(android.os.Parcelable) 17351 */ 17352 public void restoreHierarchyState(SparseArray<Parcelable> container) { 17353 dispatchRestoreInstanceState(container); 17354 } 17355 17356 /** 17357 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 17358 * state for this view and its children. May be overridden to modify how restoring 17359 * happens to a view's children; for example, some views may want to not store state 17360 * for their children. 17361 * 17362 * @param container The SparseArray which holds previously saved state. 17363 * 17364 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17365 * @see #restoreHierarchyState(android.util.SparseArray) 17366 * @see #onRestoreInstanceState(android.os.Parcelable) 17367 */ 17368 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 17369 if (mID != NO_ID) { 17370 Parcelable state = container.get(mID); 17371 if (state != null) { 17372 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 17373 // + ": " + state); 17374 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 17375 onRestoreInstanceState(state); 17376 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 17377 throw new IllegalStateException( 17378 "Derived class did not call super.onRestoreInstanceState()"); 17379 } 17380 } 17381 } 17382 } 17383 17384 /** 17385 * Hook allowing a view to re-apply a representation of its internal state that had previously 17386 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 17387 * null state. 17388 * 17389 * @param state The frozen state that had previously been returned by 17390 * {@link #onSaveInstanceState}. 17391 * 17392 * @see #onSaveInstanceState() 17393 * @see #restoreHierarchyState(android.util.SparseArray) 17394 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17395 */ 17396 @CallSuper 17397 protected void onRestoreInstanceState(Parcelable state) { 17398 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17399 if (state != null && !(state instanceof AbsSavedState)) { 17400 throw new IllegalArgumentException("Wrong state class, expecting View State but " 17401 + "received " + state.getClass().toString() + " instead. This usually happens " 17402 + "when two views of different type have the same id in the same hierarchy. " 17403 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 17404 + "other views do not use the same id."); 17405 } 17406 if (state != null && state instanceof BaseSavedState) { 17407 BaseSavedState baseState = (BaseSavedState) state; 17408 17409 if ((baseState.mSavedData & BaseSavedState.START_ACTIVITY_REQUESTED_WHO_SAVED) != 0) { 17410 mStartActivityRequestWho = baseState.mStartActivityRequestWhoSaved; 17411 } 17412 if ((baseState.mSavedData & BaseSavedState.IS_AUTOFILLED) != 0) { 17413 setAutofilled(baseState.mIsAutofilled); 17414 } 17415 if ((baseState.mSavedData & BaseSavedState.ACCESSIBILITY_ID) != 0) { 17416 mAccessibilityViewId = baseState.mAccessibilityViewId; 17417 } 17418 } 17419 } 17420 17421 /** 17422 * <p>Return the time at which the drawing of the view hierarchy started.</p> 17423 * 17424 * @return the drawing start time in milliseconds 17425 */ 17426 public long getDrawingTime() { 17427 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 17428 } 17429 17430 /** 17431 * <p>Enables or disables the duplication of the parent's state into this view. When 17432 * duplication is enabled, this view gets its drawable state from its parent rather 17433 * than from its own internal properties.</p> 17434 * 17435 * <p>Note: in the current implementation, setting this property to true after the 17436 * view was added to a ViewGroup might have no effect at all. This property should 17437 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 17438 * 17439 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 17440 * property is enabled, an exception will be thrown.</p> 17441 * 17442 * <p>Note: if the child view uses and updates additional states which are unknown to the 17443 * parent, these states should not be affected by this method.</p> 17444 * 17445 * @param enabled True to enable duplication of the parent's drawable state, false 17446 * to disable it. 17447 * 17448 * @see #getDrawableState() 17449 * @see #isDuplicateParentStateEnabled() 17450 */ 17451 public void setDuplicateParentStateEnabled(boolean enabled) { 17452 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 17453 } 17454 17455 /** 17456 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 17457 * 17458 * @return True if this view's drawable state is duplicated from the parent, 17459 * false otherwise 17460 * 17461 * @see #getDrawableState() 17462 * @see #setDuplicateParentStateEnabled(boolean) 17463 */ 17464 public boolean isDuplicateParentStateEnabled() { 17465 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 17466 } 17467 17468 /** 17469 * <p>Specifies the type of layer backing this view. The layer can be 17470 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17471 * {@link #LAYER_TYPE_HARDWARE}.</p> 17472 * 17473 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17474 * instance that controls how the layer is composed on screen. The following 17475 * properties of the paint are taken into account when composing the layer:</p> 17476 * <ul> 17477 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17478 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17479 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17480 * </ul> 17481 * 17482 * <p>If this view has an alpha value set to < 1.0 by calling 17483 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 17484 * by this view's alpha value.</p> 17485 * 17486 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 17487 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 17488 * for more information on when and how to use layers.</p> 17489 * 17490 * @param layerType The type of layer to use with this view, must be one of 17491 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17492 * {@link #LAYER_TYPE_HARDWARE} 17493 * @param paint The paint used to compose the layer. This argument is optional 17494 * and can be null. It is ignored when the layer type is 17495 * {@link #LAYER_TYPE_NONE} 17496 * 17497 * @see #getLayerType() 17498 * @see #LAYER_TYPE_NONE 17499 * @see #LAYER_TYPE_SOFTWARE 17500 * @see #LAYER_TYPE_HARDWARE 17501 * @see #setAlpha(float) 17502 * 17503 * @attr ref android.R.styleable#View_layerType 17504 */ 17505 public void setLayerType(int layerType, @Nullable Paint paint) { 17506 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 17507 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 17508 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 17509 } 17510 17511 boolean typeChanged = mRenderNode.setLayerType(layerType); 17512 17513 if (!typeChanged) { 17514 setLayerPaint(paint); 17515 return; 17516 } 17517 17518 if (layerType != LAYER_TYPE_SOFTWARE) { 17519 // Destroy any previous software drawing cache if present 17520 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 17521 // drawing cache created in View#draw when drawing to a SW canvas. 17522 destroyDrawingCache(); 17523 } 17524 17525 mLayerType = layerType; 17526 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 17527 mRenderNode.setLayerPaint(mLayerPaint); 17528 17529 // draw() behaves differently if we are on a layer, so we need to 17530 // invalidate() here 17531 invalidateParentCaches(); 17532 invalidate(true); 17533 } 17534 17535 /** 17536 * Updates the {@link Paint} object used with the current layer (used only if the current 17537 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 17538 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 17539 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 17540 * ensure that the view gets redrawn immediately. 17541 * 17542 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17543 * instance that controls how the layer is composed on screen. The following 17544 * properties of the paint are taken into account when composing the layer:</p> 17545 * <ul> 17546 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17547 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17548 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17549 * </ul> 17550 * 17551 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 17552 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 17553 * 17554 * @param paint The paint used to compose the layer. This argument is optional 17555 * and can be null. It is ignored when the layer type is 17556 * {@link #LAYER_TYPE_NONE} 17557 * 17558 * @see #setLayerType(int, android.graphics.Paint) 17559 */ 17560 public void setLayerPaint(@Nullable Paint paint) { 17561 int layerType = getLayerType(); 17562 if (layerType != LAYER_TYPE_NONE) { 17563 mLayerPaint = paint; 17564 if (layerType == LAYER_TYPE_HARDWARE) { 17565 if (mRenderNode.setLayerPaint(paint)) { 17566 invalidateViewProperty(false, false); 17567 } 17568 } else { 17569 invalidate(); 17570 } 17571 } 17572 } 17573 17574 /** 17575 * Indicates what type of layer is currently associated with this view. By default 17576 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 17577 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 17578 * for more information on the different types of layers. 17579 * 17580 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17581 * {@link #LAYER_TYPE_HARDWARE} 17582 * 17583 * @see #setLayerType(int, android.graphics.Paint) 17584 * @see #buildLayer() 17585 * @see #LAYER_TYPE_NONE 17586 * @see #LAYER_TYPE_SOFTWARE 17587 * @see #LAYER_TYPE_HARDWARE 17588 */ 17589 public int getLayerType() { 17590 return mLayerType; 17591 } 17592 17593 /** 17594 * Forces this view's layer to be created and this view to be rendered 17595 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 17596 * invoking this method will have no effect. 17597 * 17598 * This method can for instance be used to render a view into its layer before 17599 * starting an animation. If this view is complex, rendering into the layer 17600 * before starting the animation will avoid skipping frames. 17601 * 17602 * @throws IllegalStateException If this view is not attached to a window 17603 * 17604 * @see #setLayerType(int, android.graphics.Paint) 17605 */ 17606 public void buildLayer() { 17607 if (mLayerType == LAYER_TYPE_NONE) return; 17608 17609 final AttachInfo attachInfo = mAttachInfo; 17610 if (attachInfo == null) { 17611 throw new IllegalStateException("This view must be attached to a window first"); 17612 } 17613 17614 if (getWidth() == 0 || getHeight() == 0) { 17615 return; 17616 } 17617 17618 switch (mLayerType) { 17619 case LAYER_TYPE_HARDWARE: 17620 updateDisplayListIfDirty(); 17621 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 17622 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 17623 } 17624 break; 17625 case LAYER_TYPE_SOFTWARE: 17626 buildDrawingCache(true); 17627 break; 17628 } 17629 } 17630 17631 /** 17632 * Destroys all hardware rendering resources. This method is invoked 17633 * when the system needs to reclaim resources. Upon execution of this 17634 * method, you should free any OpenGL resources created by the view. 17635 * 17636 * Note: you <strong>must</strong> call 17637 * <code>super.destroyHardwareResources()</code> when overriding 17638 * this method. 17639 * 17640 * @hide 17641 */ 17642 @CallSuper 17643 protected void destroyHardwareResources() { 17644 if (mOverlay != null) { 17645 mOverlay.getOverlayView().destroyHardwareResources(); 17646 } 17647 if (mGhostView != null) { 17648 mGhostView.destroyHardwareResources(); 17649 } 17650 } 17651 17652 /** 17653 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 17654 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 17655 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 17656 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 17657 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 17658 * null.</p> 17659 * 17660 * <p>Enabling the drawing cache is similar to 17661 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 17662 * acceleration is turned off. When hardware acceleration is turned on, enabling the 17663 * drawing cache has no effect on rendering because the system uses a different mechanism 17664 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 17665 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 17666 * for information on how to enable software and hardware layers.</p> 17667 * 17668 * <p>This API can be used to manually generate 17669 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 17670 * {@link #getDrawingCache()}.</p> 17671 * 17672 * @param enabled true to enable the drawing cache, false otherwise 17673 * 17674 * @see #isDrawingCacheEnabled() 17675 * @see #getDrawingCache() 17676 * @see #buildDrawingCache() 17677 * @see #setLayerType(int, android.graphics.Paint) 17678 */ 17679 public void setDrawingCacheEnabled(boolean enabled) { 17680 mCachingFailed = false; 17681 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 17682 } 17683 17684 /** 17685 * <p>Indicates whether the drawing cache is enabled for this view.</p> 17686 * 17687 * @return true if the drawing cache is enabled 17688 * 17689 * @see #setDrawingCacheEnabled(boolean) 17690 * @see #getDrawingCache() 17691 */ 17692 @ViewDebug.ExportedProperty(category = "drawing") 17693 public boolean isDrawingCacheEnabled() { 17694 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 17695 } 17696 17697 /** 17698 * Debugging utility which recursively outputs the dirty state of a view and its 17699 * descendants. 17700 * 17701 * @hide 17702 */ 17703 @SuppressWarnings({"UnusedDeclaration"}) 17704 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 17705 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 17706 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 17707 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 17708 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 17709 if (clear) { 17710 mPrivateFlags &= clearMask; 17711 } 17712 if (this instanceof ViewGroup) { 17713 ViewGroup parent = (ViewGroup) this; 17714 final int count = parent.getChildCount(); 17715 for (int i = 0; i < count; i++) { 17716 final View child = parent.getChildAt(i); 17717 child.outputDirtyFlags(indent + " ", clear, clearMask); 17718 } 17719 } 17720 } 17721 17722 /** 17723 * This method is used by ViewGroup to cause its children to restore or recreate their 17724 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 17725 * to recreate its own display list, which would happen if it went through the normal 17726 * draw/dispatchDraw mechanisms. 17727 * 17728 * @hide 17729 */ 17730 protected void dispatchGetDisplayList() {} 17731 17732 /** 17733 * A view that is not attached or hardware accelerated cannot create a display list. 17734 * This method checks these conditions and returns the appropriate result. 17735 * 17736 * @return true if view has the ability to create a display list, false otherwise. 17737 * 17738 * @hide 17739 */ 17740 public boolean canHaveDisplayList() { 17741 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 17742 } 17743 17744 /** 17745 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 17746 * @hide 17747 */ 17748 @NonNull 17749 public RenderNode updateDisplayListIfDirty() { 17750 final RenderNode renderNode = mRenderNode; 17751 if (!canHaveDisplayList()) { 17752 // can't populate RenderNode, don't try 17753 return renderNode; 17754 } 17755 17756 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 17757 || !renderNode.isValid() 17758 || (mRecreateDisplayList)) { 17759 // Don't need to recreate the display list, just need to tell our 17760 // children to restore/recreate theirs 17761 if (renderNode.isValid() 17762 && !mRecreateDisplayList) { 17763 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17764 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17765 dispatchGetDisplayList(); 17766 17767 return renderNode; // no work needed 17768 } 17769 17770 // If we got here, we're recreating it. Mark it as such to ensure that 17771 // we copy in child display lists into ours in drawChild() 17772 mRecreateDisplayList = true; 17773 17774 int width = mRight - mLeft; 17775 int height = mBottom - mTop; 17776 int layerType = getLayerType(); 17777 17778 final DisplayListCanvas canvas = renderNode.start(width, height); 17779 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 17780 17781 try { 17782 if (layerType == LAYER_TYPE_SOFTWARE) { 17783 buildDrawingCache(true); 17784 Bitmap cache = getDrawingCache(true); 17785 if (cache != null) { 17786 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 17787 } 17788 } else { 17789 computeScroll(); 17790 17791 canvas.translate(-mScrollX, -mScrollY); 17792 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17793 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17794 17795 // Fast path for layouts with no backgrounds 17796 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17797 dispatchDraw(canvas); 17798 drawAutofilledHighlight(canvas); 17799 if (mOverlay != null && !mOverlay.isEmpty()) { 17800 mOverlay.getOverlayView().draw(canvas); 17801 } 17802 if (debugDraw()) { 17803 debugDrawFocus(canvas); 17804 } 17805 } else { 17806 draw(canvas); 17807 } 17808 } 17809 } finally { 17810 renderNode.end(canvas); 17811 setDisplayListProperties(renderNode); 17812 } 17813 } else { 17814 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17815 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17816 } 17817 return renderNode; 17818 } 17819 17820 private void resetDisplayList() { 17821 mRenderNode.discardDisplayList(); 17822 if (mBackgroundRenderNode != null) { 17823 mBackgroundRenderNode.discardDisplayList(); 17824 } 17825 } 17826 17827 /** 17828 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 17829 * 17830 * @return A non-scaled bitmap representing this view or null if cache is disabled. 17831 * 17832 * @see #getDrawingCache(boolean) 17833 */ 17834 public Bitmap getDrawingCache() { 17835 return getDrawingCache(false); 17836 } 17837 17838 /** 17839 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 17840 * is null when caching is disabled. If caching is enabled and the cache is not ready, 17841 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 17842 * draw from the cache when the cache is enabled. To benefit from the cache, you must 17843 * request the drawing cache by calling this method and draw it on screen if the 17844 * returned bitmap is not null.</p> 17845 * 17846 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17847 * this method will create a bitmap of the same size as this view. Because this bitmap 17848 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17849 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17850 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17851 * size than the view. This implies that your application must be able to handle this 17852 * size.</p> 17853 * 17854 * @param autoScale Indicates whether the generated bitmap should be scaled based on 17855 * the current density of the screen when the application is in compatibility 17856 * mode. 17857 * 17858 * @return A bitmap representing this view or null if cache is disabled. 17859 * 17860 * @see #setDrawingCacheEnabled(boolean) 17861 * @see #isDrawingCacheEnabled() 17862 * @see #buildDrawingCache(boolean) 17863 * @see #destroyDrawingCache() 17864 */ 17865 public Bitmap getDrawingCache(boolean autoScale) { 17866 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 17867 return null; 17868 } 17869 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 17870 buildDrawingCache(autoScale); 17871 } 17872 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 17873 } 17874 17875 /** 17876 * <p>Frees the resources used by the drawing cache. If you call 17877 * {@link #buildDrawingCache()} manually without calling 17878 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17879 * should cleanup the cache with this method afterwards.</p> 17880 * 17881 * @see #setDrawingCacheEnabled(boolean) 17882 * @see #buildDrawingCache() 17883 * @see #getDrawingCache() 17884 */ 17885 public void destroyDrawingCache() { 17886 if (mDrawingCache != null) { 17887 mDrawingCache.recycle(); 17888 mDrawingCache = null; 17889 } 17890 if (mUnscaledDrawingCache != null) { 17891 mUnscaledDrawingCache.recycle(); 17892 mUnscaledDrawingCache = null; 17893 } 17894 } 17895 17896 /** 17897 * Setting a solid background color for the drawing cache's bitmaps will improve 17898 * performance and memory usage. Note, though that this should only be used if this 17899 * view will always be drawn on top of a solid color. 17900 * 17901 * @param color The background color to use for the drawing cache's bitmap 17902 * 17903 * @see #setDrawingCacheEnabled(boolean) 17904 * @see #buildDrawingCache() 17905 * @see #getDrawingCache() 17906 */ 17907 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 17908 if (color != mDrawingCacheBackgroundColor) { 17909 mDrawingCacheBackgroundColor = color; 17910 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 17911 } 17912 } 17913 17914 /** 17915 * @see #setDrawingCacheBackgroundColor(int) 17916 * 17917 * @return The background color to used for the drawing cache's bitmap 17918 */ 17919 @ColorInt 17920 public int getDrawingCacheBackgroundColor() { 17921 return mDrawingCacheBackgroundColor; 17922 } 17923 17924 /** 17925 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 17926 * 17927 * @see #buildDrawingCache(boolean) 17928 */ 17929 public void buildDrawingCache() { 17930 buildDrawingCache(false); 17931 } 17932 17933 /** 17934 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 17935 * 17936 * <p>If you call {@link #buildDrawingCache()} manually without calling 17937 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17938 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 17939 * 17940 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17941 * this method will create a bitmap of the same size as this view. Because this bitmap 17942 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17943 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17944 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17945 * size than the view. This implies that your application must be able to handle this 17946 * size.</p> 17947 * 17948 * <p>You should avoid calling this method when hardware acceleration is enabled. If 17949 * you do not need the drawing cache bitmap, calling this method will increase memory 17950 * usage and cause the view to be rendered in software once, thus negatively impacting 17951 * performance.</p> 17952 * 17953 * @see #getDrawingCache() 17954 * @see #destroyDrawingCache() 17955 */ 17956 public void buildDrawingCache(boolean autoScale) { 17957 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 17958 mDrawingCache == null : mUnscaledDrawingCache == null)) { 17959 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 17960 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 17961 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 17962 } 17963 try { 17964 buildDrawingCacheImpl(autoScale); 17965 } finally { 17966 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 17967 } 17968 } 17969 } 17970 17971 /** 17972 * private, internal implementation of buildDrawingCache, used to enable tracing 17973 */ 17974 private void buildDrawingCacheImpl(boolean autoScale) { 17975 mCachingFailed = false; 17976 17977 int width = mRight - mLeft; 17978 int height = mBottom - mTop; 17979 17980 final AttachInfo attachInfo = mAttachInfo; 17981 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 17982 17983 if (autoScale && scalingRequired) { 17984 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 17985 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 17986 } 17987 17988 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 17989 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 17990 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 17991 17992 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 17993 final long drawingCacheSize = 17994 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 17995 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 17996 if (width > 0 && height > 0) { 17997 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 17998 + " too large to fit into a software layer (or drawing cache), needs " 17999 + projectedBitmapSize + " bytes, only " 18000 + drawingCacheSize + " available"); 18001 } 18002 destroyDrawingCache(); 18003 mCachingFailed = true; 18004 return; 18005 } 18006 18007 boolean clear = true; 18008 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 18009 18010 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 18011 Bitmap.Config quality; 18012 if (!opaque) { 18013 // Never pick ARGB_4444 because it looks awful 18014 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 18015 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 18016 case DRAWING_CACHE_QUALITY_AUTO: 18017 case DRAWING_CACHE_QUALITY_LOW: 18018 case DRAWING_CACHE_QUALITY_HIGH: 18019 default: 18020 quality = Bitmap.Config.ARGB_8888; 18021 break; 18022 } 18023 } else { 18024 // Optimization for translucent windows 18025 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 18026 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 18027 } 18028 18029 // Try to cleanup memory 18030 if (bitmap != null) bitmap.recycle(); 18031 18032 try { 18033 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 18034 width, height, quality); 18035 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 18036 if (autoScale) { 18037 mDrawingCache = bitmap; 18038 } else { 18039 mUnscaledDrawingCache = bitmap; 18040 } 18041 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 18042 } catch (OutOfMemoryError e) { 18043 // If there is not enough memory to create the bitmap cache, just 18044 // ignore the issue as bitmap caches are not required to draw the 18045 // view hierarchy 18046 if (autoScale) { 18047 mDrawingCache = null; 18048 } else { 18049 mUnscaledDrawingCache = null; 18050 } 18051 mCachingFailed = true; 18052 return; 18053 } 18054 18055 clear = drawingCacheBackgroundColor != 0; 18056 } 18057 18058 Canvas canvas; 18059 if (attachInfo != null) { 18060 canvas = attachInfo.mCanvas; 18061 if (canvas == null) { 18062 canvas = new Canvas(); 18063 } 18064 canvas.setBitmap(bitmap); 18065 // Temporarily clobber the cached Canvas in case one of our children 18066 // is also using a drawing cache. Without this, the children would 18067 // steal the canvas by attaching their own bitmap to it and bad, bad 18068 // thing would happen (invisible views, corrupted drawings, etc.) 18069 attachInfo.mCanvas = null; 18070 } else { 18071 // This case should hopefully never or seldom happen 18072 canvas = new Canvas(bitmap); 18073 } 18074 18075 if (clear) { 18076 bitmap.eraseColor(drawingCacheBackgroundColor); 18077 } 18078 18079 computeScroll(); 18080 final int restoreCount = canvas.save(); 18081 18082 if (autoScale && scalingRequired) { 18083 final float scale = attachInfo.mApplicationScale; 18084 canvas.scale(scale, scale); 18085 } 18086 18087 canvas.translate(-mScrollX, -mScrollY); 18088 18089 mPrivateFlags |= PFLAG_DRAWN; 18090 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 18091 mLayerType != LAYER_TYPE_NONE) { 18092 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 18093 } 18094 18095 // Fast path for layouts with no backgrounds 18096 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18097 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18098 dispatchDraw(canvas); 18099 drawAutofilledHighlight(canvas); 18100 if (mOverlay != null && !mOverlay.isEmpty()) { 18101 mOverlay.getOverlayView().draw(canvas); 18102 } 18103 } else { 18104 draw(canvas); 18105 } 18106 18107 canvas.restoreToCount(restoreCount); 18108 canvas.setBitmap(null); 18109 18110 if (attachInfo != null) { 18111 // Restore the cached Canvas for our siblings 18112 attachInfo.mCanvas = canvas; 18113 } 18114 } 18115 18116 /** 18117 * Create a snapshot of the view into a bitmap. We should probably make 18118 * some form of this public, but should think about the API. 18119 * 18120 * @hide 18121 */ 18122 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 18123 int width = mRight - mLeft; 18124 int height = mBottom - mTop; 18125 18126 final AttachInfo attachInfo = mAttachInfo; 18127 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 18128 width = (int) ((width * scale) + 0.5f); 18129 height = (int) ((height * scale) + 0.5f); 18130 18131 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 18132 width > 0 ? width : 1, height > 0 ? height : 1, quality); 18133 if (bitmap == null) { 18134 throw new OutOfMemoryError(); 18135 } 18136 18137 Resources resources = getResources(); 18138 if (resources != null) { 18139 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 18140 } 18141 18142 Canvas canvas; 18143 if (attachInfo != null) { 18144 canvas = attachInfo.mCanvas; 18145 if (canvas == null) { 18146 canvas = new Canvas(); 18147 } 18148 canvas.setBitmap(bitmap); 18149 // Temporarily clobber the cached Canvas in case one of our children 18150 // is also using a drawing cache. Without this, the children would 18151 // steal the canvas by attaching their own bitmap to it and bad, bad 18152 // things would happen (invisible views, corrupted drawings, etc.) 18153 attachInfo.mCanvas = null; 18154 } else { 18155 // This case should hopefully never or seldom happen 18156 canvas = new Canvas(bitmap); 18157 } 18158 boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled(); 18159 canvas.setHwBitmapsInSwModeEnabled(true); 18160 if ((backgroundColor & 0xff000000) != 0) { 18161 bitmap.eraseColor(backgroundColor); 18162 } 18163 18164 computeScroll(); 18165 final int restoreCount = canvas.save(); 18166 canvas.scale(scale, scale); 18167 canvas.translate(-mScrollX, -mScrollY); 18168 18169 // Temporarily remove the dirty mask 18170 int flags = mPrivateFlags; 18171 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18172 18173 // Fast path for layouts with no backgrounds 18174 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18175 dispatchDraw(canvas); 18176 drawAutofilledHighlight(canvas); 18177 if (mOverlay != null && !mOverlay.isEmpty()) { 18178 mOverlay.getOverlayView().draw(canvas); 18179 } 18180 } else { 18181 draw(canvas); 18182 } 18183 18184 mPrivateFlags = flags; 18185 18186 canvas.restoreToCount(restoreCount); 18187 canvas.setBitmap(null); 18188 canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode); 18189 18190 if (attachInfo != null) { 18191 // Restore the cached Canvas for our siblings 18192 attachInfo.mCanvas = canvas; 18193 } 18194 18195 return bitmap; 18196 } 18197 18198 /** 18199 * Indicates whether this View is currently in edit mode. A View is usually 18200 * in edit mode when displayed within a developer tool. For instance, if 18201 * this View is being drawn by a visual user interface builder, this method 18202 * should return true. 18203 * 18204 * Subclasses should check the return value of this method to provide 18205 * different behaviors if their normal behavior might interfere with the 18206 * host environment. For instance: the class spawns a thread in its 18207 * constructor, the drawing code relies on device-specific features, etc. 18208 * 18209 * This method is usually checked in the drawing code of custom widgets. 18210 * 18211 * @return True if this View is in edit mode, false otherwise. 18212 */ 18213 public boolean isInEditMode() { 18214 return false; 18215 } 18216 18217 /** 18218 * If the View draws content inside its padding and enables fading edges, 18219 * it needs to support padding offsets. Padding offsets are added to the 18220 * fading edges to extend the length of the fade so that it covers pixels 18221 * drawn inside the padding. 18222 * 18223 * Subclasses of this class should override this method if they need 18224 * to draw content inside the padding. 18225 * 18226 * @return True if padding offset must be applied, false otherwise. 18227 * 18228 * @see #getLeftPaddingOffset() 18229 * @see #getRightPaddingOffset() 18230 * @see #getTopPaddingOffset() 18231 * @see #getBottomPaddingOffset() 18232 * 18233 * @since CURRENT 18234 */ 18235 protected boolean isPaddingOffsetRequired() { 18236 return false; 18237 } 18238 18239 /** 18240 * Amount by which to extend the left fading region. Called only when 18241 * {@link #isPaddingOffsetRequired()} returns true. 18242 * 18243 * @return The left padding offset in pixels. 18244 * 18245 * @see #isPaddingOffsetRequired() 18246 * 18247 * @since CURRENT 18248 */ 18249 protected int getLeftPaddingOffset() { 18250 return 0; 18251 } 18252 18253 /** 18254 * Amount by which to extend the right fading region. Called only when 18255 * {@link #isPaddingOffsetRequired()} returns true. 18256 * 18257 * @return The right padding offset in pixels. 18258 * 18259 * @see #isPaddingOffsetRequired() 18260 * 18261 * @since CURRENT 18262 */ 18263 protected int getRightPaddingOffset() { 18264 return 0; 18265 } 18266 18267 /** 18268 * Amount by which to extend the top fading region. Called only when 18269 * {@link #isPaddingOffsetRequired()} returns true. 18270 * 18271 * @return The top padding offset in pixels. 18272 * 18273 * @see #isPaddingOffsetRequired() 18274 * 18275 * @since CURRENT 18276 */ 18277 protected int getTopPaddingOffset() { 18278 return 0; 18279 } 18280 18281 /** 18282 * Amount by which to extend the bottom fading region. Called only when 18283 * {@link #isPaddingOffsetRequired()} returns true. 18284 * 18285 * @return The bottom padding offset in pixels. 18286 * 18287 * @see #isPaddingOffsetRequired() 18288 * 18289 * @since CURRENT 18290 */ 18291 protected int getBottomPaddingOffset() { 18292 return 0; 18293 } 18294 18295 /** 18296 * @hide 18297 * @param offsetRequired 18298 */ 18299 protected int getFadeTop(boolean offsetRequired) { 18300 int top = mPaddingTop; 18301 if (offsetRequired) top += getTopPaddingOffset(); 18302 return top; 18303 } 18304 18305 /** 18306 * @hide 18307 * @param offsetRequired 18308 */ 18309 protected int getFadeHeight(boolean offsetRequired) { 18310 int padding = mPaddingTop; 18311 if (offsetRequired) padding += getTopPaddingOffset(); 18312 return mBottom - mTop - mPaddingBottom - padding; 18313 } 18314 18315 /** 18316 * <p>Indicates whether this view is attached to a hardware accelerated 18317 * window or not.</p> 18318 * 18319 * <p>Even if this method returns true, it does not mean that every call 18320 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 18321 * accelerated {@link android.graphics.Canvas}. For instance, if this view 18322 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 18323 * window is hardware accelerated, 18324 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 18325 * return false, and this method will return true.</p> 18326 * 18327 * @return True if the view is attached to a window and the window is 18328 * hardware accelerated; false in any other case. 18329 */ 18330 @ViewDebug.ExportedProperty(category = "drawing") 18331 public boolean isHardwareAccelerated() { 18332 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 18333 } 18334 18335 /** 18336 * Sets a rectangular area on this view to which the view will be clipped 18337 * when it is drawn. Setting the value to null will remove the clip bounds 18338 * and the view will draw normally, using its full bounds. 18339 * 18340 * @param clipBounds The rectangular area, in the local coordinates of 18341 * this view, to which future drawing operations will be clipped. 18342 */ 18343 public void setClipBounds(Rect clipBounds) { 18344 if (clipBounds == mClipBounds 18345 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 18346 return; 18347 } 18348 if (clipBounds != null) { 18349 if (mClipBounds == null) { 18350 mClipBounds = new Rect(clipBounds); 18351 } else { 18352 mClipBounds.set(clipBounds); 18353 } 18354 } else { 18355 mClipBounds = null; 18356 } 18357 mRenderNode.setClipBounds(mClipBounds); 18358 invalidateViewProperty(false, false); 18359 } 18360 18361 /** 18362 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 18363 * 18364 * @return A copy of the current clip bounds if clip bounds are set, 18365 * otherwise null. 18366 */ 18367 public Rect getClipBounds() { 18368 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 18369 } 18370 18371 18372 /** 18373 * Populates an output rectangle with the clip bounds of the view, 18374 * returning {@code true} if successful or {@code false} if the view's 18375 * clip bounds are {@code null}. 18376 * 18377 * @param outRect rectangle in which to place the clip bounds of the view 18378 * @return {@code true} if successful or {@code false} if the view's 18379 * clip bounds are {@code null} 18380 */ 18381 public boolean getClipBounds(Rect outRect) { 18382 if (mClipBounds != null) { 18383 outRect.set(mClipBounds); 18384 return true; 18385 } 18386 return false; 18387 } 18388 18389 /** 18390 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 18391 * case of an active Animation being run on the view. 18392 */ 18393 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 18394 Animation a, boolean scalingRequired) { 18395 Transformation invalidationTransform; 18396 final int flags = parent.mGroupFlags; 18397 final boolean initialized = a.isInitialized(); 18398 if (!initialized) { 18399 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 18400 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 18401 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 18402 onAnimationStart(); 18403 } 18404 18405 final Transformation t = parent.getChildTransformation(); 18406 boolean more = a.getTransformation(drawingTime, t, 1f); 18407 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 18408 if (parent.mInvalidationTransformation == null) { 18409 parent.mInvalidationTransformation = new Transformation(); 18410 } 18411 invalidationTransform = parent.mInvalidationTransformation; 18412 a.getTransformation(drawingTime, invalidationTransform, 1f); 18413 } else { 18414 invalidationTransform = t; 18415 } 18416 18417 if (more) { 18418 if (!a.willChangeBounds()) { 18419 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 18420 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 18421 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 18422 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 18423 // The child need to draw an animation, potentially offscreen, so 18424 // make sure we do not cancel invalidate requests 18425 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18426 parent.invalidate(mLeft, mTop, mRight, mBottom); 18427 } 18428 } else { 18429 if (parent.mInvalidateRegion == null) { 18430 parent.mInvalidateRegion = new RectF(); 18431 } 18432 final RectF region = parent.mInvalidateRegion; 18433 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 18434 invalidationTransform); 18435 18436 // The child need to draw an animation, potentially offscreen, so 18437 // make sure we do not cancel invalidate requests 18438 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18439 18440 final int left = mLeft + (int) region.left; 18441 final int top = mTop + (int) region.top; 18442 parent.invalidate(left, top, left + (int) (region.width() + .5f), 18443 top + (int) (region.height() + .5f)); 18444 } 18445 } 18446 return more; 18447 } 18448 18449 /** 18450 * This method is called by getDisplayList() when a display list is recorded for a View. 18451 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 18452 */ 18453 void setDisplayListProperties(RenderNode renderNode) { 18454 if (renderNode != null) { 18455 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 18456 renderNode.setClipToBounds(mParent instanceof ViewGroup 18457 && ((ViewGroup) mParent).getClipChildren()); 18458 18459 float alpha = 1; 18460 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 18461 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18462 ViewGroup parentVG = (ViewGroup) mParent; 18463 final Transformation t = parentVG.getChildTransformation(); 18464 if (parentVG.getChildStaticTransformation(this, t)) { 18465 final int transformType = t.getTransformationType(); 18466 if (transformType != Transformation.TYPE_IDENTITY) { 18467 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 18468 alpha = t.getAlpha(); 18469 } 18470 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 18471 renderNode.setStaticMatrix(t.getMatrix()); 18472 } 18473 } 18474 } 18475 } 18476 if (mTransformationInfo != null) { 18477 alpha *= getFinalAlpha(); 18478 if (alpha < 1) { 18479 final int multipliedAlpha = (int) (255 * alpha); 18480 if (onSetAlpha(multipliedAlpha)) { 18481 alpha = 1; 18482 } 18483 } 18484 renderNode.setAlpha(alpha); 18485 } else if (alpha < 1) { 18486 renderNode.setAlpha(alpha); 18487 } 18488 } 18489 } 18490 18491 /** 18492 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 18493 * 18494 * This is where the View specializes rendering behavior based on layer type, 18495 * and hardware acceleration. 18496 */ 18497 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 18498 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 18499 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 18500 * 18501 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 18502 * HW accelerated, it can't handle drawing RenderNodes. 18503 */ 18504 boolean drawingWithRenderNode = mAttachInfo != null 18505 && mAttachInfo.mHardwareAccelerated 18506 && hardwareAcceleratedCanvas; 18507 18508 boolean more = false; 18509 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 18510 final int parentFlags = parent.mGroupFlags; 18511 18512 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 18513 parent.getChildTransformation().clear(); 18514 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18515 } 18516 18517 Transformation transformToApply = null; 18518 boolean concatMatrix = false; 18519 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 18520 final Animation a = getAnimation(); 18521 if (a != null) { 18522 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 18523 concatMatrix = a.willChangeTransformationMatrix(); 18524 if (concatMatrix) { 18525 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18526 } 18527 transformToApply = parent.getChildTransformation(); 18528 } else { 18529 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 18530 // No longer animating: clear out old animation matrix 18531 mRenderNode.setAnimationMatrix(null); 18532 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18533 } 18534 if (!drawingWithRenderNode 18535 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18536 final Transformation t = parent.getChildTransformation(); 18537 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 18538 if (hasTransform) { 18539 final int transformType = t.getTransformationType(); 18540 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 18541 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 18542 } 18543 } 18544 } 18545 18546 concatMatrix |= !childHasIdentityMatrix; 18547 18548 // Sets the flag as early as possible to allow draw() implementations 18549 // to call invalidate() successfully when doing animations 18550 mPrivateFlags |= PFLAG_DRAWN; 18551 18552 if (!concatMatrix && 18553 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 18554 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 18555 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 18556 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 18557 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 18558 return more; 18559 } 18560 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 18561 18562 if (hardwareAcceleratedCanvas) { 18563 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 18564 // retain the flag's value temporarily in the mRecreateDisplayList flag 18565 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 18566 mPrivateFlags &= ~PFLAG_INVALIDATED; 18567 } 18568 18569 RenderNode renderNode = null; 18570 Bitmap cache = null; 18571 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 18572 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 18573 if (layerType != LAYER_TYPE_NONE) { 18574 // If not drawing with RenderNode, treat HW layers as SW 18575 layerType = LAYER_TYPE_SOFTWARE; 18576 buildDrawingCache(true); 18577 } 18578 cache = getDrawingCache(true); 18579 } 18580 18581 if (drawingWithRenderNode) { 18582 // Delay getting the display list until animation-driven alpha values are 18583 // set up and possibly passed on to the view 18584 renderNode = updateDisplayListIfDirty(); 18585 if (!renderNode.isValid()) { 18586 // Uncommon, but possible. If a view is removed from the hierarchy during the call 18587 // to getDisplayList(), the display list will be marked invalid and we should not 18588 // try to use it again. 18589 renderNode = null; 18590 drawingWithRenderNode = false; 18591 } 18592 } 18593 18594 int sx = 0; 18595 int sy = 0; 18596 if (!drawingWithRenderNode) { 18597 computeScroll(); 18598 sx = mScrollX; 18599 sy = mScrollY; 18600 } 18601 18602 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 18603 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 18604 18605 int restoreTo = -1; 18606 if (!drawingWithRenderNode || transformToApply != null) { 18607 restoreTo = canvas.save(); 18608 } 18609 if (offsetForScroll) { 18610 canvas.translate(mLeft - sx, mTop - sy); 18611 } else { 18612 if (!drawingWithRenderNode) { 18613 canvas.translate(mLeft, mTop); 18614 } 18615 if (scalingRequired) { 18616 if (drawingWithRenderNode) { 18617 // TODO: Might not need this if we put everything inside the DL 18618 restoreTo = canvas.save(); 18619 } 18620 // mAttachInfo cannot be null, otherwise scalingRequired == false 18621 final float scale = 1.0f / mAttachInfo.mApplicationScale; 18622 canvas.scale(scale, scale); 18623 } 18624 } 18625 18626 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 18627 if (transformToApply != null 18628 || alpha < 1 18629 || !hasIdentityMatrix() 18630 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18631 if (transformToApply != null || !childHasIdentityMatrix) { 18632 int transX = 0; 18633 int transY = 0; 18634 18635 if (offsetForScroll) { 18636 transX = -sx; 18637 transY = -sy; 18638 } 18639 18640 if (transformToApply != null) { 18641 if (concatMatrix) { 18642 if (drawingWithRenderNode) { 18643 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 18644 } else { 18645 // Undo the scroll translation, apply the transformation matrix, 18646 // then redo the scroll translate to get the correct result. 18647 canvas.translate(-transX, -transY); 18648 canvas.concat(transformToApply.getMatrix()); 18649 canvas.translate(transX, transY); 18650 } 18651 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18652 } 18653 18654 float transformAlpha = transformToApply.getAlpha(); 18655 if (transformAlpha < 1) { 18656 alpha *= transformAlpha; 18657 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18658 } 18659 } 18660 18661 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 18662 canvas.translate(-transX, -transY); 18663 canvas.concat(getMatrix()); 18664 canvas.translate(transX, transY); 18665 } 18666 } 18667 18668 // Deal with alpha if it is or used to be <1 18669 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18670 if (alpha < 1) { 18671 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18672 } else { 18673 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18674 } 18675 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18676 if (!drawingWithDrawingCache) { 18677 final int multipliedAlpha = (int) (255 * alpha); 18678 if (!onSetAlpha(multipliedAlpha)) { 18679 if (drawingWithRenderNode) { 18680 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 18681 } else if (layerType == LAYER_TYPE_NONE) { 18682 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 18683 multipliedAlpha); 18684 } 18685 } else { 18686 // Alpha is handled by the child directly, clobber the layer's alpha 18687 mPrivateFlags |= PFLAG_ALPHA_SET; 18688 } 18689 } 18690 } 18691 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18692 onSetAlpha(255); 18693 mPrivateFlags &= ~PFLAG_ALPHA_SET; 18694 } 18695 18696 if (!drawingWithRenderNode) { 18697 // apply clips directly, since RenderNode won't do it for this draw 18698 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 18699 if (offsetForScroll) { 18700 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 18701 } else { 18702 if (!scalingRequired || cache == null) { 18703 canvas.clipRect(0, 0, getWidth(), getHeight()); 18704 } else { 18705 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 18706 } 18707 } 18708 } 18709 18710 if (mClipBounds != null) { 18711 // clip bounds ignore scroll 18712 canvas.clipRect(mClipBounds); 18713 } 18714 } 18715 18716 if (!drawingWithDrawingCache) { 18717 if (drawingWithRenderNode) { 18718 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18719 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 18720 } else { 18721 // Fast path for layouts with no backgrounds 18722 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18723 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18724 dispatchDraw(canvas); 18725 } else { 18726 draw(canvas); 18727 } 18728 } 18729 } else if (cache != null) { 18730 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18731 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 18732 // no layer paint, use temporary paint to draw bitmap 18733 Paint cachePaint = parent.mCachePaint; 18734 if (cachePaint == null) { 18735 cachePaint = new Paint(); 18736 cachePaint.setDither(false); 18737 parent.mCachePaint = cachePaint; 18738 } 18739 cachePaint.setAlpha((int) (alpha * 255)); 18740 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 18741 } else { 18742 // use layer paint to draw the bitmap, merging the two alphas, but also restore 18743 int layerPaintAlpha = mLayerPaint.getAlpha(); 18744 if (alpha < 1) { 18745 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 18746 } 18747 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 18748 if (alpha < 1) { 18749 mLayerPaint.setAlpha(layerPaintAlpha); 18750 } 18751 } 18752 } 18753 18754 if (restoreTo >= 0) { 18755 canvas.restoreToCount(restoreTo); 18756 } 18757 18758 if (a != null && !more) { 18759 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 18760 onSetAlpha(255); 18761 } 18762 parent.finishAnimatingView(this, a); 18763 } 18764 18765 if (more && hardwareAcceleratedCanvas) { 18766 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18767 // alpha animations should cause the child to recreate its display list 18768 invalidate(true); 18769 } 18770 } 18771 18772 mRecreateDisplayList = false; 18773 18774 return more; 18775 } 18776 18777 static Paint getDebugPaint() { 18778 if (sDebugPaint == null) { 18779 sDebugPaint = new Paint(); 18780 sDebugPaint.setAntiAlias(false); 18781 } 18782 return sDebugPaint; 18783 } 18784 18785 final int dipsToPixels(int dips) { 18786 float scale = getContext().getResources().getDisplayMetrics().density; 18787 return (int) (dips * scale + 0.5f); 18788 } 18789 18790 final private void debugDrawFocus(Canvas canvas) { 18791 if (isFocused()) { 18792 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 18793 final int l = mScrollX; 18794 final int r = l + mRight - mLeft; 18795 final int t = mScrollY; 18796 final int b = t + mBottom - mTop; 18797 18798 final Paint paint = getDebugPaint(); 18799 paint.setColor(DEBUG_CORNERS_COLOR); 18800 18801 // Draw squares in corners. 18802 paint.setStyle(Paint.Style.FILL); 18803 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 18804 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 18805 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 18806 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 18807 18808 // Draw big X across the view. 18809 paint.setStyle(Paint.Style.STROKE); 18810 canvas.drawLine(l, t, r, b, paint); 18811 canvas.drawLine(l, b, r, t, paint); 18812 } 18813 } 18814 18815 /** 18816 * Manually render this view (and all of its children) to the given Canvas. 18817 * The view must have already done a full layout before this function is 18818 * called. When implementing a view, implement 18819 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 18820 * If you do need to override this method, call the superclass version. 18821 * 18822 * @param canvas The Canvas to which the View is rendered. 18823 */ 18824 @CallSuper 18825 public void draw(Canvas canvas) { 18826 final int privateFlags = mPrivateFlags; 18827 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 18828 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 18829 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 18830 18831 /* 18832 * Draw traversal performs several drawing steps which must be executed 18833 * in the appropriate order: 18834 * 18835 * 1. Draw the background 18836 * 2. If necessary, save the canvas' layers to prepare for fading 18837 * 3. Draw view's content 18838 * 4. Draw children 18839 * 5. If necessary, draw the fading edges and restore layers 18840 * 6. Draw decorations (scrollbars for instance) 18841 */ 18842 18843 // Step 1, draw the background, if needed 18844 int saveCount; 18845 18846 if (!dirtyOpaque) { 18847 drawBackground(canvas); 18848 } 18849 18850 // skip step 2 & 5 if possible (common case) 18851 final int viewFlags = mViewFlags; 18852 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 18853 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 18854 if (!verticalEdges && !horizontalEdges) { 18855 // Step 3, draw the content 18856 if (!dirtyOpaque) onDraw(canvas); 18857 18858 // Step 4, draw the children 18859 dispatchDraw(canvas); 18860 18861 drawAutofilledHighlight(canvas); 18862 18863 // Overlay is part of the content and draws beneath Foreground 18864 if (mOverlay != null && !mOverlay.isEmpty()) { 18865 mOverlay.getOverlayView().dispatchDraw(canvas); 18866 } 18867 18868 // Step 6, draw decorations (foreground, scrollbars) 18869 onDrawForeground(canvas); 18870 18871 // Step 7, draw the default focus highlight 18872 drawDefaultFocusHighlight(canvas); 18873 18874 if (debugDraw()) { 18875 debugDrawFocus(canvas); 18876 } 18877 18878 // we're done... 18879 return; 18880 } 18881 18882 /* 18883 * Here we do the full fledged routine... 18884 * (this is an uncommon case where speed matters less, 18885 * this is why we repeat some of the tests that have been 18886 * done above) 18887 */ 18888 18889 boolean drawTop = false; 18890 boolean drawBottom = false; 18891 boolean drawLeft = false; 18892 boolean drawRight = false; 18893 18894 float topFadeStrength = 0.0f; 18895 float bottomFadeStrength = 0.0f; 18896 float leftFadeStrength = 0.0f; 18897 float rightFadeStrength = 0.0f; 18898 18899 // Step 2, save the canvas' layers 18900 int paddingLeft = mPaddingLeft; 18901 18902 final boolean offsetRequired = isPaddingOffsetRequired(); 18903 if (offsetRequired) { 18904 paddingLeft += getLeftPaddingOffset(); 18905 } 18906 18907 int left = mScrollX + paddingLeft; 18908 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 18909 int top = mScrollY + getFadeTop(offsetRequired); 18910 int bottom = top + getFadeHeight(offsetRequired); 18911 18912 if (offsetRequired) { 18913 right += getRightPaddingOffset(); 18914 bottom += getBottomPaddingOffset(); 18915 } 18916 18917 final ScrollabilityCache scrollabilityCache = mScrollCache; 18918 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 18919 int length = (int) fadeHeight; 18920 18921 // clip the fade length if top and bottom fades overlap 18922 // overlapping fades produce odd-looking artifacts 18923 if (verticalEdges && (top + length > bottom - length)) { 18924 length = (bottom - top) / 2; 18925 } 18926 18927 // also clip horizontal fades if necessary 18928 if (horizontalEdges && (left + length > right - length)) { 18929 length = (right - left) / 2; 18930 } 18931 18932 if (verticalEdges) { 18933 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 18934 drawTop = topFadeStrength * fadeHeight > 1.0f; 18935 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 18936 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 18937 } 18938 18939 if (horizontalEdges) { 18940 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 18941 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 18942 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 18943 drawRight = rightFadeStrength * fadeHeight > 1.0f; 18944 } 18945 18946 saveCount = canvas.getSaveCount(); 18947 18948 int solidColor = getSolidColor(); 18949 if (solidColor == 0) { 18950 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 18951 18952 if (drawTop) { 18953 canvas.saveLayer(left, top, right, top + length, null, flags); 18954 } 18955 18956 if (drawBottom) { 18957 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 18958 } 18959 18960 if (drawLeft) { 18961 canvas.saveLayer(left, top, left + length, bottom, null, flags); 18962 } 18963 18964 if (drawRight) { 18965 canvas.saveLayer(right - length, top, right, bottom, null, flags); 18966 } 18967 } else { 18968 scrollabilityCache.setFadeColor(solidColor); 18969 } 18970 18971 // Step 3, draw the content 18972 if (!dirtyOpaque) onDraw(canvas); 18973 18974 // Step 4, draw the children 18975 dispatchDraw(canvas); 18976 18977 // Step 5, draw the fade effect and restore layers 18978 final Paint p = scrollabilityCache.paint; 18979 final Matrix matrix = scrollabilityCache.matrix; 18980 final Shader fade = scrollabilityCache.shader; 18981 18982 if (drawTop) { 18983 matrix.setScale(1, fadeHeight * topFadeStrength); 18984 matrix.postTranslate(left, top); 18985 fade.setLocalMatrix(matrix); 18986 p.setShader(fade); 18987 canvas.drawRect(left, top, right, top + length, p); 18988 } 18989 18990 if (drawBottom) { 18991 matrix.setScale(1, fadeHeight * bottomFadeStrength); 18992 matrix.postRotate(180); 18993 matrix.postTranslate(left, bottom); 18994 fade.setLocalMatrix(matrix); 18995 p.setShader(fade); 18996 canvas.drawRect(left, bottom - length, right, bottom, p); 18997 } 18998 18999 if (drawLeft) { 19000 matrix.setScale(1, fadeHeight * leftFadeStrength); 19001 matrix.postRotate(-90); 19002 matrix.postTranslate(left, top); 19003 fade.setLocalMatrix(matrix); 19004 p.setShader(fade); 19005 canvas.drawRect(left, top, left + length, bottom, p); 19006 } 19007 19008 if (drawRight) { 19009 matrix.setScale(1, fadeHeight * rightFadeStrength); 19010 matrix.postRotate(90); 19011 matrix.postTranslate(right, top); 19012 fade.setLocalMatrix(matrix); 19013 p.setShader(fade); 19014 canvas.drawRect(right - length, top, right, bottom, p); 19015 } 19016 19017 canvas.restoreToCount(saveCount); 19018 19019 drawAutofilledHighlight(canvas); 19020 19021 // Overlay is part of the content and draws beneath Foreground 19022 if (mOverlay != null && !mOverlay.isEmpty()) { 19023 mOverlay.getOverlayView().dispatchDraw(canvas); 19024 } 19025 19026 // Step 6, draw decorations (foreground, scrollbars) 19027 onDrawForeground(canvas); 19028 19029 if (debugDraw()) { 19030 debugDrawFocus(canvas); 19031 } 19032 } 19033 19034 /** 19035 * Draws the background onto the specified canvas. 19036 * 19037 * @param canvas Canvas on which to draw the background 19038 */ 19039 private void drawBackground(Canvas canvas) { 19040 final Drawable background = mBackground; 19041 if (background == null) { 19042 return; 19043 } 19044 19045 setBackgroundBounds(); 19046 19047 // Attempt to use a display list if requested. 19048 if (canvas.isHardwareAccelerated() && mAttachInfo != null 19049 && mAttachInfo.mThreadedRenderer != null) { 19050 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 19051 19052 final RenderNode renderNode = mBackgroundRenderNode; 19053 if (renderNode != null && renderNode.isValid()) { 19054 setBackgroundRenderNodeProperties(renderNode); 19055 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 19056 return; 19057 } 19058 } 19059 19060 final int scrollX = mScrollX; 19061 final int scrollY = mScrollY; 19062 if ((scrollX | scrollY) == 0) { 19063 background.draw(canvas); 19064 } else { 19065 canvas.translate(scrollX, scrollY); 19066 background.draw(canvas); 19067 canvas.translate(-scrollX, -scrollY); 19068 } 19069 } 19070 19071 /** 19072 * Sets the correct background bounds and rebuilds the outline, if needed. 19073 * <p/> 19074 * This is called by LayoutLib. 19075 */ 19076 void setBackgroundBounds() { 19077 if (mBackgroundSizeChanged && mBackground != null) { 19078 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 19079 mBackgroundSizeChanged = false; 19080 rebuildOutline(); 19081 } 19082 } 19083 19084 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 19085 renderNode.setTranslationX(mScrollX); 19086 renderNode.setTranslationY(mScrollY); 19087 } 19088 19089 /** 19090 * Creates a new display list or updates the existing display list for the 19091 * specified Drawable. 19092 * 19093 * @param drawable Drawable for which to create a display list 19094 * @param renderNode Existing RenderNode, or {@code null} 19095 * @return A valid display list for the specified drawable 19096 */ 19097 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 19098 if (renderNode == null) { 19099 renderNode = RenderNode.create(drawable.getClass().getName(), this); 19100 } 19101 19102 final Rect bounds = drawable.getBounds(); 19103 final int width = bounds.width(); 19104 final int height = bounds.height(); 19105 final DisplayListCanvas canvas = renderNode.start(width, height); 19106 19107 // Reverse left/top translation done by drawable canvas, which will 19108 // instead be applied by rendernode's LTRB bounds below. This way, the 19109 // drawable's bounds match with its rendernode bounds and its content 19110 // will lie within those bounds in the rendernode tree. 19111 canvas.translate(-bounds.left, -bounds.top); 19112 19113 try { 19114 drawable.draw(canvas); 19115 } finally { 19116 renderNode.end(canvas); 19117 } 19118 19119 // Set up drawable properties that are view-independent. 19120 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 19121 renderNode.setProjectBackwards(drawable.isProjected()); 19122 renderNode.setProjectionReceiver(true); 19123 renderNode.setClipToBounds(false); 19124 return renderNode; 19125 } 19126 19127 /** 19128 * Returns the overlay for this view, creating it if it does not yet exist. 19129 * Adding drawables to the overlay will cause them to be displayed whenever 19130 * the view itself is redrawn. Objects in the overlay should be actively 19131 * managed: remove them when they should not be displayed anymore. The 19132 * overlay will always have the same size as its host view. 19133 * 19134 * <p>Note: Overlays do not currently work correctly with {@link 19135 * SurfaceView} or {@link TextureView}; contents in overlays for these 19136 * types of views may not display correctly.</p> 19137 * 19138 * @return The ViewOverlay object for this view. 19139 * @see ViewOverlay 19140 */ 19141 public ViewOverlay getOverlay() { 19142 if (mOverlay == null) { 19143 mOverlay = new ViewOverlay(mContext, this); 19144 } 19145 return mOverlay; 19146 } 19147 19148 /** 19149 * Override this if your view is known to always be drawn on top of a solid color background, 19150 * and needs to draw fading edges. Returning a non-zero color enables the view system to 19151 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 19152 * should be set to 0xFF. 19153 * 19154 * @see #setVerticalFadingEdgeEnabled(boolean) 19155 * @see #setHorizontalFadingEdgeEnabled(boolean) 19156 * 19157 * @return The known solid color background for this view, or 0 if the color may vary 19158 */ 19159 @ViewDebug.ExportedProperty(category = "drawing") 19160 @ColorInt 19161 public int getSolidColor() { 19162 return 0; 19163 } 19164 19165 /** 19166 * Build a human readable string representation of the specified view flags. 19167 * 19168 * @param flags the view flags to convert to a string 19169 * @return a String representing the supplied flags 19170 */ 19171 private static String printFlags(int flags) { 19172 String output = ""; 19173 int numFlags = 0; 19174 if ((flags & FOCUSABLE) == FOCUSABLE) { 19175 output += "TAKES_FOCUS"; 19176 numFlags++; 19177 } 19178 19179 switch (flags & VISIBILITY_MASK) { 19180 case INVISIBLE: 19181 if (numFlags > 0) { 19182 output += " "; 19183 } 19184 output += "INVISIBLE"; 19185 // USELESS HERE numFlags++; 19186 break; 19187 case GONE: 19188 if (numFlags > 0) { 19189 output += " "; 19190 } 19191 output += "GONE"; 19192 // USELESS HERE numFlags++; 19193 break; 19194 default: 19195 break; 19196 } 19197 return output; 19198 } 19199 19200 /** 19201 * Build a human readable string representation of the specified private 19202 * view flags. 19203 * 19204 * @param privateFlags the private view flags to convert to a string 19205 * @return a String representing the supplied flags 19206 */ 19207 private static String printPrivateFlags(int privateFlags) { 19208 String output = ""; 19209 int numFlags = 0; 19210 19211 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 19212 output += "WANTS_FOCUS"; 19213 numFlags++; 19214 } 19215 19216 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 19217 if (numFlags > 0) { 19218 output += " "; 19219 } 19220 output += "FOCUSED"; 19221 numFlags++; 19222 } 19223 19224 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 19225 if (numFlags > 0) { 19226 output += " "; 19227 } 19228 output += "SELECTED"; 19229 numFlags++; 19230 } 19231 19232 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 19233 if (numFlags > 0) { 19234 output += " "; 19235 } 19236 output += "IS_ROOT_NAMESPACE"; 19237 numFlags++; 19238 } 19239 19240 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 19241 if (numFlags > 0) { 19242 output += " "; 19243 } 19244 output += "HAS_BOUNDS"; 19245 numFlags++; 19246 } 19247 19248 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 19249 if (numFlags > 0) { 19250 output += " "; 19251 } 19252 output += "DRAWN"; 19253 // USELESS HERE numFlags++; 19254 } 19255 return output; 19256 } 19257 19258 /** 19259 * <p>Indicates whether or not this view's layout will be requested during 19260 * the next hierarchy layout pass.</p> 19261 * 19262 * @return true if the layout will be forced during next layout pass 19263 */ 19264 public boolean isLayoutRequested() { 19265 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19266 } 19267 19268 /** 19269 * Return true if o is a ViewGroup that is laying out using optical bounds. 19270 * @hide 19271 */ 19272 public static boolean isLayoutModeOptical(Object o) { 19273 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 19274 } 19275 19276 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 19277 Insets parentInsets = mParent instanceof View ? 19278 ((View) mParent).getOpticalInsets() : Insets.NONE; 19279 Insets childInsets = getOpticalInsets(); 19280 return setFrame( 19281 left + parentInsets.left - childInsets.left, 19282 top + parentInsets.top - childInsets.top, 19283 right + parentInsets.left + childInsets.right, 19284 bottom + parentInsets.top + childInsets.bottom); 19285 } 19286 19287 /** 19288 * Assign a size and position to a view and all of its 19289 * descendants 19290 * 19291 * <p>This is the second phase of the layout mechanism. 19292 * (The first is measuring). In this phase, each parent calls 19293 * layout on all of its children to position them. 19294 * This is typically done using the child measurements 19295 * that were stored in the measure pass().</p> 19296 * 19297 * <p>Derived classes should not override this method. 19298 * Derived classes with children should override 19299 * onLayout. In that method, they should 19300 * call layout on each of their children.</p> 19301 * 19302 * @param l Left position, relative to parent 19303 * @param t Top position, relative to parent 19304 * @param r Right position, relative to parent 19305 * @param b Bottom position, relative to parent 19306 */ 19307 @SuppressWarnings({"unchecked"}) 19308 public void layout(int l, int t, int r, int b) { 19309 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 19310 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 19311 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19312 } 19313 19314 int oldL = mLeft; 19315 int oldT = mTop; 19316 int oldB = mBottom; 19317 int oldR = mRight; 19318 19319 boolean changed = isLayoutModeOptical(mParent) ? 19320 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 19321 19322 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 19323 onLayout(changed, l, t, r, b); 19324 19325 if (shouldDrawRoundScrollbar()) { 19326 if(mRoundScrollbarRenderer == null) { 19327 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 19328 } 19329 } else { 19330 mRoundScrollbarRenderer = null; 19331 } 19332 19333 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 19334 19335 ListenerInfo li = mListenerInfo; 19336 if (li != null && li.mOnLayoutChangeListeners != null) { 19337 ArrayList<OnLayoutChangeListener> listenersCopy = 19338 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 19339 int numListeners = listenersCopy.size(); 19340 for (int i = 0; i < numListeners; ++i) { 19341 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 19342 } 19343 } 19344 } 19345 19346 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 19347 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 19348 19349 if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) { 19350 mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT; 19351 notifyEnterOrExitForAutoFillIfNeeded(true); 19352 } 19353 } 19354 19355 /** 19356 * Called from layout when this view should 19357 * assign a size and position to each of its children. 19358 * 19359 * Derived classes with children should override 19360 * this method and call layout on each of 19361 * their children. 19362 * @param changed This is a new size or position for this view 19363 * @param left Left position, relative to parent 19364 * @param top Top position, relative to parent 19365 * @param right Right position, relative to parent 19366 * @param bottom Bottom position, relative to parent 19367 */ 19368 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 19369 } 19370 19371 /** 19372 * Assign a size and position to this view. 19373 * 19374 * This is called from layout. 19375 * 19376 * @param left Left position, relative to parent 19377 * @param top Top position, relative to parent 19378 * @param right Right position, relative to parent 19379 * @param bottom Bottom position, relative to parent 19380 * @return true if the new size and position are different than the 19381 * previous ones 19382 * {@hide} 19383 */ 19384 protected boolean setFrame(int left, int top, int right, int bottom) { 19385 boolean changed = false; 19386 19387 if (DBG) { 19388 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 19389 + right + "," + bottom + ")"); 19390 } 19391 19392 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 19393 changed = true; 19394 19395 // Remember our drawn bit 19396 int drawn = mPrivateFlags & PFLAG_DRAWN; 19397 19398 int oldWidth = mRight - mLeft; 19399 int oldHeight = mBottom - mTop; 19400 int newWidth = right - left; 19401 int newHeight = bottom - top; 19402 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 19403 19404 // Invalidate our old position 19405 invalidate(sizeChanged); 19406 19407 mLeft = left; 19408 mTop = top; 19409 mRight = right; 19410 mBottom = bottom; 19411 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 19412 19413 mPrivateFlags |= PFLAG_HAS_BOUNDS; 19414 19415 19416 if (sizeChanged) { 19417 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 19418 } 19419 19420 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 19421 // If we are visible, force the DRAWN bit to on so that 19422 // this invalidate will go through (at least to our parent). 19423 // This is because someone may have invalidated this view 19424 // before this call to setFrame came in, thereby clearing 19425 // the DRAWN bit. 19426 mPrivateFlags |= PFLAG_DRAWN; 19427 invalidate(sizeChanged); 19428 // parent display list may need to be recreated based on a change in the bounds 19429 // of any child 19430 invalidateParentCaches(); 19431 } 19432 19433 // Reset drawn bit to original value (invalidate turns it off) 19434 mPrivateFlags |= drawn; 19435 19436 mBackgroundSizeChanged = true; 19437 mDefaultFocusHighlightSizeChanged = true; 19438 if (mForegroundInfo != null) { 19439 mForegroundInfo.mBoundsChanged = true; 19440 } 19441 19442 notifySubtreeAccessibilityStateChangedIfNeeded(); 19443 } 19444 return changed; 19445 } 19446 19447 /** 19448 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 19449 * @hide 19450 */ 19451 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 19452 setFrame(left, top, right, bottom); 19453 } 19454 19455 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 19456 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 19457 if (mOverlay != null) { 19458 mOverlay.getOverlayView().setRight(newWidth); 19459 mOverlay.getOverlayView().setBottom(newHeight); 19460 } 19461 rebuildOutline(); 19462 } 19463 19464 /** 19465 * Finalize inflating a view from XML. This is called as the last phase 19466 * of inflation, after all child views have been added. 19467 * 19468 * <p>Even if the subclass overrides onFinishInflate, they should always be 19469 * sure to call the super method, so that we get called. 19470 */ 19471 @CallSuper 19472 protected void onFinishInflate() { 19473 } 19474 19475 /** 19476 * Returns the resources associated with this view. 19477 * 19478 * @return Resources object. 19479 */ 19480 public Resources getResources() { 19481 return mResources; 19482 } 19483 19484 /** 19485 * Invalidates the specified Drawable. 19486 * 19487 * @param drawable the drawable to invalidate 19488 */ 19489 @Override 19490 public void invalidateDrawable(@NonNull Drawable drawable) { 19491 if (verifyDrawable(drawable)) { 19492 final Rect dirty = drawable.getDirtyBounds(); 19493 final int scrollX = mScrollX; 19494 final int scrollY = mScrollY; 19495 19496 invalidate(dirty.left + scrollX, dirty.top + scrollY, 19497 dirty.right + scrollX, dirty.bottom + scrollY); 19498 rebuildOutline(); 19499 } 19500 } 19501 19502 /** 19503 * Schedules an action on a drawable to occur at a specified time. 19504 * 19505 * @param who the recipient of the action 19506 * @param what the action to run on the drawable 19507 * @param when the time at which the action must occur. Uses the 19508 * {@link SystemClock#uptimeMillis} timebase. 19509 */ 19510 @Override 19511 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 19512 if (verifyDrawable(who) && what != null) { 19513 final long delay = when - SystemClock.uptimeMillis(); 19514 if (mAttachInfo != null) { 19515 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 19516 Choreographer.CALLBACK_ANIMATION, what, who, 19517 Choreographer.subtractFrameDelay(delay)); 19518 } else { 19519 // Postpone the runnable until we know 19520 // on which thread it needs to run. 19521 getRunQueue().postDelayed(what, delay); 19522 } 19523 } 19524 } 19525 19526 /** 19527 * Cancels a scheduled action on a drawable. 19528 * 19529 * @param who the recipient of the action 19530 * @param what the action to cancel 19531 */ 19532 @Override 19533 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 19534 if (verifyDrawable(who) && what != null) { 19535 if (mAttachInfo != null) { 19536 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19537 Choreographer.CALLBACK_ANIMATION, what, who); 19538 } 19539 getRunQueue().removeCallbacks(what); 19540 } 19541 } 19542 19543 /** 19544 * Unschedule any events associated with the given Drawable. This can be 19545 * used when selecting a new Drawable into a view, so that the previous 19546 * one is completely unscheduled. 19547 * 19548 * @param who The Drawable to unschedule. 19549 * 19550 * @see #drawableStateChanged 19551 */ 19552 public void unscheduleDrawable(Drawable who) { 19553 if (mAttachInfo != null && who != null) { 19554 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19555 Choreographer.CALLBACK_ANIMATION, null, who); 19556 } 19557 } 19558 19559 /** 19560 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 19561 * that the View directionality can and will be resolved before its Drawables. 19562 * 19563 * Will call {@link View#onResolveDrawables} when resolution is done. 19564 * 19565 * @hide 19566 */ 19567 protected void resolveDrawables() { 19568 // Drawables resolution may need to happen before resolving the layout direction (which is 19569 // done only during the measure() call). 19570 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 19571 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 19572 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 19573 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 19574 // direction to be resolved as its resolved value will be the same as its raw value. 19575 if (!isLayoutDirectionResolved() && 19576 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 19577 return; 19578 } 19579 19580 final int layoutDirection = isLayoutDirectionResolved() ? 19581 getLayoutDirection() : getRawLayoutDirection(); 19582 19583 if (mBackground != null) { 19584 mBackground.setLayoutDirection(layoutDirection); 19585 } 19586 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19587 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 19588 } 19589 if (mDefaultFocusHighlight != null) { 19590 mDefaultFocusHighlight.setLayoutDirection(layoutDirection); 19591 } 19592 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 19593 onResolveDrawables(layoutDirection); 19594 } 19595 19596 boolean areDrawablesResolved() { 19597 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 19598 } 19599 19600 /** 19601 * Called when layout direction has been resolved. 19602 * 19603 * The default implementation does nothing. 19604 * 19605 * @param layoutDirection The resolved layout direction. 19606 * 19607 * @see #LAYOUT_DIRECTION_LTR 19608 * @see #LAYOUT_DIRECTION_RTL 19609 * 19610 * @hide 19611 */ 19612 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 19613 } 19614 19615 /** 19616 * @hide 19617 */ 19618 protected void resetResolvedDrawables() { 19619 resetResolvedDrawablesInternal(); 19620 } 19621 19622 void resetResolvedDrawablesInternal() { 19623 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 19624 } 19625 19626 /** 19627 * If your view subclass is displaying its own Drawable objects, it should 19628 * override this function and return true for any Drawable it is 19629 * displaying. This allows animations for those drawables to be 19630 * scheduled. 19631 * 19632 * <p>Be sure to call through to the super class when overriding this 19633 * function. 19634 * 19635 * @param who The Drawable to verify. Return true if it is one you are 19636 * displaying, else return the result of calling through to the 19637 * super class. 19638 * 19639 * @return boolean If true than the Drawable is being displayed in the 19640 * view; else false and it is not allowed to animate. 19641 * 19642 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 19643 * @see #drawableStateChanged() 19644 */ 19645 @CallSuper 19646 protected boolean verifyDrawable(@NonNull Drawable who) { 19647 // Avoid verifying the scroll bar drawable so that we don't end up in 19648 // an invalidation loop. This effectively prevents the scroll bar 19649 // drawable from triggering invalidations and scheduling runnables. 19650 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who) 19651 || (mDefaultFocusHighlight == who); 19652 } 19653 19654 /** 19655 * This function is called whenever the state of the view changes in such 19656 * a way that it impacts the state of drawables being shown. 19657 * <p> 19658 * If the View has a StateListAnimator, it will also be called to run necessary state 19659 * change animations. 19660 * <p> 19661 * Be sure to call through to the superclass when overriding this function. 19662 * 19663 * @see Drawable#setState(int[]) 19664 */ 19665 @CallSuper 19666 protected void drawableStateChanged() { 19667 final int[] state = getDrawableState(); 19668 boolean changed = false; 19669 19670 final Drawable bg = mBackground; 19671 if (bg != null && bg.isStateful()) { 19672 changed |= bg.setState(state); 19673 } 19674 19675 final Drawable hl = mDefaultFocusHighlight; 19676 if (hl != null && hl.isStateful()) { 19677 changed |= hl.setState(state); 19678 } 19679 19680 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19681 if (fg != null && fg.isStateful()) { 19682 changed |= fg.setState(state); 19683 } 19684 19685 if (mScrollCache != null) { 19686 final Drawable scrollBar = mScrollCache.scrollBar; 19687 if (scrollBar != null && scrollBar.isStateful()) { 19688 changed |= scrollBar.setState(state) 19689 && mScrollCache.state != ScrollabilityCache.OFF; 19690 } 19691 } 19692 19693 if (mStateListAnimator != null) { 19694 mStateListAnimator.setState(state); 19695 } 19696 19697 if (changed) { 19698 invalidate(); 19699 } 19700 } 19701 19702 /** 19703 * This function is called whenever the view hotspot changes and needs to 19704 * be propagated to drawables or child views managed by the view. 19705 * <p> 19706 * Dispatching to child views is handled by 19707 * {@link #dispatchDrawableHotspotChanged(float, float)}. 19708 * <p> 19709 * Be sure to call through to the superclass when overriding this function. 19710 * 19711 * @param x hotspot x coordinate 19712 * @param y hotspot y coordinate 19713 */ 19714 @CallSuper 19715 public void drawableHotspotChanged(float x, float y) { 19716 if (mBackground != null) { 19717 mBackground.setHotspot(x, y); 19718 } 19719 if (mDefaultFocusHighlight != null) { 19720 mDefaultFocusHighlight.setHotspot(x, y); 19721 } 19722 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19723 mForegroundInfo.mDrawable.setHotspot(x, y); 19724 } 19725 19726 dispatchDrawableHotspotChanged(x, y); 19727 } 19728 19729 /** 19730 * Dispatches drawableHotspotChanged to all of this View's children. 19731 * 19732 * @param x hotspot x coordinate 19733 * @param y hotspot y coordinate 19734 * @see #drawableHotspotChanged(float, float) 19735 */ 19736 public void dispatchDrawableHotspotChanged(float x, float y) { 19737 } 19738 19739 /** 19740 * Call this to force a view to update its drawable state. This will cause 19741 * drawableStateChanged to be called on this view. Views that are interested 19742 * in the new state should call getDrawableState. 19743 * 19744 * @see #drawableStateChanged 19745 * @see #getDrawableState 19746 */ 19747 public void refreshDrawableState() { 19748 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 19749 drawableStateChanged(); 19750 19751 ViewParent parent = mParent; 19752 if (parent != null) { 19753 parent.childDrawableStateChanged(this); 19754 } 19755 } 19756 19757 /** 19758 * Create a default focus highlight if it doesn't exist. 19759 * @return a default focus highlight. 19760 */ 19761 private Drawable getDefaultFocusHighlightDrawable() { 19762 if (mDefaultFocusHighlightCache == null) { 19763 if (mContext != null) { 19764 final int[] attrs = new int[] { android.R.attr.selectableItemBackground }; 19765 final TypedArray ta = mContext.obtainStyledAttributes(attrs); 19766 mDefaultFocusHighlightCache = ta.getDrawable(0); 19767 ta.recycle(); 19768 } 19769 } 19770 return mDefaultFocusHighlightCache; 19771 } 19772 19773 /** 19774 * Set the current default focus highlight. 19775 * @param highlight the highlight drawable, or {@code null} if it's no longer needed. 19776 */ 19777 private void setDefaultFocusHighlight(Drawable highlight) { 19778 mDefaultFocusHighlight = highlight; 19779 mDefaultFocusHighlightSizeChanged = true; 19780 if (highlight != null) { 19781 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 19782 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 19783 } 19784 highlight.setLayoutDirection(getLayoutDirection()); 19785 if (highlight.isStateful()) { 19786 highlight.setState(getDrawableState()); 19787 } 19788 if (isAttachedToWindow()) { 19789 highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 19790 } 19791 // Set callback last, since the view may still be initializing. 19792 highlight.setCallback(this); 19793 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 19794 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 19795 mPrivateFlags |= PFLAG_SKIP_DRAW; 19796 } 19797 requestLayout(); 19798 invalidate(); 19799 } 19800 19801 /** 19802 * Check whether we need to draw a default focus highlight when this view gets focused, 19803 * which requires: 19804 * <ul> 19805 * <li>In the background, {@link android.R.attr#state_focused} is not defined.</li> 19806 * <li>This view is not in touch mode.</li> 19807 * <li>This view doesn't opt out for a default focus highlight, via 19808 * {@link #setDefaultFocusHighlightEnabled(boolean)}.</li> 19809 * <li>This view is attached to window.</li> 19810 * </ul> 19811 * @return {@code true} if a default focus highlight is needed. 19812 */ 19813 private boolean isDefaultFocusHighlightNeeded(Drawable background) { 19814 final boolean hasFocusStateSpecified = background == null || !background.isStateful() 19815 || !background.hasFocusStateSpecified(); 19816 return !isInTouchMode() && getDefaultFocusHighlightEnabled() && hasFocusStateSpecified 19817 && isAttachedToWindow() && sUseDefaultFocusHighlight; 19818 } 19819 19820 /** 19821 * When this view is focused, switches on/off the default focused highlight. 19822 * <p> 19823 * This always happens when this view is focused, and only at this moment the default focus 19824 * highlight can be visible. 19825 */ 19826 private void switchDefaultFocusHighlight() { 19827 if (isFocused()) { 19828 final boolean needed = isDefaultFocusHighlightNeeded(mBackground); 19829 final boolean active = mDefaultFocusHighlight != null; 19830 if (needed && !active) { 19831 setDefaultFocusHighlight(getDefaultFocusHighlightDrawable()); 19832 } else if (!needed && active) { 19833 // The highlight is no longer needed, so tear it down. 19834 setDefaultFocusHighlight(null); 19835 } 19836 } 19837 } 19838 19839 /** 19840 * Draw the default focus highlight onto the canvas. 19841 * @param canvas the canvas where we're drawing the highlight. 19842 */ 19843 private void drawDefaultFocusHighlight(Canvas canvas) { 19844 if (mDefaultFocusHighlight != null) { 19845 if (mDefaultFocusHighlightSizeChanged) { 19846 mDefaultFocusHighlightSizeChanged = false; 19847 final int l = mScrollX; 19848 final int r = l + mRight - mLeft; 19849 final int t = mScrollY; 19850 final int b = t + mBottom - mTop; 19851 mDefaultFocusHighlight.setBounds(l, t, r, b); 19852 } 19853 mDefaultFocusHighlight.draw(canvas); 19854 } 19855 } 19856 19857 /** 19858 * Return an array of resource IDs of the drawable states representing the 19859 * current state of the view. 19860 * 19861 * @return The current drawable state 19862 * 19863 * @see Drawable#setState(int[]) 19864 * @see #drawableStateChanged() 19865 * @see #onCreateDrawableState(int) 19866 */ 19867 public final int[] getDrawableState() { 19868 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 19869 return mDrawableState; 19870 } else { 19871 mDrawableState = onCreateDrawableState(0); 19872 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 19873 return mDrawableState; 19874 } 19875 } 19876 19877 /** 19878 * Generate the new {@link android.graphics.drawable.Drawable} state for 19879 * this view. This is called by the view 19880 * system when the cached Drawable state is determined to be invalid. To 19881 * retrieve the current state, you should use {@link #getDrawableState}. 19882 * 19883 * @param extraSpace if non-zero, this is the number of extra entries you 19884 * would like in the returned array in which you can place your own 19885 * states. 19886 * 19887 * @return Returns an array holding the current {@link Drawable} state of 19888 * the view. 19889 * 19890 * @see #mergeDrawableStates(int[], int[]) 19891 */ 19892 protected int[] onCreateDrawableState(int extraSpace) { 19893 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 19894 mParent instanceof View) { 19895 return ((View) mParent).onCreateDrawableState(extraSpace); 19896 } 19897 19898 int[] drawableState; 19899 19900 int privateFlags = mPrivateFlags; 19901 19902 int viewStateIndex = 0; 19903 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 19904 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 19905 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 19906 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 19907 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 19908 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 19909 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 19910 ThreadedRenderer.isAvailable()) { 19911 // This is set if HW acceleration is requested, even if the current 19912 // process doesn't allow it. This is just to allow app preview 19913 // windows to better match their app. 19914 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 19915 } 19916 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 19917 19918 final int privateFlags2 = mPrivateFlags2; 19919 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 19920 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 19921 } 19922 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 19923 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 19924 } 19925 19926 drawableState = StateSet.get(viewStateIndex); 19927 19928 //noinspection ConstantIfStatement 19929 if (false) { 19930 Log.i("View", "drawableStateIndex=" + viewStateIndex); 19931 Log.i("View", toString() 19932 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 19933 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 19934 + " fo=" + hasFocus() 19935 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 19936 + " wf=" + hasWindowFocus() 19937 + ": " + Arrays.toString(drawableState)); 19938 } 19939 19940 if (extraSpace == 0) { 19941 return drawableState; 19942 } 19943 19944 final int[] fullState; 19945 if (drawableState != null) { 19946 fullState = new int[drawableState.length + extraSpace]; 19947 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 19948 } else { 19949 fullState = new int[extraSpace]; 19950 } 19951 19952 return fullState; 19953 } 19954 19955 /** 19956 * Merge your own state values in <var>additionalState</var> into the base 19957 * state values <var>baseState</var> that were returned by 19958 * {@link #onCreateDrawableState(int)}. 19959 * 19960 * @param baseState The base state values returned by 19961 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 19962 * own additional state values. 19963 * 19964 * @param additionalState The additional state values you would like 19965 * added to <var>baseState</var>; this array is not modified. 19966 * 19967 * @return As a convenience, the <var>baseState</var> array you originally 19968 * passed into the function is returned. 19969 * 19970 * @see #onCreateDrawableState(int) 19971 */ 19972 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 19973 final int N = baseState.length; 19974 int i = N - 1; 19975 while (i >= 0 && baseState[i] == 0) { 19976 i--; 19977 } 19978 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 19979 return baseState; 19980 } 19981 19982 /** 19983 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 19984 * on all Drawable objects associated with this view. 19985 * <p> 19986 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 19987 * attached to this view. 19988 */ 19989 @CallSuper 19990 public void jumpDrawablesToCurrentState() { 19991 if (mBackground != null) { 19992 mBackground.jumpToCurrentState(); 19993 } 19994 if (mStateListAnimator != null) { 19995 mStateListAnimator.jumpToCurrentState(); 19996 } 19997 if (mDefaultFocusHighlight != null) { 19998 mDefaultFocusHighlight.jumpToCurrentState(); 19999 } 20000 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 20001 mForegroundInfo.mDrawable.jumpToCurrentState(); 20002 } 20003 } 20004 20005 /** 20006 * Sets the background color for this view. 20007 * @param color the color of the background 20008 */ 20009 @RemotableViewMethod 20010 public void setBackgroundColor(@ColorInt int color) { 20011 if (mBackground instanceof ColorDrawable) { 20012 ((ColorDrawable) mBackground.mutate()).setColor(color); 20013 computeOpaqueFlags(); 20014 mBackgroundResource = 0; 20015 } else { 20016 setBackground(new ColorDrawable(color)); 20017 } 20018 } 20019 20020 /** 20021 * Set the background to a given resource. The resource should refer to 20022 * a Drawable object or 0 to remove the background. 20023 * @param resid The identifier of the resource. 20024 * 20025 * @attr ref android.R.styleable#View_background 20026 */ 20027 @RemotableViewMethod 20028 public void setBackgroundResource(@DrawableRes int resid) { 20029 if (resid != 0 && resid == mBackgroundResource) { 20030 return; 20031 } 20032 20033 Drawable d = null; 20034 if (resid != 0) { 20035 d = mContext.getDrawable(resid); 20036 } 20037 setBackground(d); 20038 20039 mBackgroundResource = resid; 20040 } 20041 20042 /** 20043 * Set the background to a given Drawable, or remove the background. If the 20044 * background has padding, this View's padding is set to the background's 20045 * padding. However, when a background is removed, this View's padding isn't 20046 * touched. If setting the padding is desired, please use 20047 * {@link #setPadding(int, int, int, int)}. 20048 * 20049 * @param background The Drawable to use as the background, or null to remove the 20050 * background 20051 */ 20052 public void setBackground(Drawable background) { 20053 //noinspection deprecation 20054 setBackgroundDrawable(background); 20055 } 20056 20057 /** 20058 * @deprecated use {@link #setBackground(Drawable)} instead 20059 */ 20060 @Deprecated 20061 public void setBackgroundDrawable(Drawable background) { 20062 computeOpaqueFlags(); 20063 20064 if (background == mBackground) { 20065 return; 20066 } 20067 20068 boolean requestLayout = false; 20069 20070 mBackgroundResource = 0; 20071 20072 /* 20073 * Regardless of whether we're setting a new background or not, we want 20074 * to clear the previous drawable. setVisible first while we still have the callback set. 20075 */ 20076 if (mBackground != null) { 20077 if (isAttachedToWindow()) { 20078 mBackground.setVisible(false, false); 20079 } 20080 mBackground.setCallback(null); 20081 unscheduleDrawable(mBackground); 20082 } 20083 20084 if (background != null) { 20085 Rect padding = sThreadLocal.get(); 20086 if (padding == null) { 20087 padding = new Rect(); 20088 sThreadLocal.set(padding); 20089 } 20090 resetResolvedDrawablesInternal(); 20091 background.setLayoutDirection(getLayoutDirection()); 20092 if (background.getPadding(padding)) { 20093 resetResolvedPaddingInternal(); 20094 switch (background.getLayoutDirection()) { 20095 case LAYOUT_DIRECTION_RTL: 20096 mUserPaddingLeftInitial = padding.right; 20097 mUserPaddingRightInitial = padding.left; 20098 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 20099 break; 20100 case LAYOUT_DIRECTION_LTR: 20101 default: 20102 mUserPaddingLeftInitial = padding.left; 20103 mUserPaddingRightInitial = padding.right; 20104 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 20105 } 20106 mLeftPaddingDefined = false; 20107 mRightPaddingDefined = false; 20108 } 20109 20110 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 20111 // if it has a different minimum size, we should layout again 20112 if (mBackground == null 20113 || mBackground.getMinimumHeight() != background.getMinimumHeight() 20114 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 20115 requestLayout = true; 20116 } 20117 20118 // Set mBackground before we set this as the callback and start making other 20119 // background drawable state change calls. In particular, the setVisible call below 20120 // can result in drawables attempting to start animations or otherwise invalidate, 20121 // which requires the view set as the callback (us) to recognize the drawable as 20122 // belonging to it as per verifyDrawable. 20123 mBackground = background; 20124 if (background.isStateful()) { 20125 background.setState(getDrawableState()); 20126 } 20127 if (isAttachedToWindow()) { 20128 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 20129 } 20130 20131 applyBackgroundTint(); 20132 20133 // Set callback last, since the view may still be initializing. 20134 background.setCallback(this); 20135 20136 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 20137 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 20138 requestLayout = true; 20139 } 20140 } else { 20141 /* Remove the background */ 20142 mBackground = null; 20143 if ((mViewFlags & WILL_NOT_DRAW) != 0 20144 && (mDefaultFocusHighlight == null) 20145 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 20146 mPrivateFlags |= PFLAG_SKIP_DRAW; 20147 } 20148 20149 /* 20150 * When the background is set, we try to apply its padding to this 20151 * View. When the background is removed, we don't touch this View's 20152 * padding. This is noted in the Javadocs. Hence, we don't need to 20153 * requestLayout(), the invalidate() below is sufficient. 20154 */ 20155 20156 // The old background's minimum size could have affected this 20157 // View's layout, so let's requestLayout 20158 requestLayout = true; 20159 } 20160 20161 computeOpaqueFlags(); 20162 20163 if (requestLayout) { 20164 requestLayout(); 20165 } 20166 20167 mBackgroundSizeChanged = true; 20168 invalidate(true); 20169 invalidateOutline(); 20170 } 20171 20172 /** 20173 * Gets the background drawable 20174 * 20175 * @return The drawable used as the background for this view, if any. 20176 * 20177 * @see #setBackground(Drawable) 20178 * 20179 * @attr ref android.R.styleable#View_background 20180 */ 20181 public Drawable getBackground() { 20182 return mBackground; 20183 } 20184 20185 /** 20186 * Applies a tint to the background drawable. Does not modify the current tint 20187 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20188 * <p> 20189 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 20190 * mutate the drawable and apply the specified tint and tint mode using 20191 * {@link Drawable#setTintList(ColorStateList)}. 20192 * 20193 * @param tint the tint to apply, may be {@code null} to clear tint 20194 * 20195 * @attr ref android.R.styleable#View_backgroundTint 20196 * @see #getBackgroundTintList() 20197 * @see Drawable#setTintList(ColorStateList) 20198 */ 20199 public void setBackgroundTintList(@Nullable ColorStateList tint) { 20200 if (mBackgroundTint == null) { 20201 mBackgroundTint = new TintInfo(); 20202 } 20203 mBackgroundTint.mTintList = tint; 20204 mBackgroundTint.mHasTintList = true; 20205 20206 applyBackgroundTint(); 20207 } 20208 20209 /** 20210 * Return the tint applied to the background drawable, if specified. 20211 * 20212 * @return the tint applied to the background drawable 20213 * @attr ref android.R.styleable#View_backgroundTint 20214 * @see #setBackgroundTintList(ColorStateList) 20215 */ 20216 @Nullable 20217 public ColorStateList getBackgroundTintList() { 20218 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 20219 } 20220 20221 /** 20222 * Specifies the blending mode used to apply the tint specified by 20223 * {@link #setBackgroundTintList(ColorStateList)}} to the background 20224 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20225 * 20226 * @param tintMode the blending mode used to apply the tint, may be 20227 * {@code null} to clear tint 20228 * @attr ref android.R.styleable#View_backgroundTintMode 20229 * @see #getBackgroundTintMode() 20230 * @see Drawable#setTintMode(PorterDuff.Mode) 20231 */ 20232 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20233 if (mBackgroundTint == null) { 20234 mBackgroundTint = new TintInfo(); 20235 } 20236 mBackgroundTint.mTintMode = tintMode; 20237 mBackgroundTint.mHasTintMode = true; 20238 20239 applyBackgroundTint(); 20240 } 20241 20242 /** 20243 * Return the blending mode used to apply the tint to the background 20244 * drawable, if specified. 20245 * 20246 * @return the blending mode used to apply the tint to the background 20247 * drawable 20248 * @attr ref android.R.styleable#View_backgroundTintMode 20249 * @see #setBackgroundTintMode(PorterDuff.Mode) 20250 */ 20251 @Nullable 20252 public PorterDuff.Mode getBackgroundTintMode() { 20253 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 20254 } 20255 20256 private void applyBackgroundTint() { 20257 if (mBackground != null && mBackgroundTint != null) { 20258 final TintInfo tintInfo = mBackgroundTint; 20259 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20260 mBackground = mBackground.mutate(); 20261 20262 if (tintInfo.mHasTintList) { 20263 mBackground.setTintList(tintInfo.mTintList); 20264 } 20265 20266 if (tintInfo.mHasTintMode) { 20267 mBackground.setTintMode(tintInfo.mTintMode); 20268 } 20269 20270 // The drawable (or one of its children) may not have been 20271 // stateful before applying the tint, so let's try again. 20272 if (mBackground.isStateful()) { 20273 mBackground.setState(getDrawableState()); 20274 } 20275 } 20276 } 20277 } 20278 20279 /** 20280 * Returns the drawable used as the foreground of this View. The 20281 * foreground drawable, if non-null, is always drawn on top of the view's content. 20282 * 20283 * @return a Drawable or null if no foreground was set 20284 * 20285 * @see #onDrawForeground(Canvas) 20286 */ 20287 public Drawable getForeground() { 20288 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20289 } 20290 20291 /** 20292 * Supply a Drawable that is to be rendered on top of all of the content in the view. 20293 * 20294 * @param foreground the Drawable to be drawn on top of the children 20295 * 20296 * @attr ref android.R.styleable#View_foreground 20297 */ 20298 public void setForeground(Drawable foreground) { 20299 if (mForegroundInfo == null) { 20300 if (foreground == null) { 20301 // Nothing to do. 20302 return; 20303 } 20304 mForegroundInfo = new ForegroundInfo(); 20305 } 20306 20307 if (foreground == mForegroundInfo.mDrawable) { 20308 // Nothing to do 20309 return; 20310 } 20311 20312 if (mForegroundInfo.mDrawable != null) { 20313 if (isAttachedToWindow()) { 20314 mForegroundInfo.mDrawable.setVisible(false, false); 20315 } 20316 mForegroundInfo.mDrawable.setCallback(null); 20317 unscheduleDrawable(mForegroundInfo.mDrawable); 20318 } 20319 20320 mForegroundInfo.mDrawable = foreground; 20321 mForegroundInfo.mBoundsChanged = true; 20322 if (foreground != null) { 20323 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 20324 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 20325 } 20326 foreground.setLayoutDirection(getLayoutDirection()); 20327 if (foreground.isStateful()) { 20328 foreground.setState(getDrawableState()); 20329 } 20330 applyForegroundTint(); 20331 if (isAttachedToWindow()) { 20332 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 20333 } 20334 // Set callback last, since the view may still be initializing. 20335 foreground.setCallback(this); 20336 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 20337 && (mDefaultFocusHighlight == null)) { 20338 mPrivateFlags |= PFLAG_SKIP_DRAW; 20339 } 20340 requestLayout(); 20341 invalidate(); 20342 } 20343 20344 /** 20345 * Magic bit used to support features of framework-internal window decor implementation details. 20346 * This used to live exclusively in FrameLayout. 20347 * 20348 * @return true if the foreground should draw inside the padding region or false 20349 * if it should draw inset by the view's padding 20350 * @hide internal use only; only used by FrameLayout and internal screen layouts. 20351 */ 20352 public boolean isForegroundInsidePadding() { 20353 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 20354 } 20355 20356 /** 20357 * Describes how the foreground is positioned. 20358 * 20359 * @return foreground gravity. 20360 * 20361 * @see #setForegroundGravity(int) 20362 * 20363 * @attr ref android.R.styleable#View_foregroundGravity 20364 */ 20365 public int getForegroundGravity() { 20366 return mForegroundInfo != null ? mForegroundInfo.mGravity 20367 : Gravity.START | Gravity.TOP; 20368 } 20369 20370 /** 20371 * Describes how the foreground is positioned. Defaults to START and TOP. 20372 * 20373 * @param gravity see {@link android.view.Gravity} 20374 * 20375 * @see #getForegroundGravity() 20376 * 20377 * @attr ref android.R.styleable#View_foregroundGravity 20378 */ 20379 public void setForegroundGravity(int gravity) { 20380 if (mForegroundInfo == null) { 20381 mForegroundInfo = new ForegroundInfo(); 20382 } 20383 20384 if (mForegroundInfo.mGravity != gravity) { 20385 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 20386 gravity |= Gravity.START; 20387 } 20388 20389 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 20390 gravity |= Gravity.TOP; 20391 } 20392 20393 mForegroundInfo.mGravity = gravity; 20394 requestLayout(); 20395 } 20396 } 20397 20398 /** 20399 * Applies a tint to the foreground drawable. Does not modify the current tint 20400 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20401 * <p> 20402 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 20403 * mutate the drawable and apply the specified tint and tint mode using 20404 * {@link Drawable#setTintList(ColorStateList)}. 20405 * 20406 * @param tint the tint to apply, may be {@code null} to clear tint 20407 * 20408 * @attr ref android.R.styleable#View_foregroundTint 20409 * @see #getForegroundTintList() 20410 * @see Drawable#setTintList(ColorStateList) 20411 */ 20412 public void setForegroundTintList(@Nullable ColorStateList tint) { 20413 if (mForegroundInfo == null) { 20414 mForegroundInfo = new ForegroundInfo(); 20415 } 20416 if (mForegroundInfo.mTintInfo == null) { 20417 mForegroundInfo.mTintInfo = new TintInfo(); 20418 } 20419 mForegroundInfo.mTintInfo.mTintList = tint; 20420 mForegroundInfo.mTintInfo.mHasTintList = true; 20421 20422 applyForegroundTint(); 20423 } 20424 20425 /** 20426 * Return the tint applied to the foreground drawable, if specified. 20427 * 20428 * @return the tint applied to the foreground drawable 20429 * @attr ref android.R.styleable#View_foregroundTint 20430 * @see #setForegroundTintList(ColorStateList) 20431 */ 20432 @Nullable 20433 public ColorStateList getForegroundTintList() { 20434 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20435 ? mForegroundInfo.mTintInfo.mTintList : null; 20436 } 20437 20438 /** 20439 * Specifies the blending mode used to apply the tint specified by 20440 * {@link #setForegroundTintList(ColorStateList)}} to the background 20441 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20442 * 20443 * @param tintMode the blending mode used to apply the tint, may be 20444 * {@code null} to clear tint 20445 * @attr ref android.R.styleable#View_foregroundTintMode 20446 * @see #getForegroundTintMode() 20447 * @see Drawable#setTintMode(PorterDuff.Mode) 20448 */ 20449 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20450 if (mForegroundInfo == null) { 20451 mForegroundInfo = new ForegroundInfo(); 20452 } 20453 if (mForegroundInfo.mTintInfo == null) { 20454 mForegroundInfo.mTintInfo = new TintInfo(); 20455 } 20456 mForegroundInfo.mTintInfo.mTintMode = tintMode; 20457 mForegroundInfo.mTintInfo.mHasTintMode = true; 20458 20459 applyForegroundTint(); 20460 } 20461 20462 /** 20463 * Return the blending mode used to apply the tint to the foreground 20464 * drawable, if specified. 20465 * 20466 * @return the blending mode used to apply the tint to the foreground 20467 * drawable 20468 * @attr ref android.R.styleable#View_foregroundTintMode 20469 * @see #setForegroundTintMode(PorterDuff.Mode) 20470 */ 20471 @Nullable 20472 public PorterDuff.Mode getForegroundTintMode() { 20473 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20474 ? mForegroundInfo.mTintInfo.mTintMode : null; 20475 } 20476 20477 private void applyForegroundTint() { 20478 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20479 && mForegroundInfo.mTintInfo != null) { 20480 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 20481 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20482 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 20483 20484 if (tintInfo.mHasTintList) { 20485 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 20486 } 20487 20488 if (tintInfo.mHasTintMode) { 20489 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 20490 } 20491 20492 // The drawable (or one of its children) may not have been 20493 // stateful before applying the tint, so let's try again. 20494 if (mForegroundInfo.mDrawable.isStateful()) { 20495 mForegroundInfo.mDrawable.setState(getDrawableState()); 20496 } 20497 } 20498 } 20499 } 20500 20501 /** 20502 * Get the drawable to be overlayed when a view is autofilled 20503 * 20504 * @return The drawable 20505 * 20506 * @throws IllegalStateException if the drawable could not be found. 20507 */ 20508 @Nullable private Drawable getAutofilledDrawable() { 20509 // Lazily load the isAutofilled drawable. 20510 if (mAttachInfo.mAutofilledDrawable == null) { 20511 Context rootContext = getRootView().getContext(); 20512 TypedArray a = rootContext.getTheme().obtainStyledAttributes(AUTOFILL_HIGHLIGHT_ATTR); 20513 int attributeResourceId = a.getResourceId(0, 0); 20514 mAttachInfo.mAutofilledDrawable = rootContext.getDrawable(attributeResourceId); 20515 a.recycle(); 20516 } 20517 20518 return mAttachInfo.mAutofilledDrawable; 20519 } 20520 20521 /** 20522 * Draw {@link View#isAutofilled()} highlight over view if the view is autofilled. 20523 * 20524 * @param canvas The canvas to draw on 20525 */ 20526 private void drawAutofilledHighlight(@NonNull Canvas canvas) { 20527 if (isAutofilled()) { 20528 Drawable autofilledHighlight = getAutofilledDrawable(); 20529 20530 if (autofilledHighlight != null) { 20531 autofilledHighlight.setBounds(0, 0, getWidth(), getHeight()); 20532 autofilledHighlight.draw(canvas); 20533 } 20534 } 20535 } 20536 20537 /** 20538 * Draw any foreground content for this view. 20539 * 20540 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 20541 * drawable or other view-specific decorations. The foreground is drawn on top of the 20542 * primary view content.</p> 20543 * 20544 * @param canvas canvas to draw into 20545 */ 20546 public void onDrawForeground(Canvas canvas) { 20547 onDrawScrollIndicators(canvas); 20548 onDrawScrollBars(canvas); 20549 20550 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20551 if (foreground != null) { 20552 if (mForegroundInfo.mBoundsChanged) { 20553 mForegroundInfo.mBoundsChanged = false; 20554 final Rect selfBounds = mForegroundInfo.mSelfBounds; 20555 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 20556 20557 if (mForegroundInfo.mInsidePadding) { 20558 selfBounds.set(0, 0, getWidth(), getHeight()); 20559 } else { 20560 selfBounds.set(getPaddingLeft(), getPaddingTop(), 20561 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 20562 } 20563 20564 final int ld = getLayoutDirection(); 20565 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 20566 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 20567 foreground.setBounds(overlayBounds); 20568 } 20569 20570 foreground.draw(canvas); 20571 } 20572 } 20573 20574 /** 20575 * Sets the padding. The view may add on the space required to display 20576 * the scrollbars, depending on the style and visibility of the scrollbars. 20577 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 20578 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 20579 * from the values set in this call. 20580 * 20581 * @attr ref android.R.styleable#View_padding 20582 * @attr ref android.R.styleable#View_paddingBottom 20583 * @attr ref android.R.styleable#View_paddingLeft 20584 * @attr ref android.R.styleable#View_paddingRight 20585 * @attr ref android.R.styleable#View_paddingTop 20586 * @param left the left padding in pixels 20587 * @param top the top padding in pixels 20588 * @param right the right padding in pixels 20589 * @param bottom the bottom padding in pixels 20590 */ 20591 public void setPadding(int left, int top, int right, int bottom) { 20592 resetResolvedPaddingInternal(); 20593 20594 mUserPaddingStart = UNDEFINED_PADDING; 20595 mUserPaddingEnd = UNDEFINED_PADDING; 20596 20597 mUserPaddingLeftInitial = left; 20598 mUserPaddingRightInitial = right; 20599 20600 mLeftPaddingDefined = true; 20601 mRightPaddingDefined = true; 20602 20603 internalSetPadding(left, top, right, bottom); 20604 } 20605 20606 /** 20607 * @hide 20608 */ 20609 protected void internalSetPadding(int left, int top, int right, int bottom) { 20610 mUserPaddingLeft = left; 20611 mUserPaddingRight = right; 20612 mUserPaddingBottom = bottom; 20613 20614 final int viewFlags = mViewFlags; 20615 boolean changed = false; 20616 20617 // Common case is there are no scroll bars. 20618 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 20619 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 20620 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 20621 ? 0 : getVerticalScrollbarWidth(); 20622 switch (mVerticalScrollbarPosition) { 20623 case SCROLLBAR_POSITION_DEFAULT: 20624 if (isLayoutRtl()) { 20625 left += offset; 20626 } else { 20627 right += offset; 20628 } 20629 break; 20630 case SCROLLBAR_POSITION_RIGHT: 20631 right += offset; 20632 break; 20633 case SCROLLBAR_POSITION_LEFT: 20634 left += offset; 20635 break; 20636 } 20637 } 20638 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 20639 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 20640 ? 0 : getHorizontalScrollbarHeight(); 20641 } 20642 } 20643 20644 if (mPaddingLeft != left) { 20645 changed = true; 20646 mPaddingLeft = left; 20647 } 20648 if (mPaddingTop != top) { 20649 changed = true; 20650 mPaddingTop = top; 20651 } 20652 if (mPaddingRight != right) { 20653 changed = true; 20654 mPaddingRight = right; 20655 } 20656 if (mPaddingBottom != bottom) { 20657 changed = true; 20658 mPaddingBottom = bottom; 20659 } 20660 20661 if (changed) { 20662 requestLayout(); 20663 invalidateOutline(); 20664 } 20665 } 20666 20667 /** 20668 * Sets the relative padding. The view may add on the space required to display 20669 * the scrollbars, depending on the style and visibility of the scrollbars. 20670 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 20671 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 20672 * from the values set in this call. 20673 * 20674 * @attr ref android.R.styleable#View_padding 20675 * @attr ref android.R.styleable#View_paddingBottom 20676 * @attr ref android.R.styleable#View_paddingStart 20677 * @attr ref android.R.styleable#View_paddingEnd 20678 * @attr ref android.R.styleable#View_paddingTop 20679 * @param start the start padding in pixels 20680 * @param top the top padding in pixels 20681 * @param end the end padding in pixels 20682 * @param bottom the bottom padding in pixels 20683 */ 20684 public void setPaddingRelative(int start, int top, int end, int bottom) { 20685 resetResolvedPaddingInternal(); 20686 20687 mUserPaddingStart = start; 20688 mUserPaddingEnd = end; 20689 mLeftPaddingDefined = true; 20690 mRightPaddingDefined = true; 20691 20692 switch(getLayoutDirection()) { 20693 case LAYOUT_DIRECTION_RTL: 20694 mUserPaddingLeftInitial = end; 20695 mUserPaddingRightInitial = start; 20696 internalSetPadding(end, top, start, bottom); 20697 break; 20698 case LAYOUT_DIRECTION_LTR: 20699 default: 20700 mUserPaddingLeftInitial = start; 20701 mUserPaddingRightInitial = end; 20702 internalSetPadding(start, top, end, bottom); 20703 } 20704 } 20705 20706 /** 20707 * Returns the top padding of this view. 20708 * 20709 * @return the top padding in pixels 20710 */ 20711 public int getPaddingTop() { 20712 return mPaddingTop; 20713 } 20714 20715 /** 20716 * Returns the bottom padding of this view. If there are inset and enabled 20717 * scrollbars, this value may include the space required to display the 20718 * scrollbars as well. 20719 * 20720 * @return the bottom padding in pixels 20721 */ 20722 public int getPaddingBottom() { 20723 return mPaddingBottom; 20724 } 20725 20726 /** 20727 * Returns the left padding of this view. If there are inset and enabled 20728 * scrollbars, this value may include the space required to display the 20729 * scrollbars as well. 20730 * 20731 * @return the left padding in pixels 20732 */ 20733 public int getPaddingLeft() { 20734 if (!isPaddingResolved()) { 20735 resolvePadding(); 20736 } 20737 return mPaddingLeft; 20738 } 20739 20740 /** 20741 * Returns the start padding of this view depending on its resolved layout direction. 20742 * If there are inset and enabled scrollbars, this value may include the space 20743 * required to display the scrollbars as well. 20744 * 20745 * @return the start padding in pixels 20746 */ 20747 public int getPaddingStart() { 20748 if (!isPaddingResolved()) { 20749 resolvePadding(); 20750 } 20751 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20752 mPaddingRight : mPaddingLeft; 20753 } 20754 20755 /** 20756 * Returns the right padding of this view. If there are inset and enabled 20757 * scrollbars, this value may include the space required to display the 20758 * scrollbars as well. 20759 * 20760 * @return the right padding in pixels 20761 */ 20762 public int getPaddingRight() { 20763 if (!isPaddingResolved()) { 20764 resolvePadding(); 20765 } 20766 return mPaddingRight; 20767 } 20768 20769 /** 20770 * Returns the end padding of this view depending on its resolved layout direction. 20771 * If there are inset and enabled scrollbars, this value may include the space 20772 * required to display the scrollbars as well. 20773 * 20774 * @return the end padding in pixels 20775 */ 20776 public int getPaddingEnd() { 20777 if (!isPaddingResolved()) { 20778 resolvePadding(); 20779 } 20780 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20781 mPaddingLeft : mPaddingRight; 20782 } 20783 20784 /** 20785 * Return if the padding has been set through relative values 20786 * {@link #setPaddingRelative(int, int, int, int)} or through 20787 * @attr ref android.R.styleable#View_paddingStart or 20788 * @attr ref android.R.styleable#View_paddingEnd 20789 * 20790 * @return true if the padding is relative or false if it is not. 20791 */ 20792 public boolean isPaddingRelative() { 20793 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 20794 } 20795 20796 Insets computeOpticalInsets() { 20797 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 20798 } 20799 20800 /** 20801 * @hide 20802 */ 20803 public void resetPaddingToInitialValues() { 20804 if (isRtlCompatibilityMode()) { 20805 mPaddingLeft = mUserPaddingLeftInitial; 20806 mPaddingRight = mUserPaddingRightInitial; 20807 return; 20808 } 20809 if (isLayoutRtl()) { 20810 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 20811 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 20812 } else { 20813 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 20814 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 20815 } 20816 } 20817 20818 /** 20819 * @hide 20820 */ 20821 public Insets getOpticalInsets() { 20822 if (mLayoutInsets == null) { 20823 mLayoutInsets = computeOpticalInsets(); 20824 } 20825 return mLayoutInsets; 20826 } 20827 20828 /** 20829 * Set this view's optical insets. 20830 * 20831 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 20832 * property. Views that compute their own optical insets should call it as part of measurement. 20833 * This method does not request layout. If you are setting optical insets outside of 20834 * measure/layout itself you will want to call requestLayout() yourself. 20835 * </p> 20836 * @hide 20837 */ 20838 public void setOpticalInsets(Insets insets) { 20839 mLayoutInsets = insets; 20840 } 20841 20842 /** 20843 * Changes the selection state of this view. A view can be selected or not. 20844 * Note that selection is not the same as focus. Views are typically 20845 * selected in the context of an AdapterView like ListView or GridView; 20846 * the selected view is the view that is highlighted. 20847 * 20848 * @param selected true if the view must be selected, false otherwise 20849 */ 20850 public void setSelected(boolean selected) { 20851 //noinspection DoubleNegation 20852 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 20853 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 20854 if (!selected) resetPressedState(); 20855 invalidate(true); 20856 refreshDrawableState(); 20857 dispatchSetSelected(selected); 20858 if (selected) { 20859 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 20860 } else { 20861 notifyViewAccessibilityStateChangedIfNeeded( 20862 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 20863 } 20864 } 20865 } 20866 20867 /** 20868 * Dispatch setSelected to all of this View's children. 20869 * 20870 * @see #setSelected(boolean) 20871 * 20872 * @param selected The new selected state 20873 */ 20874 protected void dispatchSetSelected(boolean selected) { 20875 } 20876 20877 /** 20878 * Indicates the selection state of this view. 20879 * 20880 * @return true if the view is selected, false otherwise 20881 */ 20882 @ViewDebug.ExportedProperty 20883 public boolean isSelected() { 20884 return (mPrivateFlags & PFLAG_SELECTED) != 0; 20885 } 20886 20887 /** 20888 * Changes the activated state of this view. A view can be activated or not. 20889 * Note that activation is not the same as selection. Selection is 20890 * a transient property, representing the view (hierarchy) the user is 20891 * currently interacting with. Activation is a longer-term state that the 20892 * user can move views in and out of. For example, in a list view with 20893 * single or multiple selection enabled, the views in the current selection 20894 * set are activated. (Um, yeah, we are deeply sorry about the terminology 20895 * here.) The activated state is propagated down to children of the view it 20896 * is set on. 20897 * 20898 * @param activated true if the view must be activated, false otherwise 20899 */ 20900 public void setActivated(boolean activated) { 20901 //noinspection DoubleNegation 20902 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 20903 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 20904 invalidate(true); 20905 refreshDrawableState(); 20906 dispatchSetActivated(activated); 20907 } 20908 } 20909 20910 /** 20911 * Dispatch setActivated to all of this View's children. 20912 * 20913 * @see #setActivated(boolean) 20914 * 20915 * @param activated The new activated state 20916 */ 20917 protected void dispatchSetActivated(boolean activated) { 20918 } 20919 20920 /** 20921 * Indicates the activation state of this view. 20922 * 20923 * @return true if the view is activated, false otherwise 20924 */ 20925 @ViewDebug.ExportedProperty 20926 public boolean isActivated() { 20927 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 20928 } 20929 20930 /** 20931 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 20932 * observer can be used to get notifications when global events, like 20933 * layout, happen. 20934 * 20935 * The returned ViewTreeObserver observer is not guaranteed to remain 20936 * valid for the lifetime of this View. If the caller of this method keeps 20937 * a long-lived reference to ViewTreeObserver, it should always check for 20938 * the return value of {@link ViewTreeObserver#isAlive()}. 20939 * 20940 * @return The ViewTreeObserver for this view's hierarchy. 20941 */ 20942 public ViewTreeObserver getViewTreeObserver() { 20943 if (mAttachInfo != null) { 20944 return mAttachInfo.mTreeObserver; 20945 } 20946 if (mFloatingTreeObserver == null) { 20947 mFloatingTreeObserver = new ViewTreeObserver(mContext); 20948 } 20949 return mFloatingTreeObserver; 20950 } 20951 20952 /** 20953 * <p>Finds the topmost view in the current view hierarchy.</p> 20954 * 20955 * @return the topmost view containing this view 20956 */ 20957 public View getRootView() { 20958 if (mAttachInfo != null) { 20959 final View v = mAttachInfo.mRootView; 20960 if (v != null) { 20961 return v; 20962 } 20963 } 20964 20965 View parent = this; 20966 20967 while (parent.mParent != null && parent.mParent instanceof View) { 20968 parent = (View) parent.mParent; 20969 } 20970 20971 return parent; 20972 } 20973 20974 /** 20975 * Transforms a motion event from view-local coordinates to on-screen 20976 * coordinates. 20977 * 20978 * @param ev the view-local motion event 20979 * @return false if the transformation could not be applied 20980 * @hide 20981 */ 20982 public boolean toGlobalMotionEvent(MotionEvent ev) { 20983 final AttachInfo info = mAttachInfo; 20984 if (info == null) { 20985 return false; 20986 } 20987 20988 final Matrix m = info.mTmpMatrix; 20989 m.set(Matrix.IDENTITY_MATRIX); 20990 transformMatrixToGlobal(m); 20991 ev.transform(m); 20992 return true; 20993 } 20994 20995 /** 20996 * Transforms a motion event from on-screen coordinates to view-local 20997 * coordinates. 20998 * 20999 * @param ev the on-screen motion event 21000 * @return false if the transformation could not be applied 21001 * @hide 21002 */ 21003 public boolean toLocalMotionEvent(MotionEvent ev) { 21004 final AttachInfo info = mAttachInfo; 21005 if (info == null) { 21006 return false; 21007 } 21008 21009 final Matrix m = info.mTmpMatrix; 21010 m.set(Matrix.IDENTITY_MATRIX); 21011 transformMatrixToLocal(m); 21012 ev.transform(m); 21013 return true; 21014 } 21015 21016 /** 21017 * Modifies the input matrix such that it maps view-local coordinates to 21018 * on-screen coordinates. 21019 * 21020 * @param m input matrix to modify 21021 * @hide 21022 */ 21023 public void transformMatrixToGlobal(Matrix m) { 21024 final ViewParent parent = mParent; 21025 if (parent instanceof View) { 21026 final View vp = (View) parent; 21027 vp.transformMatrixToGlobal(m); 21028 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 21029 } else if (parent instanceof ViewRootImpl) { 21030 final ViewRootImpl vr = (ViewRootImpl) parent; 21031 vr.transformMatrixToGlobal(m); 21032 m.preTranslate(0, -vr.mCurScrollY); 21033 } 21034 21035 m.preTranslate(mLeft, mTop); 21036 21037 if (!hasIdentityMatrix()) { 21038 m.preConcat(getMatrix()); 21039 } 21040 } 21041 21042 /** 21043 * Modifies the input matrix such that it maps on-screen coordinates to 21044 * view-local coordinates. 21045 * 21046 * @param m input matrix to modify 21047 * @hide 21048 */ 21049 public void transformMatrixToLocal(Matrix m) { 21050 final ViewParent parent = mParent; 21051 if (parent instanceof View) { 21052 final View vp = (View) parent; 21053 vp.transformMatrixToLocal(m); 21054 m.postTranslate(vp.mScrollX, vp.mScrollY); 21055 } else if (parent instanceof ViewRootImpl) { 21056 final ViewRootImpl vr = (ViewRootImpl) parent; 21057 vr.transformMatrixToLocal(m); 21058 m.postTranslate(0, vr.mCurScrollY); 21059 } 21060 21061 m.postTranslate(-mLeft, -mTop); 21062 21063 if (!hasIdentityMatrix()) { 21064 m.postConcat(getInverseMatrix()); 21065 } 21066 } 21067 21068 /** 21069 * @hide 21070 */ 21071 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 21072 @ViewDebug.IntToString(from = 0, to = "x"), 21073 @ViewDebug.IntToString(from = 1, to = "y") 21074 }) 21075 public int[] getLocationOnScreen() { 21076 int[] location = new int[2]; 21077 getLocationOnScreen(location); 21078 return location; 21079 } 21080 21081 /** 21082 * <p>Computes the coordinates of this view on the screen. The argument 21083 * must be an array of two integers. After the method returns, the array 21084 * contains the x and y location in that order.</p> 21085 * 21086 * @param outLocation an array of two integers in which to hold the coordinates 21087 */ 21088 public void getLocationOnScreen(@Size(2) int[] outLocation) { 21089 getLocationInWindow(outLocation); 21090 21091 final AttachInfo info = mAttachInfo; 21092 if (info != null) { 21093 outLocation[0] += info.mWindowLeft; 21094 outLocation[1] += info.mWindowTop; 21095 } 21096 } 21097 21098 /** 21099 * <p>Computes the coordinates of this view in its window. The argument 21100 * must be an array of two integers. After the method returns, the array 21101 * contains the x and y location in that order.</p> 21102 * 21103 * @param outLocation an array of two integers in which to hold the coordinates 21104 */ 21105 public void getLocationInWindow(@Size(2) int[] outLocation) { 21106 if (outLocation == null || outLocation.length < 2) { 21107 throw new IllegalArgumentException("outLocation must be an array of two integers"); 21108 } 21109 21110 outLocation[0] = 0; 21111 outLocation[1] = 0; 21112 21113 transformFromViewToWindowSpace(outLocation); 21114 } 21115 21116 /** @hide */ 21117 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 21118 if (inOutLocation == null || inOutLocation.length < 2) { 21119 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 21120 } 21121 21122 if (mAttachInfo == null) { 21123 // When the view is not attached to a window, this method does not make sense 21124 inOutLocation[0] = inOutLocation[1] = 0; 21125 return; 21126 } 21127 21128 float position[] = mAttachInfo.mTmpTransformLocation; 21129 position[0] = inOutLocation[0]; 21130 position[1] = inOutLocation[1]; 21131 21132 if (!hasIdentityMatrix()) { 21133 getMatrix().mapPoints(position); 21134 } 21135 21136 position[0] += mLeft; 21137 position[1] += mTop; 21138 21139 ViewParent viewParent = mParent; 21140 while (viewParent instanceof View) { 21141 final View view = (View) viewParent; 21142 21143 position[0] -= view.mScrollX; 21144 position[1] -= view.mScrollY; 21145 21146 if (!view.hasIdentityMatrix()) { 21147 view.getMatrix().mapPoints(position); 21148 } 21149 21150 position[0] += view.mLeft; 21151 position[1] += view.mTop; 21152 21153 viewParent = view.mParent; 21154 } 21155 21156 if (viewParent instanceof ViewRootImpl) { 21157 // *cough* 21158 final ViewRootImpl vr = (ViewRootImpl) viewParent; 21159 position[1] -= vr.mCurScrollY; 21160 } 21161 21162 inOutLocation[0] = Math.round(position[0]); 21163 inOutLocation[1] = Math.round(position[1]); 21164 } 21165 21166 /** 21167 * @param id the id of the view to be found 21168 * @return the view of the specified id, null if cannot be found 21169 * @hide 21170 */ 21171 protected <T extends View> T findViewTraversal(@IdRes int id) { 21172 if (id == mID) { 21173 return (T) this; 21174 } 21175 return null; 21176 } 21177 21178 /** 21179 * @param tag the tag of the view to be found 21180 * @return the view of specified tag, null if cannot be found 21181 * @hide 21182 */ 21183 protected <T extends View> T findViewWithTagTraversal(Object tag) { 21184 if (tag != null && tag.equals(mTag)) { 21185 return (T) this; 21186 } 21187 return null; 21188 } 21189 21190 /** 21191 * @param predicate The predicate to evaluate. 21192 * @param childToSkip If not null, ignores this child during the recursive traversal. 21193 * @return The first view that matches the predicate or null. 21194 * @hide 21195 */ 21196 protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate, 21197 View childToSkip) { 21198 if (predicate.test(this)) { 21199 return (T) this; 21200 } 21201 return null; 21202 } 21203 21204 /** 21205 * Finds the first descendant view with the given ID, the view itself if 21206 * the ID matches {@link #getId()}, or {@code null} if the ID is invalid 21207 * (< 0) or there is no matching view in the hierarchy. 21208 * <p> 21209 * <strong>Note:</strong> In most cases -- depending on compiler support -- 21210 * the resulting view is automatically cast to the target class type. If 21211 * the target class type is unconstrained, an explicit cast may be 21212 * necessary. 21213 * 21214 * @param id the ID to search for 21215 * @return a view with given ID if found, or {@code null} otherwise 21216 * @see View#findViewById(int) 21217 */ 21218 @Nullable 21219 public final <T extends View> T findViewById(@IdRes int id) { 21220 if (id == NO_ID) { 21221 return null; 21222 } 21223 return findViewTraversal(id); 21224 } 21225 21226 /** 21227 * Finds a view by its unuque and stable accessibility id. 21228 * 21229 * @param accessibilityId The searched accessibility id. 21230 * @return The found view. 21231 */ 21232 final <T extends View> T findViewByAccessibilityId(int accessibilityId) { 21233 if (accessibilityId < 0) { 21234 return null; 21235 } 21236 T view = findViewByAccessibilityIdTraversal(accessibilityId); 21237 if (view != null) { 21238 return view.includeForAccessibility() ? view : null; 21239 } 21240 return null; 21241 } 21242 21243 /** 21244 * Performs the traversal to find a view by its unuque and stable accessibility id. 21245 * 21246 * <strong>Note:</strong>This method does not stop at the root namespace 21247 * boundary since the user can touch the screen at an arbitrary location 21248 * potentially crossing the root namespace bounday which will send an 21249 * accessibility event to accessibility services and they should be able 21250 * to obtain the event source. Also accessibility ids are guaranteed to be 21251 * unique in the window. 21252 * 21253 * @param accessibilityId The accessibility id. 21254 * @return The found view. 21255 * @hide 21256 */ 21257 public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) { 21258 if (getAccessibilityViewId() == accessibilityId) { 21259 return (T) this; 21260 } 21261 return null; 21262 } 21263 21264 /** 21265 * Look for a child view with the given tag. If this view has the given 21266 * tag, return this view. 21267 * 21268 * @param tag The tag to search for, using "tag.equals(getTag())". 21269 * @return The View that has the given tag in the hierarchy or null 21270 */ 21271 public final <T extends View> T findViewWithTag(Object tag) { 21272 if (tag == null) { 21273 return null; 21274 } 21275 return findViewWithTagTraversal(tag); 21276 } 21277 21278 /** 21279 * Look for a child view that matches the specified predicate. 21280 * If this view matches the predicate, return this view. 21281 * 21282 * @param predicate The predicate to evaluate. 21283 * @return The first view that matches the predicate or null. 21284 * @hide 21285 */ 21286 public final <T extends View> T findViewByPredicate(Predicate<View> predicate) { 21287 return findViewByPredicateTraversal(predicate, null); 21288 } 21289 21290 /** 21291 * Look for a child view that matches the specified predicate, 21292 * starting with the specified view and its descendents and then 21293 * recusively searching the ancestors and siblings of that view 21294 * until this view is reached. 21295 * 21296 * This method is useful in cases where the predicate does not match 21297 * a single unique view (perhaps multiple views use the same id) 21298 * and we are trying to find the view that is "closest" in scope to the 21299 * starting view. 21300 * 21301 * @param start The view to start from. 21302 * @param predicate The predicate to evaluate. 21303 * @return The first view that matches the predicate or null. 21304 * @hide 21305 */ 21306 public final <T extends View> T findViewByPredicateInsideOut( 21307 View start, Predicate<View> predicate) { 21308 View childToSkip = null; 21309 for (;;) { 21310 T view = start.findViewByPredicateTraversal(predicate, childToSkip); 21311 if (view != null || start == this) { 21312 return view; 21313 } 21314 21315 ViewParent parent = start.getParent(); 21316 if (parent == null || !(parent instanceof View)) { 21317 return null; 21318 } 21319 21320 childToSkip = start; 21321 start = (View) parent; 21322 } 21323 } 21324 21325 /** 21326 * Sets the identifier for this view. The identifier does not have to be 21327 * unique in this view's hierarchy. The identifier should be a positive 21328 * number. 21329 * 21330 * @see #NO_ID 21331 * @see #getId() 21332 * @see #findViewById(int) 21333 * 21334 * @param id a number used to identify the view 21335 * 21336 * @attr ref android.R.styleable#View_id 21337 */ 21338 public void setId(@IdRes int id) { 21339 mID = id; 21340 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 21341 mID = generateViewId(); 21342 } 21343 } 21344 21345 /** 21346 * {@hide} 21347 * 21348 * @param isRoot true if the view belongs to the root namespace, false 21349 * otherwise 21350 */ 21351 public void setIsRootNamespace(boolean isRoot) { 21352 if (isRoot) { 21353 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 21354 } else { 21355 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 21356 } 21357 } 21358 21359 /** 21360 * {@hide} 21361 * 21362 * @return true if the view belongs to the root namespace, false otherwise 21363 */ 21364 public boolean isRootNamespace() { 21365 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 21366 } 21367 21368 /** 21369 * Returns this view's identifier. 21370 * 21371 * @return a positive integer used to identify the view or {@link #NO_ID} 21372 * if the view has no ID 21373 * 21374 * @see #setId(int) 21375 * @see #findViewById(int) 21376 * @attr ref android.R.styleable#View_id 21377 */ 21378 @IdRes 21379 @ViewDebug.CapturedViewProperty 21380 public int getId() { 21381 return mID; 21382 } 21383 21384 /** 21385 * Returns this view's tag. 21386 * 21387 * @return the Object stored in this view as a tag, or {@code null} if not 21388 * set 21389 * 21390 * @see #setTag(Object) 21391 * @see #getTag(int) 21392 */ 21393 @ViewDebug.ExportedProperty 21394 public Object getTag() { 21395 return mTag; 21396 } 21397 21398 /** 21399 * Sets the tag associated with this view. A tag can be used to mark 21400 * a view in its hierarchy and does not have to be unique within the 21401 * hierarchy. Tags can also be used to store data within a view without 21402 * resorting to another data structure. 21403 * 21404 * @param tag an Object to tag the view with 21405 * 21406 * @see #getTag() 21407 * @see #setTag(int, Object) 21408 */ 21409 public void setTag(final Object tag) { 21410 mTag = tag; 21411 } 21412 21413 /** 21414 * Returns the tag associated with this view and the specified key. 21415 * 21416 * @param key The key identifying the tag 21417 * 21418 * @return the Object stored in this view as a tag, or {@code null} if not 21419 * set 21420 * 21421 * @see #setTag(int, Object) 21422 * @see #getTag() 21423 */ 21424 public Object getTag(int key) { 21425 if (mKeyedTags != null) return mKeyedTags.get(key); 21426 return null; 21427 } 21428 21429 /** 21430 * Sets a tag associated with this view and a key. A tag can be used 21431 * to mark a view in its hierarchy and does not have to be unique within 21432 * the hierarchy. Tags can also be used to store data within a view 21433 * without resorting to another data structure. 21434 * 21435 * The specified key should be an id declared in the resources of the 21436 * application to ensure it is unique (see the <a 21437 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 21438 * Keys identified as belonging to 21439 * the Android framework or not associated with any package will cause 21440 * an {@link IllegalArgumentException} to be thrown. 21441 * 21442 * @param key The key identifying the tag 21443 * @param tag An Object to tag the view with 21444 * 21445 * @throws IllegalArgumentException If they specified key is not valid 21446 * 21447 * @see #setTag(Object) 21448 * @see #getTag(int) 21449 */ 21450 public void setTag(int key, final Object tag) { 21451 // If the package id is 0x00 or 0x01, it's either an undefined package 21452 // or a framework id 21453 if ((key >>> 24) < 2) { 21454 throw new IllegalArgumentException("The key must be an application-specific " 21455 + "resource id."); 21456 } 21457 21458 setKeyedTag(key, tag); 21459 } 21460 21461 /** 21462 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 21463 * framework id. 21464 * 21465 * @hide 21466 */ 21467 public void setTagInternal(int key, Object tag) { 21468 if ((key >>> 24) != 0x1) { 21469 throw new IllegalArgumentException("The key must be a framework-specific " 21470 + "resource id."); 21471 } 21472 21473 setKeyedTag(key, tag); 21474 } 21475 21476 private void setKeyedTag(int key, Object tag) { 21477 if (mKeyedTags == null) { 21478 mKeyedTags = new SparseArray<Object>(2); 21479 } 21480 21481 mKeyedTags.put(key, tag); 21482 } 21483 21484 /** 21485 * Prints information about this view in the log output, with the tag 21486 * {@link #VIEW_LOG_TAG}. 21487 * 21488 * @hide 21489 */ 21490 public void debug() { 21491 debug(0); 21492 } 21493 21494 /** 21495 * Prints information about this view in the log output, with the tag 21496 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 21497 * indentation defined by the <code>depth</code>. 21498 * 21499 * @param depth the indentation level 21500 * 21501 * @hide 21502 */ 21503 protected void debug(int depth) { 21504 String output = debugIndent(depth - 1); 21505 21506 output += "+ " + this; 21507 int id = getId(); 21508 if (id != -1) { 21509 output += " (id=" + id + ")"; 21510 } 21511 Object tag = getTag(); 21512 if (tag != null) { 21513 output += " (tag=" + tag + ")"; 21514 } 21515 Log.d(VIEW_LOG_TAG, output); 21516 21517 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 21518 output = debugIndent(depth) + " FOCUSED"; 21519 Log.d(VIEW_LOG_TAG, output); 21520 } 21521 21522 output = debugIndent(depth); 21523 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 21524 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 21525 + "} "; 21526 Log.d(VIEW_LOG_TAG, output); 21527 21528 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 21529 || mPaddingBottom != 0) { 21530 output = debugIndent(depth); 21531 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 21532 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 21533 Log.d(VIEW_LOG_TAG, output); 21534 } 21535 21536 output = debugIndent(depth); 21537 output += "mMeasureWidth=" + mMeasuredWidth + 21538 " mMeasureHeight=" + mMeasuredHeight; 21539 Log.d(VIEW_LOG_TAG, output); 21540 21541 output = debugIndent(depth); 21542 if (mLayoutParams == null) { 21543 output += "BAD! no layout params"; 21544 } else { 21545 output = mLayoutParams.debug(output); 21546 } 21547 Log.d(VIEW_LOG_TAG, output); 21548 21549 output = debugIndent(depth); 21550 output += "flags={"; 21551 output += View.printFlags(mViewFlags); 21552 output += "}"; 21553 Log.d(VIEW_LOG_TAG, output); 21554 21555 output = debugIndent(depth); 21556 output += "privateFlags={"; 21557 output += View.printPrivateFlags(mPrivateFlags); 21558 output += "}"; 21559 Log.d(VIEW_LOG_TAG, output); 21560 } 21561 21562 /** 21563 * Creates a string of whitespaces used for indentation. 21564 * 21565 * @param depth the indentation level 21566 * @return a String containing (depth * 2 + 3) * 2 white spaces 21567 * 21568 * @hide 21569 */ 21570 protected static String debugIndent(int depth) { 21571 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 21572 for (int i = 0; i < (depth * 2) + 3; i++) { 21573 spaces.append(' ').append(' '); 21574 } 21575 return spaces.toString(); 21576 } 21577 21578 /** 21579 * <p>Return the offset of the widget's text baseline from the widget's top 21580 * boundary. If this widget does not support baseline alignment, this 21581 * method returns -1. </p> 21582 * 21583 * @return the offset of the baseline within the widget's bounds or -1 21584 * if baseline alignment is not supported 21585 */ 21586 @ViewDebug.ExportedProperty(category = "layout") 21587 public int getBaseline() { 21588 return -1; 21589 } 21590 21591 /** 21592 * Returns whether the view hierarchy is currently undergoing a layout pass. This 21593 * information is useful to avoid situations such as calling {@link #requestLayout()} during 21594 * a layout pass. 21595 * 21596 * @return whether the view hierarchy is currently undergoing a layout pass 21597 */ 21598 public boolean isInLayout() { 21599 ViewRootImpl viewRoot = getViewRootImpl(); 21600 return (viewRoot != null && viewRoot.isInLayout()); 21601 } 21602 21603 /** 21604 * Call this when something has changed which has invalidated the 21605 * layout of this view. This will schedule a layout pass of the view 21606 * tree. This should not be called while the view hierarchy is currently in a layout 21607 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 21608 * end of the current layout pass (and then layout will run again) or after the current 21609 * frame is drawn and the next layout occurs. 21610 * 21611 * <p>Subclasses which override this method should call the superclass method to 21612 * handle possible request-during-layout errors correctly.</p> 21613 */ 21614 @CallSuper 21615 public void requestLayout() { 21616 if (mMeasureCache != null) mMeasureCache.clear(); 21617 21618 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 21619 // Only trigger request-during-layout logic if this is the view requesting it, 21620 // not the views in its parent hierarchy 21621 ViewRootImpl viewRoot = getViewRootImpl(); 21622 if (viewRoot != null && viewRoot.isInLayout()) { 21623 if (!viewRoot.requestLayoutDuringLayout(this)) { 21624 return; 21625 } 21626 } 21627 mAttachInfo.mViewRequestingLayout = this; 21628 } 21629 21630 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21631 mPrivateFlags |= PFLAG_INVALIDATED; 21632 21633 if (mParent != null && !mParent.isLayoutRequested()) { 21634 mParent.requestLayout(); 21635 } 21636 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 21637 mAttachInfo.mViewRequestingLayout = null; 21638 } 21639 } 21640 21641 /** 21642 * Forces this view to be laid out during the next layout pass. 21643 * This method does not call requestLayout() or forceLayout() 21644 * on the parent. 21645 */ 21646 public void forceLayout() { 21647 if (mMeasureCache != null) mMeasureCache.clear(); 21648 21649 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21650 mPrivateFlags |= PFLAG_INVALIDATED; 21651 } 21652 21653 /** 21654 * <p> 21655 * This is called to find out how big a view should be. The parent 21656 * supplies constraint information in the width and height parameters. 21657 * </p> 21658 * 21659 * <p> 21660 * The actual measurement work of a view is performed in 21661 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 21662 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 21663 * </p> 21664 * 21665 * 21666 * @param widthMeasureSpec Horizontal space requirements as imposed by the 21667 * parent 21668 * @param heightMeasureSpec Vertical space requirements as imposed by the 21669 * parent 21670 * 21671 * @see #onMeasure(int, int) 21672 */ 21673 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 21674 boolean optical = isLayoutModeOptical(this); 21675 if (optical != isLayoutModeOptical(mParent)) { 21676 Insets insets = getOpticalInsets(); 21677 int oWidth = insets.left + insets.right; 21678 int oHeight = insets.top + insets.bottom; 21679 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 21680 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 21681 } 21682 21683 // Suppress sign extension for the low bytes 21684 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 21685 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 21686 21687 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 21688 21689 // Optimize layout by avoiding an extra EXACTLY pass when the view is 21690 // already measured as the correct size. In API 23 and below, this 21691 // extra pass is required to make LinearLayout re-distribute weight. 21692 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 21693 || heightMeasureSpec != mOldHeightMeasureSpec; 21694 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 21695 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 21696 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 21697 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 21698 final boolean needsLayout = specChanged 21699 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 21700 21701 if (forceLayout || needsLayout) { 21702 // first clears the measured dimension flag 21703 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 21704 21705 resolveRtlPropertiesIfNeeded(); 21706 21707 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 21708 if (cacheIndex < 0 || sIgnoreMeasureCache) { 21709 // measure ourselves, this should set the measured dimension flag back 21710 onMeasure(widthMeasureSpec, heightMeasureSpec); 21711 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21712 } else { 21713 long value = mMeasureCache.valueAt(cacheIndex); 21714 // Casting a long to int drops the high 32 bits, no mask needed 21715 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 21716 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21717 } 21718 21719 // flag not set, setMeasuredDimension() was not invoked, we raise 21720 // an exception to warn the developer 21721 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 21722 throw new IllegalStateException("View with id " + getId() + ": " 21723 + getClass().getName() + "#onMeasure() did not set the" 21724 + " measured dimension by calling" 21725 + " setMeasuredDimension()"); 21726 } 21727 21728 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 21729 } 21730 21731 mOldWidthMeasureSpec = widthMeasureSpec; 21732 mOldHeightMeasureSpec = heightMeasureSpec; 21733 21734 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 21735 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 21736 } 21737 21738 /** 21739 * <p> 21740 * Measure the view and its content to determine the measured width and the 21741 * measured height. This method is invoked by {@link #measure(int, int)} and 21742 * should be overridden by subclasses to provide accurate and efficient 21743 * measurement of their contents. 21744 * </p> 21745 * 21746 * <p> 21747 * <strong>CONTRACT:</strong> When overriding this method, you 21748 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 21749 * measured width and height of this view. Failure to do so will trigger an 21750 * <code>IllegalStateException</code>, thrown by 21751 * {@link #measure(int, int)}. Calling the superclass' 21752 * {@link #onMeasure(int, int)} is a valid use. 21753 * </p> 21754 * 21755 * <p> 21756 * The base class implementation of measure defaults to the background size, 21757 * unless a larger size is allowed by the MeasureSpec. Subclasses should 21758 * override {@link #onMeasure(int, int)} to provide better measurements of 21759 * their content. 21760 * </p> 21761 * 21762 * <p> 21763 * If this method is overridden, it is the subclass's responsibility to make 21764 * sure the measured height and width are at least the view's minimum height 21765 * and width ({@link #getSuggestedMinimumHeight()} and 21766 * {@link #getSuggestedMinimumWidth()}). 21767 * </p> 21768 * 21769 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 21770 * The requirements are encoded with 21771 * {@link android.view.View.MeasureSpec}. 21772 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 21773 * The requirements are encoded with 21774 * {@link android.view.View.MeasureSpec}. 21775 * 21776 * @see #getMeasuredWidth() 21777 * @see #getMeasuredHeight() 21778 * @see #setMeasuredDimension(int, int) 21779 * @see #getSuggestedMinimumHeight() 21780 * @see #getSuggestedMinimumWidth() 21781 * @see android.view.View.MeasureSpec#getMode(int) 21782 * @see android.view.View.MeasureSpec#getSize(int) 21783 */ 21784 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 21785 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 21786 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 21787 } 21788 21789 /** 21790 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 21791 * measured width and measured height. Failing to do so will trigger an 21792 * exception at measurement time.</p> 21793 * 21794 * @param measuredWidth The measured width of this view. May be a complex 21795 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21796 * {@link #MEASURED_STATE_TOO_SMALL}. 21797 * @param measuredHeight The measured height of this view. May be a complex 21798 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21799 * {@link #MEASURED_STATE_TOO_SMALL}. 21800 */ 21801 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 21802 boolean optical = isLayoutModeOptical(this); 21803 if (optical != isLayoutModeOptical(mParent)) { 21804 Insets insets = getOpticalInsets(); 21805 int opticalWidth = insets.left + insets.right; 21806 int opticalHeight = insets.top + insets.bottom; 21807 21808 measuredWidth += optical ? opticalWidth : -opticalWidth; 21809 measuredHeight += optical ? opticalHeight : -opticalHeight; 21810 } 21811 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 21812 } 21813 21814 /** 21815 * Sets the measured dimension without extra processing for things like optical bounds. 21816 * Useful for reapplying consistent values that have already been cooked with adjustments 21817 * for optical bounds, etc. such as those from the measurement cache. 21818 * 21819 * @param measuredWidth The measured width of this view. May be a complex 21820 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21821 * {@link #MEASURED_STATE_TOO_SMALL}. 21822 * @param measuredHeight The measured height of this view. May be a complex 21823 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21824 * {@link #MEASURED_STATE_TOO_SMALL}. 21825 */ 21826 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 21827 mMeasuredWidth = measuredWidth; 21828 mMeasuredHeight = measuredHeight; 21829 21830 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 21831 } 21832 21833 /** 21834 * Merge two states as returned by {@link #getMeasuredState()}. 21835 * @param curState The current state as returned from a view or the result 21836 * of combining multiple views. 21837 * @param newState The new view state to combine. 21838 * @return Returns a new integer reflecting the combination of the two 21839 * states. 21840 */ 21841 public static int combineMeasuredStates(int curState, int newState) { 21842 return curState | newState; 21843 } 21844 21845 /** 21846 * Version of {@link #resolveSizeAndState(int, int, int)} 21847 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 21848 */ 21849 public static int resolveSize(int size, int measureSpec) { 21850 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 21851 } 21852 21853 /** 21854 * Utility to reconcile a desired size and state, with constraints imposed 21855 * by a MeasureSpec. Will take the desired size, unless a different size 21856 * is imposed by the constraints. The returned value is a compound integer, 21857 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 21858 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 21859 * resulting size is smaller than the size the view wants to be. 21860 * 21861 * @param size How big the view wants to be. 21862 * @param measureSpec Constraints imposed by the parent. 21863 * @param childMeasuredState Size information bit mask for the view's 21864 * children. 21865 * @return Size information bit mask as defined by 21866 * {@link #MEASURED_SIZE_MASK} and 21867 * {@link #MEASURED_STATE_TOO_SMALL}. 21868 */ 21869 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 21870 final int specMode = MeasureSpec.getMode(measureSpec); 21871 final int specSize = MeasureSpec.getSize(measureSpec); 21872 final int result; 21873 switch (specMode) { 21874 case MeasureSpec.AT_MOST: 21875 if (specSize < size) { 21876 result = specSize | MEASURED_STATE_TOO_SMALL; 21877 } else { 21878 result = size; 21879 } 21880 break; 21881 case MeasureSpec.EXACTLY: 21882 result = specSize; 21883 break; 21884 case MeasureSpec.UNSPECIFIED: 21885 default: 21886 result = size; 21887 } 21888 return result | (childMeasuredState & MEASURED_STATE_MASK); 21889 } 21890 21891 /** 21892 * Utility to return a default size. Uses the supplied size if the 21893 * MeasureSpec imposed no constraints. Will get larger if allowed 21894 * by the MeasureSpec. 21895 * 21896 * @param size Default size for this view 21897 * @param measureSpec Constraints imposed by the parent 21898 * @return The size this view should be. 21899 */ 21900 public static int getDefaultSize(int size, int measureSpec) { 21901 int result = size; 21902 int specMode = MeasureSpec.getMode(measureSpec); 21903 int specSize = MeasureSpec.getSize(measureSpec); 21904 21905 switch (specMode) { 21906 case MeasureSpec.UNSPECIFIED: 21907 result = size; 21908 break; 21909 case MeasureSpec.AT_MOST: 21910 case MeasureSpec.EXACTLY: 21911 result = specSize; 21912 break; 21913 } 21914 return result; 21915 } 21916 21917 /** 21918 * Returns the suggested minimum height that the view should use. This 21919 * returns the maximum of the view's minimum height 21920 * and the background's minimum height 21921 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 21922 * <p> 21923 * When being used in {@link #onMeasure(int, int)}, the caller should still 21924 * ensure the returned height is within the requirements of the parent. 21925 * 21926 * @return The suggested minimum height of the view. 21927 */ 21928 protected int getSuggestedMinimumHeight() { 21929 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 21930 21931 } 21932 21933 /** 21934 * Returns the suggested minimum width that the view should use. This 21935 * returns the maximum of the view's minimum width 21936 * and the background's minimum width 21937 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 21938 * <p> 21939 * When being used in {@link #onMeasure(int, int)}, the caller should still 21940 * ensure the returned width is within the requirements of the parent. 21941 * 21942 * @return The suggested minimum width of the view. 21943 */ 21944 protected int getSuggestedMinimumWidth() { 21945 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 21946 } 21947 21948 /** 21949 * Returns the minimum height of the view. 21950 * 21951 * @return the minimum height the view will try to be, in pixels 21952 * 21953 * @see #setMinimumHeight(int) 21954 * 21955 * @attr ref android.R.styleable#View_minHeight 21956 */ 21957 public int getMinimumHeight() { 21958 return mMinHeight; 21959 } 21960 21961 /** 21962 * Sets the minimum height of the view. It is not guaranteed the view will 21963 * be able to achieve this minimum height (for example, if its parent layout 21964 * constrains it with less available height). 21965 * 21966 * @param minHeight The minimum height the view will try to be, in pixels 21967 * 21968 * @see #getMinimumHeight() 21969 * 21970 * @attr ref android.R.styleable#View_minHeight 21971 */ 21972 @RemotableViewMethod 21973 public void setMinimumHeight(int minHeight) { 21974 mMinHeight = minHeight; 21975 requestLayout(); 21976 } 21977 21978 /** 21979 * Returns the minimum width of the view. 21980 * 21981 * @return the minimum width the view will try to be, in pixels 21982 * 21983 * @see #setMinimumWidth(int) 21984 * 21985 * @attr ref android.R.styleable#View_minWidth 21986 */ 21987 public int getMinimumWidth() { 21988 return mMinWidth; 21989 } 21990 21991 /** 21992 * Sets the minimum width of the view. It is not guaranteed the view will 21993 * be able to achieve this minimum width (for example, if its parent layout 21994 * constrains it with less available width). 21995 * 21996 * @param minWidth The minimum width the view will try to be, in pixels 21997 * 21998 * @see #getMinimumWidth() 21999 * 22000 * @attr ref android.R.styleable#View_minWidth 22001 */ 22002 public void setMinimumWidth(int minWidth) { 22003 mMinWidth = minWidth; 22004 requestLayout(); 22005 22006 } 22007 22008 /** 22009 * Get the animation currently associated with this view. 22010 * 22011 * @return The animation that is currently playing or 22012 * scheduled to play for this view. 22013 */ 22014 public Animation getAnimation() { 22015 return mCurrentAnimation; 22016 } 22017 22018 /** 22019 * Start the specified animation now. 22020 * 22021 * @param animation the animation to start now 22022 */ 22023 public void startAnimation(Animation animation) { 22024 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 22025 setAnimation(animation); 22026 invalidateParentCaches(); 22027 invalidate(true); 22028 } 22029 22030 /** 22031 * Cancels any animations for this view. 22032 */ 22033 public void clearAnimation() { 22034 if (mCurrentAnimation != null) { 22035 mCurrentAnimation.detach(); 22036 } 22037 mCurrentAnimation = null; 22038 invalidateParentIfNeeded(); 22039 } 22040 22041 /** 22042 * Sets the next animation to play for this view. 22043 * If you want the animation to play immediately, use 22044 * {@link #startAnimation(android.view.animation.Animation)} instead. 22045 * This method provides allows fine-grained 22046 * control over the start time and invalidation, but you 22047 * must make sure that 1) the animation has a start time set, and 22048 * 2) the view's parent (which controls animations on its children) 22049 * will be invalidated when the animation is supposed to 22050 * start. 22051 * 22052 * @param animation The next animation, or null. 22053 */ 22054 public void setAnimation(Animation animation) { 22055 mCurrentAnimation = animation; 22056 22057 if (animation != null) { 22058 // If the screen is off assume the animation start time is now instead of 22059 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 22060 // would cause the animation to start when the screen turns back on 22061 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 22062 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 22063 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 22064 } 22065 animation.reset(); 22066 } 22067 } 22068 22069 /** 22070 * Invoked by a parent ViewGroup to notify the start of the animation 22071 * currently associated with this view. If you override this method, 22072 * always call super.onAnimationStart(); 22073 * 22074 * @see #setAnimation(android.view.animation.Animation) 22075 * @see #getAnimation() 22076 */ 22077 @CallSuper 22078 protected void onAnimationStart() { 22079 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 22080 } 22081 22082 /** 22083 * Invoked by a parent ViewGroup to notify the end of the animation 22084 * currently associated with this view. If you override this method, 22085 * always call super.onAnimationEnd(); 22086 * 22087 * @see #setAnimation(android.view.animation.Animation) 22088 * @see #getAnimation() 22089 */ 22090 @CallSuper 22091 protected void onAnimationEnd() { 22092 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 22093 } 22094 22095 /** 22096 * Invoked if there is a Transform that involves alpha. Subclass that can 22097 * draw themselves with the specified alpha should return true, and then 22098 * respect that alpha when their onDraw() is called. If this returns false 22099 * then the view may be redirected to draw into an offscreen buffer to 22100 * fulfill the request, which will look fine, but may be slower than if the 22101 * subclass handles it internally. The default implementation returns false. 22102 * 22103 * @param alpha The alpha (0..255) to apply to the view's drawing 22104 * @return true if the view can draw with the specified alpha. 22105 */ 22106 protected boolean onSetAlpha(int alpha) { 22107 return false; 22108 } 22109 22110 /** 22111 * This is used by the RootView to perform an optimization when 22112 * the view hierarchy contains one or several SurfaceView. 22113 * SurfaceView is always considered transparent, but its children are not, 22114 * therefore all View objects remove themselves from the global transparent 22115 * region (passed as a parameter to this function). 22116 * 22117 * @param region The transparent region for this ViewAncestor (window). 22118 * 22119 * @return Returns true if the effective visibility of the view at this 22120 * point is opaque, regardless of the transparent region; returns false 22121 * if it is possible for underlying windows to be seen behind the view. 22122 * 22123 * {@hide} 22124 */ 22125 public boolean gatherTransparentRegion(Region region) { 22126 final AttachInfo attachInfo = mAttachInfo; 22127 if (region != null && attachInfo != null) { 22128 final int pflags = mPrivateFlags; 22129 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 22130 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 22131 // remove it from the transparent region. 22132 final int[] location = attachInfo.mTransparentLocation; 22133 getLocationInWindow(location); 22134 // When a view has Z value, then it will be better to leave some area below the view 22135 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 22136 // the bottom part needs more offset than the left, top and right parts due to the 22137 // spot light effects. 22138 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 22139 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 22140 location[0] + mRight - mLeft + shadowOffset, 22141 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 22142 } else { 22143 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 22144 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 22145 // the background drawable's non-transparent parts from this transparent region. 22146 applyDrawableToTransparentRegion(mBackground, region); 22147 } 22148 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 22149 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 22150 // Similarly, we remove the foreground drawable's non-transparent parts. 22151 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 22152 } 22153 if (mDefaultFocusHighlight != null 22154 && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) { 22155 // Similarly, we remove the default focus highlight's non-transparent parts. 22156 applyDrawableToTransparentRegion(mDefaultFocusHighlight, region); 22157 } 22158 } 22159 } 22160 return true; 22161 } 22162 22163 /** 22164 * Play a sound effect for this view. 22165 * 22166 * <p>The framework will play sound effects for some built in actions, such as 22167 * clicking, but you may wish to play these effects in your widget, 22168 * for instance, for internal navigation. 22169 * 22170 * <p>The sound effect will only be played if sound effects are enabled by the user, and 22171 * {@link #isSoundEffectsEnabled()} is true. 22172 * 22173 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 22174 */ 22175 public void playSoundEffect(int soundConstant) { 22176 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 22177 return; 22178 } 22179 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 22180 } 22181 22182 /** 22183 * BZZZTT!!1! 22184 * 22185 * <p>Provide haptic feedback to the user for this view. 22186 * 22187 * <p>The framework will provide haptic feedback for some built in actions, 22188 * such as long presses, but you may wish to provide feedback for your 22189 * own widget. 22190 * 22191 * <p>The feedback will only be performed if 22192 * {@link #isHapticFeedbackEnabled()} is true. 22193 * 22194 * @param feedbackConstant One of the constants defined in 22195 * {@link HapticFeedbackConstants} 22196 */ 22197 public boolean performHapticFeedback(int feedbackConstant) { 22198 return performHapticFeedback(feedbackConstant, 0); 22199 } 22200 22201 /** 22202 * BZZZTT!!1! 22203 * 22204 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 22205 * 22206 * @param feedbackConstant One of the constants defined in 22207 * {@link HapticFeedbackConstants} 22208 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 22209 */ 22210 public boolean performHapticFeedback(int feedbackConstant, int flags) { 22211 if (mAttachInfo == null) { 22212 return false; 22213 } 22214 //noinspection SimplifiableIfStatement 22215 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 22216 && !isHapticFeedbackEnabled()) { 22217 return false; 22218 } 22219 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 22220 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 22221 } 22222 22223 /** 22224 * Request that the visibility of the status bar or other screen/window 22225 * decorations be changed. 22226 * 22227 * <p>This method is used to put the over device UI into temporary modes 22228 * where the user's attention is focused more on the application content, 22229 * by dimming or hiding surrounding system affordances. This is typically 22230 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 22231 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 22232 * to be placed behind the action bar (and with these flags other system 22233 * affordances) so that smooth transitions between hiding and showing them 22234 * can be done. 22235 * 22236 * <p>Two representative examples of the use of system UI visibility is 22237 * implementing a content browsing application (like a magazine reader) 22238 * and a video playing application. 22239 * 22240 * <p>The first code shows a typical implementation of a View in a content 22241 * browsing application. In this implementation, the application goes 22242 * into a content-oriented mode by hiding the status bar and action bar, 22243 * and putting the navigation elements into lights out mode. The user can 22244 * then interact with content while in this mode. Such an application should 22245 * provide an easy way for the user to toggle out of the mode (such as to 22246 * check information in the status bar or access notifications). In the 22247 * implementation here, this is done simply by tapping on the content. 22248 * 22249 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 22250 * content} 22251 * 22252 * <p>This second code sample shows a typical implementation of a View 22253 * in a video playing application. In this situation, while the video is 22254 * playing the application would like to go into a complete full-screen mode, 22255 * to use as much of the display as possible for the video. When in this state 22256 * the user can not interact with the application; the system intercepts 22257 * touching on the screen to pop the UI out of full screen mode. See 22258 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 22259 * 22260 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 22261 * content} 22262 * 22263 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22264 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22265 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22266 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22267 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22268 */ 22269 public void setSystemUiVisibility(int visibility) { 22270 if (visibility != mSystemUiVisibility) { 22271 mSystemUiVisibility = visibility; 22272 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22273 mParent.recomputeViewAttributes(this); 22274 } 22275 } 22276 } 22277 22278 /** 22279 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 22280 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22281 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22282 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22283 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22284 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22285 */ 22286 public int getSystemUiVisibility() { 22287 return mSystemUiVisibility; 22288 } 22289 22290 /** 22291 * Returns the current system UI visibility that is currently set for 22292 * the entire window. This is the combination of the 22293 * {@link #setSystemUiVisibility(int)} values supplied by all of the 22294 * views in the window. 22295 */ 22296 public int getWindowSystemUiVisibility() { 22297 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 22298 } 22299 22300 /** 22301 * Override to find out when the window's requested system UI visibility 22302 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 22303 * This is different from the callbacks received through 22304 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 22305 * in that this is only telling you about the local request of the window, 22306 * not the actual values applied by the system. 22307 */ 22308 public void onWindowSystemUiVisibilityChanged(int visible) { 22309 } 22310 22311 /** 22312 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 22313 * the view hierarchy. 22314 */ 22315 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 22316 onWindowSystemUiVisibilityChanged(visible); 22317 } 22318 22319 /** 22320 * Set a listener to receive callbacks when the visibility of the system bar changes. 22321 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 22322 */ 22323 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 22324 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 22325 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22326 mParent.recomputeViewAttributes(this); 22327 } 22328 } 22329 22330 /** 22331 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 22332 * the view hierarchy. 22333 */ 22334 public void dispatchSystemUiVisibilityChanged(int visibility) { 22335 ListenerInfo li = mListenerInfo; 22336 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 22337 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 22338 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 22339 } 22340 } 22341 22342 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 22343 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 22344 if (val != mSystemUiVisibility) { 22345 setSystemUiVisibility(val); 22346 return true; 22347 } 22348 return false; 22349 } 22350 22351 /** @hide */ 22352 public void setDisabledSystemUiVisibility(int flags) { 22353 if (mAttachInfo != null) { 22354 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 22355 mAttachInfo.mDisabledSystemUiVisibility = flags; 22356 if (mParent != null) { 22357 mParent.recomputeViewAttributes(this); 22358 } 22359 } 22360 } 22361 } 22362 22363 /** 22364 * Creates an image that the system displays during the drag and drop 22365 * operation. This is called a "drag shadow". The default implementation 22366 * for a DragShadowBuilder based on a View returns an image that has exactly the same 22367 * appearance as the given View. The default also positions the center of the drag shadow 22368 * directly under the touch point. If no View is provided (the constructor with no parameters 22369 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 22370 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 22371 * default is an invisible drag shadow. 22372 * <p> 22373 * You are not required to use the View you provide to the constructor as the basis of the 22374 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 22375 * anything you want as the drag shadow. 22376 * </p> 22377 * <p> 22378 * You pass a DragShadowBuilder object to the system when you start the drag. The system 22379 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 22380 * size and position of the drag shadow. It uses this data to construct a 22381 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 22382 * so that your application can draw the shadow image in the Canvas. 22383 * </p> 22384 * 22385 * <div class="special reference"> 22386 * <h3>Developer Guides</h3> 22387 * <p>For a guide to implementing drag and drop features, read the 22388 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22389 * </div> 22390 */ 22391 public static class DragShadowBuilder { 22392 private final WeakReference<View> mView; 22393 22394 /** 22395 * Constructs a shadow image builder based on a View. By default, the resulting drag 22396 * shadow will have the same appearance and dimensions as the View, with the touch point 22397 * over the center of the View. 22398 * @param view A View. Any View in scope can be used. 22399 */ 22400 public DragShadowBuilder(View view) { 22401 mView = new WeakReference<View>(view); 22402 } 22403 22404 /** 22405 * Construct a shadow builder object with no associated View. This 22406 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 22407 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 22408 * to supply the drag shadow's dimensions and appearance without 22409 * reference to any View object. If they are not overridden, then the result is an 22410 * invisible drag shadow. 22411 */ 22412 public DragShadowBuilder() { 22413 mView = new WeakReference<View>(null); 22414 } 22415 22416 /** 22417 * Returns the View object that had been passed to the 22418 * {@link #View.DragShadowBuilder(View)} 22419 * constructor. If that View parameter was {@code null} or if the 22420 * {@link #View.DragShadowBuilder()} 22421 * constructor was used to instantiate the builder object, this method will return 22422 * null. 22423 * 22424 * @return The View object associate with this builder object. 22425 */ 22426 @SuppressWarnings({"JavadocReference"}) 22427 final public View getView() { 22428 return mView.get(); 22429 } 22430 22431 /** 22432 * Provides the metrics for the shadow image. These include the dimensions of 22433 * the shadow image, and the point within that shadow that should 22434 * be centered under the touch location while dragging. 22435 * <p> 22436 * The default implementation sets the dimensions of the shadow to be the 22437 * same as the dimensions of the View itself and centers the shadow under 22438 * the touch point. 22439 * </p> 22440 * 22441 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 22442 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 22443 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 22444 * image. 22445 * 22446 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 22447 * shadow image that should be underneath the touch point during the drag and drop 22448 * operation. Your application must set {@link android.graphics.Point#x} to the 22449 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 22450 */ 22451 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 22452 final View view = mView.get(); 22453 if (view != null) { 22454 outShadowSize.set(view.getWidth(), view.getHeight()); 22455 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 22456 } else { 22457 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 22458 } 22459 } 22460 22461 /** 22462 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 22463 * based on the dimensions it received from the 22464 * {@link #onProvideShadowMetrics(Point, Point)} callback. 22465 * 22466 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 22467 */ 22468 public void onDrawShadow(Canvas canvas) { 22469 final View view = mView.get(); 22470 if (view != null) { 22471 view.draw(canvas); 22472 } else { 22473 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 22474 } 22475 } 22476 } 22477 22478 /** 22479 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 22480 * startDragAndDrop()} for newer platform versions. 22481 */ 22482 @Deprecated 22483 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 22484 Object myLocalState, int flags) { 22485 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 22486 } 22487 22488 /** 22489 * Starts a drag and drop operation. When your application calls this method, it passes a 22490 * {@link android.view.View.DragShadowBuilder} object to the system. The 22491 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 22492 * to get metrics for the drag shadow, and then calls the object's 22493 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 22494 * <p> 22495 * Once the system has the drag shadow, it begins the drag and drop operation by sending 22496 * drag events to all the View objects in your application that are currently visible. It does 22497 * this either by calling the View object's drag listener (an implementation of 22498 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 22499 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 22500 * Both are passed a {@link android.view.DragEvent} object that has a 22501 * {@link android.view.DragEvent#getAction()} value of 22502 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 22503 * </p> 22504 * <p> 22505 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 22506 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 22507 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 22508 * to the View the user selected for dragging. 22509 * </p> 22510 * @param data A {@link android.content.ClipData} object pointing to the data to be 22511 * transferred by the drag and drop operation. 22512 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22513 * drag shadow. 22514 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 22515 * drop operation. When dispatching drag events to views in the same activity this object 22516 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 22517 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 22518 * will return null). 22519 * <p> 22520 * myLocalState is a lightweight mechanism for the sending information from the dragged View 22521 * to the target Views. For example, it can contain flags that differentiate between a 22522 * a copy operation and a move operation. 22523 * </p> 22524 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 22525 * flags, or any combination of the following: 22526 * <ul> 22527 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 22528 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 22529 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 22530 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 22531 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 22532 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 22533 * </ul> 22534 * @return {@code true} if the method completes successfully, or 22535 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 22536 * do a drag, and so no drag operation is in progress. 22537 */ 22538 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 22539 Object myLocalState, int flags) { 22540 if (ViewDebug.DEBUG_DRAG) { 22541 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 22542 } 22543 if (mAttachInfo == null) { 22544 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 22545 return false; 22546 } 22547 22548 if (data != null) { 22549 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 22550 } 22551 22552 boolean okay = false; 22553 22554 Point shadowSize = new Point(); 22555 Point shadowTouchPoint = new Point(); 22556 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 22557 22558 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 22559 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 22560 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 22561 } 22562 22563 if (ViewDebug.DEBUG_DRAG) { 22564 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 22565 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 22566 } 22567 if (mAttachInfo.mDragSurface != null) { 22568 mAttachInfo.mDragSurface.release(); 22569 } 22570 mAttachInfo.mDragSurface = new Surface(); 22571 try { 22572 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 22573 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 22574 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 22575 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 22576 if (mAttachInfo.mDragToken != null) { 22577 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22578 try { 22579 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22580 shadowBuilder.onDrawShadow(canvas); 22581 } finally { 22582 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22583 } 22584 22585 final ViewRootImpl root = getViewRootImpl(); 22586 22587 // Cache the local state object for delivery with DragEvents 22588 root.setLocalDragState(myLocalState); 22589 22590 // repurpose 'shadowSize' for the last touch point 22591 root.getLastTouchPoint(shadowSize); 22592 22593 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 22594 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 22595 shadowTouchPoint.x, shadowTouchPoint.y, data); 22596 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 22597 } 22598 } catch (Exception e) { 22599 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 22600 mAttachInfo.mDragSurface.destroy(); 22601 mAttachInfo.mDragSurface = null; 22602 } 22603 22604 return okay; 22605 } 22606 22607 /** 22608 * Cancels an ongoing drag and drop operation. 22609 * <p> 22610 * A {@link android.view.DragEvent} object with 22611 * {@link android.view.DragEvent#getAction()} value of 22612 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 22613 * {@link android.view.DragEvent#getResult()} value of {@code false} 22614 * will be sent to every 22615 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 22616 * even if they are not currently visible. 22617 * </p> 22618 * <p> 22619 * This method can be called on any View in the same window as the View on which 22620 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 22621 * was called. 22622 * </p> 22623 */ 22624 public final void cancelDragAndDrop() { 22625 if (ViewDebug.DEBUG_DRAG) { 22626 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 22627 } 22628 if (mAttachInfo == null) { 22629 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 22630 return; 22631 } 22632 if (mAttachInfo.mDragToken != null) { 22633 try { 22634 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 22635 } catch (Exception e) { 22636 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 22637 } 22638 mAttachInfo.mDragToken = null; 22639 } else { 22640 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 22641 } 22642 } 22643 22644 /** 22645 * Updates the drag shadow for the ongoing drag and drop operation. 22646 * 22647 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22648 * new drag shadow. 22649 */ 22650 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 22651 if (ViewDebug.DEBUG_DRAG) { 22652 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 22653 } 22654 if (mAttachInfo == null) { 22655 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 22656 return; 22657 } 22658 if (mAttachInfo.mDragToken != null) { 22659 try { 22660 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22661 try { 22662 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22663 shadowBuilder.onDrawShadow(canvas); 22664 } finally { 22665 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22666 } 22667 } catch (Exception e) { 22668 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 22669 } 22670 } else { 22671 Log.e(VIEW_LOG_TAG, "No active drag"); 22672 } 22673 } 22674 22675 /** 22676 * Starts a move from {startX, startY}, the amount of the movement will be the offset 22677 * between {startX, startY} and the new cursor positon. 22678 * @param startX horizontal coordinate where the move started. 22679 * @param startY vertical coordinate where the move started. 22680 * @return whether moving was started successfully. 22681 * @hide 22682 */ 22683 public final boolean startMovingTask(float startX, float startY) { 22684 if (ViewDebug.DEBUG_POSITIONING) { 22685 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 22686 } 22687 try { 22688 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 22689 } catch (RemoteException e) { 22690 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 22691 } 22692 return false; 22693 } 22694 22695 /** 22696 * Handles drag events sent by the system following a call to 22697 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 22698 * startDragAndDrop()}. 22699 *<p> 22700 * When the system calls this method, it passes a 22701 * {@link android.view.DragEvent} object. A call to 22702 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 22703 * in DragEvent. The method uses these to determine what is happening in the drag and drop 22704 * operation. 22705 * @param event The {@link android.view.DragEvent} sent by the system. 22706 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 22707 * in DragEvent, indicating the type of drag event represented by this object. 22708 * @return {@code true} if the method was successful, otherwise {@code false}. 22709 * <p> 22710 * The method should return {@code true} in response to an action type of 22711 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 22712 * operation. 22713 * </p> 22714 * <p> 22715 * The method should also return {@code true} in response to an action type of 22716 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 22717 * {@code false} if it didn't. 22718 * </p> 22719 * <p> 22720 * For all other events, the return value is ignored. 22721 * </p> 22722 */ 22723 public boolean onDragEvent(DragEvent event) { 22724 return false; 22725 } 22726 22727 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 22728 boolean dispatchDragEnterExitInPreN(DragEvent event) { 22729 return callDragEventHandler(event); 22730 } 22731 22732 /** 22733 * Detects if this View is enabled and has a drag event listener. 22734 * If both are true, then it calls the drag event listener with the 22735 * {@link android.view.DragEvent} it received. If the drag event listener returns 22736 * {@code true}, then dispatchDragEvent() returns {@code true}. 22737 * <p> 22738 * For all other cases, the method calls the 22739 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 22740 * method and returns its result. 22741 * </p> 22742 * <p> 22743 * This ensures that a drag event is always consumed, even if the View does not have a drag 22744 * event listener. However, if the View has a listener and the listener returns true, then 22745 * onDragEvent() is not called. 22746 * </p> 22747 */ 22748 public boolean dispatchDragEvent(DragEvent event) { 22749 event.mEventHandlerWasCalled = true; 22750 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 22751 event.mAction == DragEvent.ACTION_DROP) { 22752 // About to deliver an event with coordinates to this view. Notify that now this view 22753 // has drag focus. This will send exit/enter events as needed. 22754 getViewRootImpl().setDragFocus(this, event); 22755 } 22756 return callDragEventHandler(event); 22757 } 22758 22759 final boolean callDragEventHandler(DragEvent event) { 22760 final boolean result; 22761 22762 ListenerInfo li = mListenerInfo; 22763 //noinspection SimplifiableIfStatement 22764 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 22765 && li.mOnDragListener.onDrag(this, event)) { 22766 result = true; 22767 } else { 22768 result = onDragEvent(event); 22769 } 22770 22771 switch (event.mAction) { 22772 case DragEvent.ACTION_DRAG_ENTERED: { 22773 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 22774 refreshDrawableState(); 22775 } break; 22776 case DragEvent.ACTION_DRAG_EXITED: { 22777 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 22778 refreshDrawableState(); 22779 } break; 22780 case DragEvent.ACTION_DRAG_ENDED: { 22781 mPrivateFlags2 &= ~View.DRAG_MASK; 22782 refreshDrawableState(); 22783 } break; 22784 } 22785 22786 return result; 22787 } 22788 22789 boolean canAcceptDrag() { 22790 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 22791 } 22792 22793 /** 22794 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 22795 * it is ever exposed at all. 22796 * @hide 22797 */ 22798 public void onCloseSystemDialogs(String reason) { 22799 } 22800 22801 /** 22802 * Given a Drawable whose bounds have been set to draw into this view, 22803 * update a Region being computed for 22804 * {@link #gatherTransparentRegion(android.graphics.Region)} so 22805 * that any non-transparent parts of the Drawable are removed from the 22806 * given transparent region. 22807 * 22808 * @param dr The Drawable whose transparency is to be applied to the region. 22809 * @param region A Region holding the current transparency information, 22810 * where any parts of the region that are set are considered to be 22811 * transparent. On return, this region will be modified to have the 22812 * transparency information reduced by the corresponding parts of the 22813 * Drawable that are not transparent. 22814 * {@hide} 22815 */ 22816 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 22817 if (DBG) { 22818 Log.i("View", "Getting transparent region for: " + this); 22819 } 22820 final Region r = dr.getTransparentRegion(); 22821 final Rect db = dr.getBounds(); 22822 final AttachInfo attachInfo = mAttachInfo; 22823 if (r != null && attachInfo != null) { 22824 final int w = getRight()-getLeft(); 22825 final int h = getBottom()-getTop(); 22826 if (db.left > 0) { 22827 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 22828 r.op(0, 0, db.left, h, Region.Op.UNION); 22829 } 22830 if (db.right < w) { 22831 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 22832 r.op(db.right, 0, w, h, Region.Op.UNION); 22833 } 22834 if (db.top > 0) { 22835 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 22836 r.op(0, 0, w, db.top, Region.Op.UNION); 22837 } 22838 if (db.bottom < h) { 22839 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 22840 r.op(0, db.bottom, w, h, Region.Op.UNION); 22841 } 22842 final int[] location = attachInfo.mTransparentLocation; 22843 getLocationInWindow(location); 22844 r.translate(location[0], location[1]); 22845 region.op(r, Region.Op.INTERSECT); 22846 } else { 22847 region.op(db, Region.Op.DIFFERENCE); 22848 } 22849 } 22850 22851 private void checkForLongClick(int delayOffset, float x, float y) { 22852 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) { 22853 mHasPerformedLongPress = false; 22854 22855 if (mPendingCheckForLongPress == null) { 22856 mPendingCheckForLongPress = new CheckForLongPress(); 22857 } 22858 mPendingCheckForLongPress.setAnchor(x, y); 22859 mPendingCheckForLongPress.rememberWindowAttachCount(); 22860 mPendingCheckForLongPress.rememberPressedState(); 22861 postDelayed(mPendingCheckForLongPress, 22862 ViewConfiguration.getLongPressTimeout() - delayOffset); 22863 } 22864 } 22865 22866 /** 22867 * Inflate a view from an XML resource. This convenience method wraps the {@link 22868 * LayoutInflater} class, which provides a full range of options for view inflation. 22869 * 22870 * @param context The Context object for your activity or application. 22871 * @param resource The resource ID to inflate 22872 * @param root A view group that will be the parent. Used to properly inflate the 22873 * layout_* parameters. 22874 * @see LayoutInflater 22875 */ 22876 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 22877 LayoutInflater factory = LayoutInflater.from(context); 22878 return factory.inflate(resource, root); 22879 } 22880 22881 /** 22882 * Scroll the view with standard behavior for scrolling beyond the normal 22883 * content boundaries. Views that call this method should override 22884 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 22885 * results of an over-scroll operation. 22886 * 22887 * Views can use this method to handle any touch or fling-based scrolling. 22888 * 22889 * @param deltaX Change in X in pixels 22890 * @param deltaY Change in Y in pixels 22891 * @param scrollX Current X scroll value in pixels before applying deltaX 22892 * @param scrollY Current Y scroll value in pixels before applying deltaY 22893 * @param scrollRangeX Maximum content scroll range along the X axis 22894 * @param scrollRangeY Maximum content scroll range along the Y axis 22895 * @param maxOverScrollX Number of pixels to overscroll by in either direction 22896 * along the X axis. 22897 * @param maxOverScrollY Number of pixels to overscroll by in either direction 22898 * along the Y axis. 22899 * @param isTouchEvent true if this scroll operation is the result of a touch event. 22900 * @return true if scrolling was clamped to an over-scroll boundary along either 22901 * axis, false otherwise. 22902 */ 22903 @SuppressWarnings({"UnusedParameters"}) 22904 protected boolean overScrollBy(int deltaX, int deltaY, 22905 int scrollX, int scrollY, 22906 int scrollRangeX, int scrollRangeY, 22907 int maxOverScrollX, int maxOverScrollY, 22908 boolean isTouchEvent) { 22909 final int overScrollMode = mOverScrollMode; 22910 final boolean canScrollHorizontal = 22911 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 22912 final boolean canScrollVertical = 22913 computeVerticalScrollRange() > computeVerticalScrollExtent(); 22914 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 22915 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 22916 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 22917 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 22918 22919 int newScrollX = scrollX + deltaX; 22920 if (!overScrollHorizontal) { 22921 maxOverScrollX = 0; 22922 } 22923 22924 int newScrollY = scrollY + deltaY; 22925 if (!overScrollVertical) { 22926 maxOverScrollY = 0; 22927 } 22928 22929 // Clamp values if at the limits and record 22930 final int left = -maxOverScrollX; 22931 final int right = maxOverScrollX + scrollRangeX; 22932 final int top = -maxOverScrollY; 22933 final int bottom = maxOverScrollY + scrollRangeY; 22934 22935 boolean clampedX = false; 22936 if (newScrollX > right) { 22937 newScrollX = right; 22938 clampedX = true; 22939 } else if (newScrollX < left) { 22940 newScrollX = left; 22941 clampedX = true; 22942 } 22943 22944 boolean clampedY = false; 22945 if (newScrollY > bottom) { 22946 newScrollY = bottom; 22947 clampedY = true; 22948 } else if (newScrollY < top) { 22949 newScrollY = top; 22950 clampedY = true; 22951 } 22952 22953 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 22954 22955 return clampedX || clampedY; 22956 } 22957 22958 /** 22959 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 22960 * respond to the results of an over-scroll operation. 22961 * 22962 * @param scrollX New X scroll value in pixels 22963 * @param scrollY New Y scroll value in pixels 22964 * @param clampedX True if scrollX was clamped to an over-scroll boundary 22965 * @param clampedY True if scrollY was clamped to an over-scroll boundary 22966 */ 22967 protected void onOverScrolled(int scrollX, int scrollY, 22968 boolean clampedX, boolean clampedY) { 22969 // Intentionally empty. 22970 } 22971 22972 /** 22973 * Returns the over-scroll mode for this view. The result will be 22974 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22975 * (allow over-scrolling only if the view content is larger than the container), 22976 * or {@link #OVER_SCROLL_NEVER}. 22977 * 22978 * @return This view's over-scroll mode. 22979 */ 22980 public int getOverScrollMode() { 22981 return mOverScrollMode; 22982 } 22983 22984 /** 22985 * Set the over-scroll mode for this view. Valid over-scroll modes are 22986 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22987 * (allow over-scrolling only if the view content is larger than the container), 22988 * or {@link #OVER_SCROLL_NEVER}. 22989 * 22990 * Setting the over-scroll mode of a view will have an effect only if the 22991 * view is capable of scrolling. 22992 * 22993 * @param overScrollMode The new over-scroll mode for this view. 22994 */ 22995 public void setOverScrollMode(int overScrollMode) { 22996 if (overScrollMode != OVER_SCROLL_ALWAYS && 22997 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 22998 overScrollMode != OVER_SCROLL_NEVER) { 22999 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 23000 } 23001 mOverScrollMode = overScrollMode; 23002 } 23003 23004 /** 23005 * Enable or disable nested scrolling for this view. 23006 * 23007 * <p>If this property is set to true the view will be permitted to initiate nested 23008 * scrolling operations with a compatible parent view in the current hierarchy. If this 23009 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 23010 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 23011 * the nested scroll.</p> 23012 * 23013 * @param enabled true to enable nested scrolling, false to disable 23014 * 23015 * @see #isNestedScrollingEnabled() 23016 */ 23017 public void setNestedScrollingEnabled(boolean enabled) { 23018 if (enabled) { 23019 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 23020 } else { 23021 stopNestedScroll(); 23022 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 23023 } 23024 } 23025 23026 /** 23027 * Returns true if nested scrolling is enabled for this view. 23028 * 23029 * <p>If nested scrolling is enabled and this View class implementation supports it, 23030 * this view will act as a nested scrolling child view when applicable, forwarding data 23031 * about the scroll operation in progress to a compatible and cooperating nested scrolling 23032 * parent.</p> 23033 * 23034 * @return true if nested scrolling is enabled 23035 * 23036 * @see #setNestedScrollingEnabled(boolean) 23037 */ 23038 public boolean isNestedScrollingEnabled() { 23039 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 23040 PFLAG3_NESTED_SCROLLING_ENABLED; 23041 } 23042 23043 /** 23044 * Begin a nestable scroll operation along the given axes. 23045 * 23046 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 23047 * 23048 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 23049 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 23050 * In the case of touch scrolling the nested scroll will be terminated automatically in 23051 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 23052 * In the event of programmatic scrolling the caller must explicitly call 23053 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 23054 * 23055 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 23056 * If it returns false the caller may ignore the rest of this contract until the next scroll. 23057 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 23058 * 23059 * <p>At each incremental step of the scroll the caller should invoke 23060 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 23061 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 23062 * parent at least partially consumed the scroll and the caller should adjust the amount it 23063 * scrolls by.</p> 23064 * 23065 * <p>After applying the remainder of the scroll delta the caller should invoke 23066 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 23067 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 23068 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 23069 * </p> 23070 * 23071 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 23072 * {@link #SCROLL_AXIS_VERTICAL}. 23073 * @return true if a cooperative parent was found and nested scrolling has been enabled for 23074 * the current gesture. 23075 * 23076 * @see #stopNestedScroll() 23077 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 23078 * @see #dispatchNestedScroll(int, int, int, int, int[]) 23079 */ 23080 public boolean startNestedScroll(int axes) { 23081 if (hasNestedScrollingParent()) { 23082 // Already in progress 23083 return true; 23084 } 23085 if (isNestedScrollingEnabled()) { 23086 ViewParent p = getParent(); 23087 View child = this; 23088 while (p != null) { 23089 try { 23090 if (p.onStartNestedScroll(child, this, axes)) { 23091 mNestedScrollingParent = p; 23092 p.onNestedScrollAccepted(child, this, axes); 23093 return true; 23094 } 23095 } catch (AbstractMethodError e) { 23096 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 23097 "method onStartNestedScroll", e); 23098 // Allow the search upward to continue 23099 } 23100 if (p instanceof View) { 23101 child = (View) p; 23102 } 23103 p = p.getParent(); 23104 } 23105 } 23106 return false; 23107 } 23108 23109 /** 23110 * Stop a nested scroll in progress. 23111 * 23112 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 23113 * 23114 * @see #startNestedScroll(int) 23115 */ 23116 public void stopNestedScroll() { 23117 if (mNestedScrollingParent != null) { 23118 mNestedScrollingParent.onStopNestedScroll(this); 23119 mNestedScrollingParent = null; 23120 } 23121 } 23122 23123 /** 23124 * Returns true if this view has a nested scrolling parent. 23125 * 23126 * <p>The presence of a nested scrolling parent indicates that this view has initiated 23127 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 23128 * 23129 * @return whether this view has a nested scrolling parent 23130 */ 23131 public boolean hasNestedScrollingParent() { 23132 return mNestedScrollingParent != null; 23133 } 23134 23135 /** 23136 * Dispatch one step of a nested scroll in progress. 23137 * 23138 * <p>Implementations of views that support nested scrolling should call this to report 23139 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 23140 * is not currently in progress or nested scrolling is not 23141 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 23142 * 23143 * <p>Compatible View implementations should also call 23144 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 23145 * consuming a component of the scroll event themselves.</p> 23146 * 23147 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 23148 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 23149 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 23150 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 23151 * @param offsetInWindow Optional. If not null, on return this will contain the offset 23152 * in local view coordinates of this view from before this operation 23153 * to after it completes. View implementations may use this to adjust 23154 * expected input coordinate tracking. 23155 * @return true if the event was dispatched, false if it could not be dispatched. 23156 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 23157 */ 23158 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 23159 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 23160 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23161 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 23162 int startX = 0; 23163 int startY = 0; 23164 if (offsetInWindow != null) { 23165 getLocationInWindow(offsetInWindow); 23166 startX = offsetInWindow[0]; 23167 startY = offsetInWindow[1]; 23168 } 23169 23170 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 23171 dxUnconsumed, dyUnconsumed); 23172 23173 if (offsetInWindow != null) { 23174 getLocationInWindow(offsetInWindow); 23175 offsetInWindow[0] -= startX; 23176 offsetInWindow[1] -= startY; 23177 } 23178 return true; 23179 } else if (offsetInWindow != null) { 23180 // No motion, no dispatch. Keep offsetInWindow up to date. 23181 offsetInWindow[0] = 0; 23182 offsetInWindow[1] = 0; 23183 } 23184 } 23185 return false; 23186 } 23187 23188 /** 23189 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 23190 * 23191 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 23192 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 23193 * scrolling operation to consume some or all of the scroll operation before the child view 23194 * consumes it.</p> 23195 * 23196 * @param dx Horizontal scroll distance in pixels 23197 * @param dy Vertical scroll distance in pixels 23198 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 23199 * and consumed[1] the consumed dy. 23200 * @param offsetInWindow Optional. If not null, on return this will contain the offset 23201 * in local view coordinates of this view from before this operation 23202 * to after it completes. View implementations may use this to adjust 23203 * expected input coordinate tracking. 23204 * @return true if the parent consumed some or all of the scroll delta 23205 * @see #dispatchNestedScroll(int, int, int, int, int[]) 23206 */ 23207 public boolean dispatchNestedPreScroll(int dx, int dy, 23208 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 23209 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23210 if (dx != 0 || dy != 0) { 23211 int startX = 0; 23212 int startY = 0; 23213 if (offsetInWindow != null) { 23214 getLocationInWindow(offsetInWindow); 23215 startX = offsetInWindow[0]; 23216 startY = offsetInWindow[1]; 23217 } 23218 23219 if (consumed == null) { 23220 if (mTempNestedScrollConsumed == null) { 23221 mTempNestedScrollConsumed = new int[2]; 23222 } 23223 consumed = mTempNestedScrollConsumed; 23224 } 23225 consumed[0] = 0; 23226 consumed[1] = 0; 23227 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 23228 23229 if (offsetInWindow != null) { 23230 getLocationInWindow(offsetInWindow); 23231 offsetInWindow[0] -= startX; 23232 offsetInWindow[1] -= startY; 23233 } 23234 return consumed[0] != 0 || consumed[1] != 0; 23235 } else if (offsetInWindow != null) { 23236 offsetInWindow[0] = 0; 23237 offsetInWindow[1] = 0; 23238 } 23239 } 23240 return false; 23241 } 23242 23243 /** 23244 * Dispatch a fling to a nested scrolling parent. 23245 * 23246 * <p>This method should be used to indicate that a nested scrolling child has detected 23247 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 23248 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 23249 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 23250 * along a scrollable axis.</p> 23251 * 23252 * <p>If a nested scrolling child view would normally fling but it is at the edge of 23253 * its own content, it can use this method to delegate the fling to its nested scrolling 23254 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 23255 * 23256 * @param velocityX Horizontal fling velocity in pixels per second 23257 * @param velocityY Vertical fling velocity in pixels per second 23258 * @param consumed true if the child consumed the fling, false otherwise 23259 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 23260 */ 23261 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 23262 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23263 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 23264 } 23265 return false; 23266 } 23267 23268 /** 23269 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 23270 * 23271 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 23272 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 23273 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 23274 * before the child view consumes it. If this method returns <code>true</code>, a nested 23275 * parent view consumed the fling and this view should not scroll as a result.</p> 23276 * 23277 * <p>For a better user experience, only one view in a nested scrolling chain should consume 23278 * the fling at a time. If a parent view consumed the fling this method will return false. 23279 * Custom view implementations should account for this in two ways:</p> 23280 * 23281 * <ul> 23282 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 23283 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 23284 * position regardless.</li> 23285 * <li>If a nested parent does consume the fling, this view should not scroll at all, 23286 * even to settle back to a valid idle position.</li> 23287 * </ul> 23288 * 23289 * <p>Views should also not offer fling velocities to nested parent views along an axis 23290 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 23291 * should not offer a horizontal fling velocity to its parents since scrolling along that 23292 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 23293 * 23294 * @param velocityX Horizontal fling velocity in pixels per second 23295 * @param velocityY Vertical fling velocity in pixels per second 23296 * @return true if a nested scrolling parent consumed the fling 23297 */ 23298 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 23299 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23300 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 23301 } 23302 return false; 23303 } 23304 23305 /** 23306 * Gets a scale factor that determines the distance the view should scroll 23307 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 23308 * @return The vertical scroll scale factor. 23309 * @hide 23310 */ 23311 protected float getVerticalScrollFactor() { 23312 if (mVerticalScrollFactor == 0) { 23313 TypedValue outValue = new TypedValue(); 23314 if (!mContext.getTheme().resolveAttribute( 23315 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 23316 throw new IllegalStateException( 23317 "Expected theme to define listPreferredItemHeight."); 23318 } 23319 mVerticalScrollFactor = outValue.getDimension( 23320 mContext.getResources().getDisplayMetrics()); 23321 } 23322 return mVerticalScrollFactor; 23323 } 23324 23325 /** 23326 * Gets a scale factor that determines the distance the view should scroll 23327 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 23328 * @return The horizontal scroll scale factor. 23329 * @hide 23330 */ 23331 protected float getHorizontalScrollFactor() { 23332 // TODO: Should use something else. 23333 return getVerticalScrollFactor(); 23334 } 23335 23336 /** 23337 * Return the value specifying the text direction or policy that was set with 23338 * {@link #setTextDirection(int)}. 23339 * 23340 * @return the defined text direction. It can be one of: 23341 * 23342 * {@link #TEXT_DIRECTION_INHERIT}, 23343 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23344 * {@link #TEXT_DIRECTION_ANY_RTL}, 23345 * {@link #TEXT_DIRECTION_LTR}, 23346 * {@link #TEXT_DIRECTION_RTL}, 23347 * {@link #TEXT_DIRECTION_LOCALE}, 23348 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23349 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23350 * 23351 * @attr ref android.R.styleable#View_textDirection 23352 * 23353 * @hide 23354 */ 23355 @ViewDebug.ExportedProperty(category = "text", mapping = { 23356 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23357 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23358 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23359 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23360 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23361 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23362 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23363 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23364 }) 23365 public int getRawTextDirection() { 23366 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 23367 } 23368 23369 /** 23370 * Set the text direction. 23371 * 23372 * @param textDirection the direction to set. Should be one of: 23373 * 23374 * {@link #TEXT_DIRECTION_INHERIT}, 23375 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23376 * {@link #TEXT_DIRECTION_ANY_RTL}, 23377 * {@link #TEXT_DIRECTION_LTR}, 23378 * {@link #TEXT_DIRECTION_RTL}, 23379 * {@link #TEXT_DIRECTION_LOCALE} 23380 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23381 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 23382 * 23383 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 23384 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 23385 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 23386 * 23387 * @attr ref android.R.styleable#View_textDirection 23388 */ 23389 public void setTextDirection(int textDirection) { 23390 if (getRawTextDirection() != textDirection) { 23391 // Reset the current text direction and the resolved one 23392 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 23393 resetResolvedTextDirection(); 23394 // Set the new text direction 23395 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 23396 // Do resolution 23397 resolveTextDirection(); 23398 // Notify change 23399 onRtlPropertiesChanged(getLayoutDirection()); 23400 // Refresh 23401 requestLayout(); 23402 invalidate(true); 23403 } 23404 } 23405 23406 /** 23407 * Return the resolved text direction. 23408 * 23409 * @return the resolved text direction. Returns one of: 23410 * 23411 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23412 * {@link #TEXT_DIRECTION_ANY_RTL}, 23413 * {@link #TEXT_DIRECTION_LTR}, 23414 * {@link #TEXT_DIRECTION_RTL}, 23415 * {@link #TEXT_DIRECTION_LOCALE}, 23416 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23417 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23418 * 23419 * @attr ref android.R.styleable#View_textDirection 23420 */ 23421 @ViewDebug.ExportedProperty(category = "text", mapping = { 23422 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23423 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23424 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23425 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23426 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23427 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23428 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23429 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23430 }) 23431 public int getTextDirection() { 23432 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 23433 } 23434 23435 /** 23436 * Resolve the text direction. 23437 * 23438 * @return true if resolution has been done, false otherwise. 23439 * 23440 * @hide 23441 */ 23442 public boolean resolveTextDirection() { 23443 // Reset any previous text direction resolution 23444 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23445 23446 if (hasRtlSupport()) { 23447 // Set resolved text direction flag depending on text direction flag 23448 final int textDirection = getRawTextDirection(); 23449 switch(textDirection) { 23450 case TEXT_DIRECTION_INHERIT: 23451 if (!canResolveTextDirection()) { 23452 // We cannot do the resolution if there is no parent, so use the default one 23453 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23454 // Resolution will need to happen again later 23455 return false; 23456 } 23457 23458 // Parent has not yet resolved, so we still return the default 23459 try { 23460 if (!mParent.isTextDirectionResolved()) { 23461 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23462 // Resolution will need to happen again later 23463 return false; 23464 } 23465 } catch (AbstractMethodError e) { 23466 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23467 " does not fully implement ViewParent", e); 23468 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 23469 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23470 return true; 23471 } 23472 23473 // Set current resolved direction to the same value as the parent's one 23474 int parentResolvedDirection; 23475 try { 23476 parentResolvedDirection = mParent.getTextDirection(); 23477 } catch (AbstractMethodError e) { 23478 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23479 " does not fully implement ViewParent", e); 23480 parentResolvedDirection = TEXT_DIRECTION_LTR; 23481 } 23482 switch (parentResolvedDirection) { 23483 case TEXT_DIRECTION_FIRST_STRONG: 23484 case TEXT_DIRECTION_ANY_RTL: 23485 case TEXT_DIRECTION_LTR: 23486 case TEXT_DIRECTION_RTL: 23487 case TEXT_DIRECTION_LOCALE: 23488 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23489 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23490 mPrivateFlags2 |= 23491 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23492 break; 23493 default: 23494 // Default resolved direction is "first strong" heuristic 23495 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23496 } 23497 break; 23498 case TEXT_DIRECTION_FIRST_STRONG: 23499 case TEXT_DIRECTION_ANY_RTL: 23500 case TEXT_DIRECTION_LTR: 23501 case TEXT_DIRECTION_RTL: 23502 case TEXT_DIRECTION_LOCALE: 23503 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23504 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23505 // Resolved direction is the same as text direction 23506 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23507 break; 23508 default: 23509 // Default resolved direction is "first strong" heuristic 23510 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23511 } 23512 } else { 23513 // Default resolved direction is "first strong" heuristic 23514 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23515 } 23516 23517 // Set to resolved 23518 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 23519 return true; 23520 } 23521 23522 /** 23523 * Check if text direction resolution can be done. 23524 * 23525 * @return true if text direction resolution can be done otherwise return false. 23526 */ 23527 public boolean canResolveTextDirection() { 23528 switch (getRawTextDirection()) { 23529 case TEXT_DIRECTION_INHERIT: 23530 if (mParent != null) { 23531 try { 23532 return mParent.canResolveTextDirection(); 23533 } catch (AbstractMethodError e) { 23534 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23535 " does not fully implement ViewParent", e); 23536 } 23537 } 23538 return false; 23539 23540 default: 23541 return true; 23542 } 23543 } 23544 23545 /** 23546 * Reset resolved text direction. Text direction will be resolved during a call to 23547 * {@link #onMeasure(int, int)}. 23548 * 23549 * @hide 23550 */ 23551 public void resetResolvedTextDirection() { 23552 // Reset any previous text direction resolution 23553 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23554 // Set to default value 23555 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23556 } 23557 23558 /** 23559 * @return true if text direction is inherited. 23560 * 23561 * @hide 23562 */ 23563 public boolean isTextDirectionInherited() { 23564 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 23565 } 23566 23567 /** 23568 * @return true if text direction is resolved. 23569 */ 23570 public boolean isTextDirectionResolved() { 23571 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 23572 } 23573 23574 /** 23575 * Return the value specifying the text alignment or policy that was set with 23576 * {@link #setTextAlignment(int)}. 23577 * 23578 * @return the defined text alignment. It can be one of: 23579 * 23580 * {@link #TEXT_ALIGNMENT_INHERIT}, 23581 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23582 * {@link #TEXT_ALIGNMENT_CENTER}, 23583 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23584 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23585 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23586 * {@link #TEXT_ALIGNMENT_VIEW_END} 23587 * 23588 * @attr ref android.R.styleable#View_textAlignment 23589 * 23590 * @hide 23591 */ 23592 @ViewDebug.ExportedProperty(category = "text", mapping = { 23593 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23594 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23595 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23596 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23597 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23598 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23599 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23600 }) 23601 @TextAlignment 23602 public int getRawTextAlignment() { 23603 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 23604 } 23605 23606 /** 23607 * Set the text alignment. 23608 * 23609 * @param textAlignment The text alignment to set. Should be one of 23610 * 23611 * {@link #TEXT_ALIGNMENT_INHERIT}, 23612 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23613 * {@link #TEXT_ALIGNMENT_CENTER}, 23614 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23615 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23616 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23617 * {@link #TEXT_ALIGNMENT_VIEW_END} 23618 * 23619 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 23620 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 23621 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 23622 * 23623 * @attr ref android.R.styleable#View_textAlignment 23624 */ 23625 public void setTextAlignment(@TextAlignment int textAlignment) { 23626 if (textAlignment != getRawTextAlignment()) { 23627 // Reset the current and resolved text alignment 23628 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 23629 resetResolvedTextAlignment(); 23630 // Set the new text alignment 23631 mPrivateFlags2 |= 23632 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 23633 // Do resolution 23634 resolveTextAlignment(); 23635 // Notify change 23636 onRtlPropertiesChanged(getLayoutDirection()); 23637 // Refresh 23638 requestLayout(); 23639 invalidate(true); 23640 } 23641 } 23642 23643 /** 23644 * Return the resolved text alignment. 23645 * 23646 * @return the resolved text alignment. Returns one of: 23647 * 23648 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23649 * {@link #TEXT_ALIGNMENT_CENTER}, 23650 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23651 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23652 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23653 * {@link #TEXT_ALIGNMENT_VIEW_END} 23654 * 23655 * @attr ref android.R.styleable#View_textAlignment 23656 */ 23657 @ViewDebug.ExportedProperty(category = "text", mapping = { 23658 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23659 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23660 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23661 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23662 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23663 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23664 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23665 }) 23666 @TextAlignment 23667 public int getTextAlignment() { 23668 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 23669 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 23670 } 23671 23672 /** 23673 * Resolve the text alignment. 23674 * 23675 * @return true if resolution has been done, false otherwise. 23676 * 23677 * @hide 23678 */ 23679 public boolean resolveTextAlignment() { 23680 // Reset any previous text alignment resolution 23681 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23682 23683 if (hasRtlSupport()) { 23684 // Set resolved text alignment flag depending on text alignment flag 23685 final int textAlignment = getRawTextAlignment(); 23686 switch (textAlignment) { 23687 case TEXT_ALIGNMENT_INHERIT: 23688 // Check if we can resolve the text alignment 23689 if (!canResolveTextAlignment()) { 23690 // We cannot do the resolution if there is no parent so use the default 23691 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23692 // Resolution will need to happen again later 23693 return false; 23694 } 23695 23696 // Parent has not yet resolved, so we still return the default 23697 try { 23698 if (!mParent.isTextAlignmentResolved()) { 23699 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23700 // Resolution will need to happen again later 23701 return false; 23702 } 23703 } catch (AbstractMethodError e) { 23704 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23705 " does not fully implement ViewParent", e); 23706 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 23707 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23708 return true; 23709 } 23710 23711 int parentResolvedTextAlignment; 23712 try { 23713 parentResolvedTextAlignment = mParent.getTextAlignment(); 23714 } catch (AbstractMethodError e) { 23715 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23716 " does not fully implement ViewParent", e); 23717 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 23718 } 23719 switch (parentResolvedTextAlignment) { 23720 case TEXT_ALIGNMENT_GRAVITY: 23721 case TEXT_ALIGNMENT_TEXT_START: 23722 case TEXT_ALIGNMENT_TEXT_END: 23723 case TEXT_ALIGNMENT_CENTER: 23724 case TEXT_ALIGNMENT_VIEW_START: 23725 case TEXT_ALIGNMENT_VIEW_END: 23726 // Resolved text alignment is the same as the parent resolved 23727 // text alignment 23728 mPrivateFlags2 |= 23729 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23730 break; 23731 default: 23732 // Use default resolved text alignment 23733 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23734 } 23735 break; 23736 case TEXT_ALIGNMENT_GRAVITY: 23737 case TEXT_ALIGNMENT_TEXT_START: 23738 case TEXT_ALIGNMENT_TEXT_END: 23739 case TEXT_ALIGNMENT_CENTER: 23740 case TEXT_ALIGNMENT_VIEW_START: 23741 case TEXT_ALIGNMENT_VIEW_END: 23742 // Resolved text alignment is the same as text alignment 23743 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23744 break; 23745 default: 23746 // Use default resolved text alignment 23747 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23748 } 23749 } else { 23750 // Use default resolved text alignment 23751 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23752 } 23753 23754 // Set the resolved 23755 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23756 return true; 23757 } 23758 23759 /** 23760 * Check if text alignment resolution can be done. 23761 * 23762 * @return true if text alignment resolution can be done otherwise return false. 23763 */ 23764 public boolean canResolveTextAlignment() { 23765 switch (getRawTextAlignment()) { 23766 case TEXT_DIRECTION_INHERIT: 23767 if (mParent != null) { 23768 try { 23769 return mParent.canResolveTextAlignment(); 23770 } catch (AbstractMethodError e) { 23771 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23772 " does not fully implement ViewParent", e); 23773 } 23774 } 23775 return false; 23776 23777 default: 23778 return true; 23779 } 23780 } 23781 23782 /** 23783 * Reset resolved text alignment. Text alignment will be resolved during a call to 23784 * {@link #onMeasure(int, int)}. 23785 * 23786 * @hide 23787 */ 23788 public void resetResolvedTextAlignment() { 23789 // Reset any previous text alignment resolution 23790 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23791 // Set to default 23792 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23793 } 23794 23795 /** 23796 * @return true if text alignment is inherited. 23797 * 23798 * @hide 23799 */ 23800 public boolean isTextAlignmentInherited() { 23801 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 23802 } 23803 23804 /** 23805 * @return true if text alignment is resolved. 23806 */ 23807 public boolean isTextAlignmentResolved() { 23808 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23809 } 23810 23811 /** 23812 * Generate a value suitable for use in {@link #setId(int)}. 23813 * This value will not collide with ID values generated at build time by aapt for R.id. 23814 * 23815 * @return a generated ID value 23816 */ 23817 public static int generateViewId() { 23818 for (;;) { 23819 final int result = sNextGeneratedId.get(); 23820 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 23821 int newValue = result + 1; 23822 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 23823 if (sNextGeneratedId.compareAndSet(result, newValue)) { 23824 return result; 23825 } 23826 } 23827 } 23828 23829 private static boolean isViewIdGenerated(int id) { 23830 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0; 23831 } 23832 23833 /** 23834 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 23835 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 23836 * a normal View or a ViewGroup with 23837 * {@link android.view.ViewGroup#isTransitionGroup()} true. 23838 * @hide 23839 */ 23840 public void captureTransitioningViews(List<View> transitioningViews) { 23841 if (getVisibility() == View.VISIBLE) { 23842 transitioningViews.add(this); 23843 } 23844 } 23845 23846 /** 23847 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 23848 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 23849 * @hide 23850 */ 23851 public void findNamedViews(Map<String, View> namedElements) { 23852 if (getVisibility() == VISIBLE || mGhostView != null) { 23853 String transitionName = getTransitionName(); 23854 if (transitionName != null) { 23855 namedElements.put(transitionName, this); 23856 } 23857 } 23858 } 23859 23860 /** 23861 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 23862 * The default implementation does not care the location or event types, but some subclasses 23863 * may use it (such as WebViews). 23864 * @param event The MotionEvent from a mouse 23865 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 23866 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 23867 * @see PointerIcon 23868 */ 23869 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 23870 final float x = event.getX(pointerIndex); 23871 final float y = event.getY(pointerIndex); 23872 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 23873 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 23874 } 23875 return mPointerIcon; 23876 } 23877 23878 /** 23879 * Set the pointer icon for the current view. 23880 * Passing {@code null} will restore the pointer icon to its default value. 23881 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 23882 */ 23883 public void setPointerIcon(PointerIcon pointerIcon) { 23884 mPointerIcon = pointerIcon; 23885 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 23886 return; 23887 } 23888 try { 23889 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 23890 } catch (RemoteException e) { 23891 } 23892 } 23893 23894 /** 23895 * Gets the pointer icon for the current view. 23896 */ 23897 public PointerIcon getPointerIcon() { 23898 return mPointerIcon; 23899 } 23900 23901 /** 23902 * Checks pointer capture status. 23903 * 23904 * @return true if the view has pointer capture. 23905 * @see #requestPointerCapture() 23906 * @see #hasPointerCapture() 23907 */ 23908 public boolean hasPointerCapture() { 23909 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23910 if (viewRootImpl == null) { 23911 return false; 23912 } 23913 return viewRootImpl.hasPointerCapture(); 23914 } 23915 23916 /** 23917 * Requests pointer capture mode. 23918 * <p> 23919 * When the window has pointer capture, the mouse pointer icon will disappear and will not 23920 * change its position. Further mouse will be dispatched with the source 23921 * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available 23922 * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events 23923 * (touchscreens, or stylus) will not be affected. 23924 * <p> 23925 * If the window already has pointer capture, this call does nothing. 23926 * <p> 23927 * The capture may be released through {@link #releasePointerCapture()}, or will be lost 23928 * automatically when the window loses focus. 23929 * 23930 * @see #releasePointerCapture() 23931 * @see #hasPointerCapture() 23932 */ 23933 public void requestPointerCapture() { 23934 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23935 if (viewRootImpl != null) { 23936 viewRootImpl.requestPointerCapture(true); 23937 } 23938 } 23939 23940 23941 /** 23942 * Releases the pointer capture. 23943 * <p> 23944 * If the window does not have pointer capture, this call will do nothing. 23945 * @see #requestPointerCapture() 23946 * @see #hasPointerCapture() 23947 */ 23948 public void releasePointerCapture() { 23949 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23950 if (viewRootImpl != null) { 23951 viewRootImpl.requestPointerCapture(false); 23952 } 23953 } 23954 23955 /** 23956 * Called when the window has just acquired or lost pointer capture. 23957 * 23958 * @param hasCapture True if the view now has pointerCapture, false otherwise. 23959 */ 23960 @CallSuper 23961 public void onPointerCaptureChange(boolean hasCapture) { 23962 } 23963 23964 /** 23965 * @see #onPointerCaptureChange 23966 */ 23967 public void dispatchPointerCaptureChanged(boolean hasCapture) { 23968 onPointerCaptureChange(hasCapture); 23969 } 23970 23971 /** 23972 * Implement this method to handle captured pointer events 23973 * 23974 * @param event The captured pointer event. 23975 * @return True if the event was handled, false otherwise. 23976 * @see #requestPointerCapture() 23977 */ 23978 public boolean onCapturedPointerEvent(MotionEvent event) { 23979 return false; 23980 } 23981 23982 /** 23983 * Interface definition for a callback to be invoked when a captured pointer event 23984 * is being dispatched this view. The callback will be invoked before the event is 23985 * given to the view. 23986 */ 23987 public interface OnCapturedPointerListener { 23988 /** 23989 * Called when a captured pointer event is dispatched to a view. 23990 * @param view The view this event has been dispatched to. 23991 * @param event The captured event. 23992 * @return True if the listener has consumed the event, false otherwise. 23993 */ 23994 boolean onCapturedPointer(View view, MotionEvent event); 23995 } 23996 23997 /** 23998 * Set a listener to receive callbacks when the pointer capture state of a view changes. 23999 * @param l The {@link OnCapturedPointerListener} to receive callbacks. 24000 */ 24001 public void setOnCapturedPointerListener(OnCapturedPointerListener l) { 24002 getListenerInfo().mOnCapturedPointerListener = l; 24003 } 24004 24005 // Properties 24006 // 24007 /** 24008 * A Property wrapper around the <code>alpha</code> functionality handled by the 24009 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 24010 */ 24011 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 24012 @Override 24013 public void setValue(View object, float value) { 24014 object.setAlpha(value); 24015 } 24016 24017 @Override 24018 public Float get(View object) { 24019 return object.getAlpha(); 24020 } 24021 }; 24022 24023 /** 24024 * A Property wrapper around the <code>translationX</code> functionality handled by the 24025 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 24026 */ 24027 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 24028 @Override 24029 public void setValue(View object, float value) { 24030 object.setTranslationX(value); 24031 } 24032 24033 @Override 24034 public Float get(View object) { 24035 return object.getTranslationX(); 24036 } 24037 }; 24038 24039 /** 24040 * A Property wrapper around the <code>translationY</code> functionality handled by the 24041 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 24042 */ 24043 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 24044 @Override 24045 public void setValue(View object, float value) { 24046 object.setTranslationY(value); 24047 } 24048 24049 @Override 24050 public Float get(View object) { 24051 return object.getTranslationY(); 24052 } 24053 }; 24054 24055 /** 24056 * A Property wrapper around the <code>translationZ</code> functionality handled by the 24057 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 24058 */ 24059 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 24060 @Override 24061 public void setValue(View object, float value) { 24062 object.setTranslationZ(value); 24063 } 24064 24065 @Override 24066 public Float get(View object) { 24067 return object.getTranslationZ(); 24068 } 24069 }; 24070 24071 /** 24072 * A Property wrapper around the <code>x</code> functionality handled by the 24073 * {@link View#setX(float)} and {@link View#getX()} methods. 24074 */ 24075 public static final Property<View, Float> X = new FloatProperty<View>("x") { 24076 @Override 24077 public void setValue(View object, float value) { 24078 object.setX(value); 24079 } 24080 24081 @Override 24082 public Float get(View object) { 24083 return object.getX(); 24084 } 24085 }; 24086 24087 /** 24088 * A Property wrapper around the <code>y</code> functionality handled by the 24089 * {@link View#setY(float)} and {@link View#getY()} methods. 24090 */ 24091 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 24092 @Override 24093 public void setValue(View object, float value) { 24094 object.setY(value); 24095 } 24096 24097 @Override 24098 public Float get(View object) { 24099 return object.getY(); 24100 } 24101 }; 24102 24103 /** 24104 * A Property wrapper around the <code>z</code> functionality handled by the 24105 * {@link View#setZ(float)} and {@link View#getZ()} methods. 24106 */ 24107 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 24108 @Override 24109 public void setValue(View object, float value) { 24110 object.setZ(value); 24111 } 24112 24113 @Override 24114 public Float get(View object) { 24115 return object.getZ(); 24116 } 24117 }; 24118 24119 /** 24120 * A Property wrapper around the <code>rotation</code> functionality handled by the 24121 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 24122 */ 24123 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 24124 @Override 24125 public void setValue(View object, float value) { 24126 object.setRotation(value); 24127 } 24128 24129 @Override 24130 public Float get(View object) { 24131 return object.getRotation(); 24132 } 24133 }; 24134 24135 /** 24136 * A Property wrapper around the <code>rotationX</code> functionality handled by the 24137 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 24138 */ 24139 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 24140 @Override 24141 public void setValue(View object, float value) { 24142 object.setRotationX(value); 24143 } 24144 24145 @Override 24146 public Float get(View object) { 24147 return object.getRotationX(); 24148 } 24149 }; 24150 24151 /** 24152 * A Property wrapper around the <code>rotationY</code> functionality handled by the 24153 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 24154 */ 24155 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 24156 @Override 24157 public void setValue(View object, float value) { 24158 object.setRotationY(value); 24159 } 24160 24161 @Override 24162 public Float get(View object) { 24163 return object.getRotationY(); 24164 } 24165 }; 24166 24167 /** 24168 * A Property wrapper around the <code>scaleX</code> functionality handled by the 24169 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 24170 */ 24171 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 24172 @Override 24173 public void setValue(View object, float value) { 24174 object.setScaleX(value); 24175 } 24176 24177 @Override 24178 public Float get(View object) { 24179 return object.getScaleX(); 24180 } 24181 }; 24182 24183 /** 24184 * A Property wrapper around the <code>scaleY</code> functionality handled by the 24185 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 24186 */ 24187 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 24188 @Override 24189 public void setValue(View object, float value) { 24190 object.setScaleY(value); 24191 } 24192 24193 @Override 24194 public Float get(View object) { 24195 return object.getScaleY(); 24196 } 24197 }; 24198 24199 /** 24200 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 24201 * Each MeasureSpec represents a requirement for either the width or the height. 24202 * A MeasureSpec is comprised of a size and a mode. There are three possible 24203 * modes: 24204 * <dl> 24205 * <dt>UNSPECIFIED</dt> 24206 * <dd> 24207 * The parent has not imposed any constraint on the child. It can be whatever size 24208 * it wants. 24209 * </dd> 24210 * 24211 * <dt>EXACTLY</dt> 24212 * <dd> 24213 * The parent has determined an exact size for the child. The child is going to be 24214 * given those bounds regardless of how big it wants to be. 24215 * </dd> 24216 * 24217 * <dt>AT_MOST</dt> 24218 * <dd> 24219 * The child can be as large as it wants up to the specified size. 24220 * </dd> 24221 * </dl> 24222 * 24223 * MeasureSpecs are implemented as ints to reduce object allocation. This class 24224 * is provided to pack and unpack the <size, mode> tuple into the int. 24225 */ 24226 public static class MeasureSpec { 24227 private static final int MODE_SHIFT = 30; 24228 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 24229 24230 /** @hide */ 24231 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 24232 @Retention(RetentionPolicy.SOURCE) 24233 public @interface MeasureSpecMode {} 24234 24235 /** 24236 * Measure specification mode: The parent has not imposed any constraint 24237 * on the child. It can be whatever size it wants. 24238 */ 24239 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 24240 24241 /** 24242 * Measure specification mode: The parent has determined an exact size 24243 * for the child. The child is going to be given those bounds regardless 24244 * of how big it wants to be. 24245 */ 24246 public static final int EXACTLY = 1 << MODE_SHIFT; 24247 24248 /** 24249 * Measure specification mode: The child can be as large as it wants up 24250 * to the specified size. 24251 */ 24252 public static final int AT_MOST = 2 << MODE_SHIFT; 24253 24254 /** 24255 * Creates a measure specification based on the supplied size and mode. 24256 * 24257 * The mode must always be one of the following: 24258 * <ul> 24259 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 24260 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 24261 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 24262 * </ul> 24263 * 24264 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 24265 * implementation was such that the order of arguments did not matter 24266 * and overflow in either value could impact the resulting MeasureSpec. 24267 * {@link android.widget.RelativeLayout} was affected by this bug. 24268 * Apps targeting API levels greater than 17 will get the fixed, more strict 24269 * behavior.</p> 24270 * 24271 * @param size the size of the measure specification 24272 * @param mode the mode of the measure specification 24273 * @return the measure specification based on size and mode 24274 */ 24275 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 24276 @MeasureSpecMode int mode) { 24277 if (sUseBrokenMakeMeasureSpec) { 24278 return size + mode; 24279 } else { 24280 return (size & ~MODE_MASK) | (mode & MODE_MASK); 24281 } 24282 } 24283 24284 /** 24285 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 24286 * will automatically get a size of 0. Older apps expect this. 24287 * 24288 * @hide internal use only for compatibility with system widgets and older apps 24289 */ 24290 public static int makeSafeMeasureSpec(int size, int mode) { 24291 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 24292 return 0; 24293 } 24294 return makeMeasureSpec(size, mode); 24295 } 24296 24297 /** 24298 * Extracts the mode from the supplied measure specification. 24299 * 24300 * @param measureSpec the measure specification to extract the mode from 24301 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 24302 * {@link android.view.View.MeasureSpec#AT_MOST} or 24303 * {@link android.view.View.MeasureSpec#EXACTLY} 24304 */ 24305 @MeasureSpecMode 24306 public static int getMode(int measureSpec) { 24307 //noinspection ResourceType 24308 return (measureSpec & MODE_MASK); 24309 } 24310 24311 /** 24312 * Extracts the size from the supplied measure specification. 24313 * 24314 * @param measureSpec the measure specification to extract the size from 24315 * @return the size in pixels defined in the supplied measure specification 24316 */ 24317 public static int getSize(int measureSpec) { 24318 return (measureSpec & ~MODE_MASK); 24319 } 24320 24321 static int adjust(int measureSpec, int delta) { 24322 final int mode = getMode(measureSpec); 24323 int size = getSize(measureSpec); 24324 if (mode == UNSPECIFIED) { 24325 // No need to adjust size for UNSPECIFIED mode. 24326 return makeMeasureSpec(size, UNSPECIFIED); 24327 } 24328 size += delta; 24329 if (size < 0) { 24330 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 24331 ") spec: " + toString(measureSpec) + " delta: " + delta); 24332 size = 0; 24333 } 24334 return makeMeasureSpec(size, mode); 24335 } 24336 24337 /** 24338 * Returns a String representation of the specified measure 24339 * specification. 24340 * 24341 * @param measureSpec the measure specification to convert to a String 24342 * @return a String with the following format: "MeasureSpec: MODE SIZE" 24343 */ 24344 public static String toString(int measureSpec) { 24345 int mode = getMode(measureSpec); 24346 int size = getSize(measureSpec); 24347 24348 StringBuilder sb = new StringBuilder("MeasureSpec: "); 24349 24350 if (mode == UNSPECIFIED) 24351 sb.append("UNSPECIFIED "); 24352 else if (mode == EXACTLY) 24353 sb.append("EXACTLY "); 24354 else if (mode == AT_MOST) 24355 sb.append("AT_MOST "); 24356 else 24357 sb.append(mode).append(" "); 24358 24359 sb.append(size); 24360 return sb.toString(); 24361 } 24362 } 24363 24364 private final class CheckForLongPress implements Runnable { 24365 private int mOriginalWindowAttachCount; 24366 private float mX; 24367 private float mY; 24368 private boolean mOriginalPressedState; 24369 24370 @Override 24371 public void run() { 24372 if ((mOriginalPressedState == isPressed()) && (mParent != null) 24373 && mOriginalWindowAttachCount == mWindowAttachCount) { 24374 if (performLongClick(mX, mY)) { 24375 mHasPerformedLongPress = true; 24376 } 24377 } 24378 } 24379 24380 public void setAnchor(float x, float y) { 24381 mX = x; 24382 mY = y; 24383 } 24384 24385 public void rememberWindowAttachCount() { 24386 mOriginalWindowAttachCount = mWindowAttachCount; 24387 } 24388 24389 public void rememberPressedState() { 24390 mOriginalPressedState = isPressed(); 24391 } 24392 } 24393 24394 private final class CheckForTap implements Runnable { 24395 public float x; 24396 public float y; 24397 24398 @Override 24399 public void run() { 24400 mPrivateFlags &= ~PFLAG_PREPRESSED; 24401 setPressed(true, x, y); 24402 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 24403 } 24404 } 24405 24406 private final class PerformClick implements Runnable { 24407 @Override 24408 public void run() { 24409 performClick(); 24410 } 24411 } 24412 24413 /** 24414 * This method returns a ViewPropertyAnimator object, which can be used to animate 24415 * specific properties on this View. 24416 * 24417 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 24418 */ 24419 public ViewPropertyAnimator animate() { 24420 if (mAnimator == null) { 24421 mAnimator = new ViewPropertyAnimator(this); 24422 } 24423 return mAnimator; 24424 } 24425 24426 /** 24427 * Sets the name of the View to be used to identify Views in Transitions. 24428 * Names should be unique in the View hierarchy. 24429 * 24430 * @param transitionName The name of the View to uniquely identify it for Transitions. 24431 */ 24432 public final void setTransitionName(String transitionName) { 24433 mTransitionName = transitionName; 24434 } 24435 24436 /** 24437 * Returns the name of the View to be used to identify Views in Transitions. 24438 * Names should be unique in the View hierarchy. 24439 * 24440 * <p>This returns null if the View has not been given a name.</p> 24441 * 24442 * @return The name used of the View to be used to identify Views in Transitions or null 24443 * if no name has been given. 24444 */ 24445 @ViewDebug.ExportedProperty 24446 public String getTransitionName() { 24447 return mTransitionName; 24448 } 24449 24450 /** 24451 * @hide 24452 */ 24453 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 24454 // Do nothing. 24455 } 24456 24457 /** 24458 * Interface definition for a callback to be invoked when a hardware key event is 24459 * dispatched to this view. The callback will be invoked before the key event is 24460 * given to the view. This is only useful for hardware keyboards; a software input 24461 * method has no obligation to trigger this listener. 24462 */ 24463 public interface OnKeyListener { 24464 /** 24465 * Called when a hardware key is dispatched to a view. This allows listeners to 24466 * get a chance to respond before the target view. 24467 * <p>Key presses in software keyboards will generally NOT trigger this method, 24468 * although some may elect to do so in some situations. Do not assume a 24469 * software input method has to be key-based; even if it is, it may use key presses 24470 * in a different way than you expect, so there is no way to reliably catch soft 24471 * input key presses. 24472 * 24473 * @param v The view the key has been dispatched to. 24474 * @param keyCode The code for the physical key that was pressed 24475 * @param event The KeyEvent object containing full information about 24476 * the event. 24477 * @return True if the listener has consumed the event, false otherwise. 24478 */ 24479 boolean onKey(View v, int keyCode, KeyEvent event); 24480 } 24481 24482 /** 24483 * Interface definition for a callback to be invoked when a touch event is 24484 * dispatched to this view. The callback will be invoked before the touch 24485 * event is given to the view. 24486 */ 24487 public interface OnTouchListener { 24488 /** 24489 * Called when a touch event is dispatched to a view. This allows listeners to 24490 * get a chance to respond before the target view. 24491 * 24492 * @param v The view the touch event has been dispatched to. 24493 * @param event The MotionEvent object containing full information about 24494 * the event. 24495 * @return True if the listener has consumed the event, false otherwise. 24496 */ 24497 boolean onTouch(View v, MotionEvent event); 24498 } 24499 24500 /** 24501 * Interface definition for a callback to be invoked when a hover event is 24502 * dispatched to this view. The callback will be invoked before the hover 24503 * event is given to the view. 24504 */ 24505 public interface OnHoverListener { 24506 /** 24507 * Called when a hover event is dispatched to a view. This allows listeners to 24508 * get a chance to respond before the target view. 24509 * 24510 * @param v The view the hover event has been dispatched to. 24511 * @param event The MotionEvent object containing full information about 24512 * the event. 24513 * @return True if the listener has consumed the event, false otherwise. 24514 */ 24515 boolean onHover(View v, MotionEvent event); 24516 } 24517 24518 /** 24519 * Interface definition for a callback to be invoked when a generic motion event is 24520 * dispatched to this view. The callback will be invoked before the generic motion 24521 * event is given to the view. 24522 */ 24523 public interface OnGenericMotionListener { 24524 /** 24525 * Called when a generic motion event is dispatched to a view. This allows listeners to 24526 * get a chance to respond before the target view. 24527 * 24528 * @param v The view the generic motion event has been dispatched to. 24529 * @param event The MotionEvent object containing full information about 24530 * the event. 24531 * @return True if the listener has consumed the event, false otherwise. 24532 */ 24533 boolean onGenericMotion(View v, MotionEvent event); 24534 } 24535 24536 /** 24537 * Interface definition for a callback to be invoked when a view has been clicked and held. 24538 */ 24539 public interface OnLongClickListener { 24540 /** 24541 * Called when a view has been clicked and held. 24542 * 24543 * @param v The view that was clicked and held. 24544 * 24545 * @return true if the callback consumed the long click, false otherwise. 24546 */ 24547 boolean onLongClick(View v); 24548 } 24549 24550 /** 24551 * Interface definition for a callback to be invoked when a drag is being dispatched 24552 * to this view. The callback will be invoked before the hosting view's own 24553 * onDrag(event) method. If the listener wants to fall back to the hosting view's 24554 * onDrag(event) behavior, it should return 'false' from this callback. 24555 * 24556 * <div class="special reference"> 24557 * <h3>Developer Guides</h3> 24558 * <p>For a guide to implementing drag and drop features, read the 24559 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 24560 * </div> 24561 */ 24562 public interface OnDragListener { 24563 /** 24564 * Called when a drag event is dispatched to a view. This allows listeners 24565 * to get a chance to override base View behavior. 24566 * 24567 * @param v The View that received the drag event. 24568 * @param event The {@link android.view.DragEvent} object for the drag event. 24569 * @return {@code true} if the drag event was handled successfully, or {@code false} 24570 * if the drag event was not handled. Note that {@code false} will trigger the View 24571 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 24572 */ 24573 boolean onDrag(View v, DragEvent event); 24574 } 24575 24576 /** 24577 * Interface definition for a callback to be invoked when the focus state of 24578 * a view changed. 24579 */ 24580 public interface OnFocusChangeListener { 24581 /** 24582 * Called when the focus state of a view has changed. 24583 * 24584 * @param v The view whose state has changed. 24585 * @param hasFocus The new focus state of v. 24586 */ 24587 void onFocusChange(View v, boolean hasFocus); 24588 } 24589 24590 /** 24591 * Interface definition for a callback to be invoked when a view is clicked. 24592 */ 24593 public interface OnClickListener { 24594 /** 24595 * Called when a view has been clicked. 24596 * 24597 * @param v The view that was clicked. 24598 */ 24599 void onClick(View v); 24600 } 24601 24602 /** 24603 * Interface definition for a callback to be invoked when a view is context clicked. 24604 */ 24605 public interface OnContextClickListener { 24606 /** 24607 * Called when a view is context clicked. 24608 * 24609 * @param v The view that has been context clicked. 24610 * @return true if the callback consumed the context click, false otherwise. 24611 */ 24612 boolean onContextClick(View v); 24613 } 24614 24615 /** 24616 * Interface definition for a callback to be invoked when the context menu 24617 * for this view is being built. 24618 */ 24619 public interface OnCreateContextMenuListener { 24620 /** 24621 * Called when the context menu for this view is being built. It is not 24622 * safe to hold onto the menu after this method returns. 24623 * 24624 * @param menu The context menu that is being built 24625 * @param v The view for which the context menu is being built 24626 * @param menuInfo Extra information about the item for which the 24627 * context menu should be shown. This information will vary 24628 * depending on the class of v. 24629 */ 24630 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 24631 } 24632 24633 /** 24634 * Interface definition for a callback to be invoked when the status bar changes 24635 * visibility. This reports <strong>global</strong> changes to the system UI 24636 * state, not what the application is requesting. 24637 * 24638 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 24639 */ 24640 public interface OnSystemUiVisibilityChangeListener { 24641 /** 24642 * Called when the status bar changes visibility because of a call to 24643 * {@link View#setSystemUiVisibility(int)}. 24644 * 24645 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 24646 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 24647 * This tells you the <strong>global</strong> state of these UI visibility 24648 * flags, not what your app is currently applying. 24649 */ 24650 public void onSystemUiVisibilityChange(int visibility); 24651 } 24652 24653 /** 24654 * Interface definition for a callback to be invoked when this view is attached 24655 * or detached from its window. 24656 */ 24657 public interface OnAttachStateChangeListener { 24658 /** 24659 * Called when the view is attached to a window. 24660 * @param v The view that was attached 24661 */ 24662 public void onViewAttachedToWindow(View v); 24663 /** 24664 * Called when the view is detached from a window. 24665 * @param v The view that was detached 24666 */ 24667 public void onViewDetachedFromWindow(View v); 24668 } 24669 24670 /** 24671 * Listener for applying window insets on a view in a custom way. 24672 * 24673 * <p>Apps may choose to implement this interface if they want to apply custom policy 24674 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 24675 * is set, its 24676 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 24677 * method will be called instead of the View's own 24678 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 24679 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 24680 * the View's normal behavior as part of its own.</p> 24681 */ 24682 public interface OnApplyWindowInsetsListener { 24683 /** 24684 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 24685 * on a View, this listener method will be called instead of the view's own 24686 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 24687 * 24688 * @param v The view applying window insets 24689 * @param insets The insets to apply 24690 * @return The insets supplied, minus any insets that were consumed 24691 */ 24692 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 24693 } 24694 24695 private final class UnsetPressedState implements Runnable { 24696 @Override 24697 public void run() { 24698 setPressed(false); 24699 } 24700 } 24701 24702 /** 24703 * When a view becomes invisible checks if autofill considers the view invisible too. This 24704 * happens after the regular removal operation to make sure the operation is finished by the 24705 * time this is called. 24706 */ 24707 private static class VisibilityChangeForAutofillHandler extends Handler { 24708 private final AutofillManager mAfm; 24709 private final View mView; 24710 24711 private VisibilityChangeForAutofillHandler(@NonNull AutofillManager afm, 24712 @NonNull View view) { 24713 mAfm = afm; 24714 mView = view; 24715 } 24716 24717 @Override 24718 public void handleMessage(Message msg) { 24719 mAfm.notifyViewVisibilityChange(mView, mView.isShown()); 24720 } 24721 } 24722 24723 /** 24724 * Base class for derived classes that want to save and restore their own 24725 * state in {@link android.view.View#onSaveInstanceState()}. 24726 */ 24727 public static class BaseSavedState extends AbsSavedState { 24728 static final int START_ACTIVITY_REQUESTED_WHO_SAVED = 0b1; 24729 static final int IS_AUTOFILLED = 0b10; 24730 static final int ACCESSIBILITY_ID = 0b100; 24731 24732 // Flags that describe what data in this state is valid 24733 int mSavedData; 24734 String mStartActivityRequestWhoSaved; 24735 boolean mIsAutofilled; 24736 int mAccessibilityViewId; 24737 24738 /** 24739 * Constructor used when reading from a parcel. Reads the state of the superclass. 24740 * 24741 * @param source parcel to read from 24742 */ 24743 public BaseSavedState(Parcel source) { 24744 this(source, null); 24745 } 24746 24747 /** 24748 * Constructor used when reading from a parcel using a given class loader. 24749 * Reads the state of the superclass. 24750 * 24751 * @param source parcel to read from 24752 * @param loader ClassLoader to use for reading 24753 */ 24754 public BaseSavedState(Parcel source, ClassLoader loader) { 24755 super(source, loader); 24756 mSavedData = source.readInt(); 24757 mStartActivityRequestWhoSaved = source.readString(); 24758 mIsAutofilled = source.readBoolean(); 24759 mAccessibilityViewId = source.readInt(); 24760 } 24761 24762 /** 24763 * Constructor called by derived classes when creating their SavedState objects 24764 * 24765 * @param superState The state of the superclass of this view 24766 */ 24767 public BaseSavedState(Parcelable superState) { 24768 super(superState); 24769 } 24770 24771 @Override 24772 public void writeToParcel(Parcel out, int flags) { 24773 super.writeToParcel(out, flags); 24774 24775 out.writeInt(mSavedData); 24776 out.writeString(mStartActivityRequestWhoSaved); 24777 out.writeBoolean(mIsAutofilled); 24778 out.writeInt(mAccessibilityViewId); 24779 } 24780 24781 public static final Parcelable.Creator<BaseSavedState> CREATOR 24782 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 24783 @Override 24784 public BaseSavedState createFromParcel(Parcel in) { 24785 return new BaseSavedState(in); 24786 } 24787 24788 @Override 24789 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 24790 return new BaseSavedState(in, loader); 24791 } 24792 24793 @Override 24794 public BaseSavedState[] newArray(int size) { 24795 return new BaseSavedState[size]; 24796 } 24797 }; 24798 } 24799 24800 /** 24801 * A set of information given to a view when it is attached to its parent 24802 * window. 24803 */ 24804 final static class AttachInfo { 24805 interface Callbacks { 24806 void playSoundEffect(int effectId); 24807 boolean performHapticFeedback(int effectId, boolean always); 24808 } 24809 24810 /** 24811 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 24812 * to a Handler. This class contains the target (View) to invalidate and 24813 * the coordinates of the dirty rectangle. 24814 * 24815 * For performance purposes, this class also implements a pool of up to 24816 * POOL_LIMIT objects that get reused. This reduces memory allocations 24817 * whenever possible. 24818 */ 24819 static class InvalidateInfo { 24820 private static final int POOL_LIMIT = 10; 24821 24822 private static final SynchronizedPool<InvalidateInfo> sPool = 24823 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 24824 24825 View target; 24826 24827 int left; 24828 int top; 24829 int right; 24830 int bottom; 24831 24832 public static InvalidateInfo obtain() { 24833 InvalidateInfo instance = sPool.acquire(); 24834 return (instance != null) ? instance : new InvalidateInfo(); 24835 } 24836 24837 public void recycle() { 24838 target = null; 24839 sPool.release(this); 24840 } 24841 } 24842 24843 final IWindowSession mSession; 24844 24845 final IWindow mWindow; 24846 24847 final IBinder mWindowToken; 24848 24849 Display mDisplay; 24850 24851 final Callbacks mRootCallbacks; 24852 24853 IWindowId mIWindowId; 24854 WindowId mWindowId; 24855 24856 /** 24857 * The top view of the hierarchy. 24858 */ 24859 View mRootView; 24860 24861 IBinder mPanelParentWindowToken; 24862 24863 boolean mHardwareAccelerated; 24864 boolean mHardwareAccelerationRequested; 24865 ThreadedRenderer mThreadedRenderer; 24866 List<RenderNode> mPendingAnimatingRenderNodes; 24867 24868 /** 24869 * The state of the display to which the window is attached, as reported 24870 * by {@link Display#getState()}. Note that the display state constants 24871 * declared by {@link Display} do not exactly line up with the screen state 24872 * constants declared by {@link View} (there are more display states than 24873 * screen states). 24874 */ 24875 int mDisplayState = Display.STATE_UNKNOWN; 24876 24877 /** 24878 * Scale factor used by the compatibility mode 24879 */ 24880 float mApplicationScale; 24881 24882 /** 24883 * Indicates whether the application is in compatibility mode 24884 */ 24885 boolean mScalingRequired; 24886 24887 /** 24888 * Left position of this view's window 24889 */ 24890 int mWindowLeft; 24891 24892 /** 24893 * Top position of this view's window 24894 */ 24895 int mWindowTop; 24896 24897 /** 24898 * Indicates whether views need to use 32-bit drawing caches 24899 */ 24900 boolean mUse32BitDrawingCache; 24901 24902 /** 24903 * For windows that are full-screen but using insets to layout inside 24904 * of the screen areas, these are the current insets to appear inside 24905 * the overscan area of the display. 24906 */ 24907 final Rect mOverscanInsets = new Rect(); 24908 24909 /** 24910 * For windows that are full-screen but using insets to layout inside 24911 * of the screen decorations, these are the current insets for the 24912 * content of the window. 24913 */ 24914 final Rect mContentInsets = new Rect(); 24915 24916 /** 24917 * For windows that are full-screen but using insets to layout inside 24918 * of the screen decorations, these are the current insets for the 24919 * actual visible parts of the window. 24920 */ 24921 final Rect mVisibleInsets = new Rect(); 24922 24923 /** 24924 * For windows that are full-screen but using insets to layout inside 24925 * of the screen decorations, these are the current insets for the 24926 * stable system windows. 24927 */ 24928 final Rect mStableInsets = new Rect(); 24929 24930 /** 24931 * For windows that include areas that are not covered by real surface these are the outsets 24932 * for real surface. 24933 */ 24934 final Rect mOutsets = new Rect(); 24935 24936 /** 24937 * In multi-window we force show the navigation bar. Because we don't want that the surface 24938 * size changes in this mode, we instead have a flag whether the navigation bar size should 24939 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 24940 */ 24941 boolean mAlwaysConsumeNavBar; 24942 24943 /** 24944 * The internal insets given by this window. This value is 24945 * supplied by the client (through 24946 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 24947 * be given to the window manager when changed to be used in laying 24948 * out windows behind it. 24949 */ 24950 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 24951 = new ViewTreeObserver.InternalInsetsInfo(); 24952 24953 /** 24954 * Set to true when mGivenInternalInsets is non-empty. 24955 */ 24956 boolean mHasNonEmptyGivenInternalInsets; 24957 24958 /** 24959 * All views in the window's hierarchy that serve as scroll containers, 24960 * used to determine if the window can be resized or must be panned 24961 * to adjust for a soft input area. 24962 */ 24963 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 24964 24965 final KeyEvent.DispatcherState mKeyDispatchState 24966 = new KeyEvent.DispatcherState(); 24967 24968 /** 24969 * Indicates whether the view's window currently has the focus. 24970 */ 24971 boolean mHasWindowFocus; 24972 24973 /** 24974 * The current visibility of the window. 24975 */ 24976 int mWindowVisibility; 24977 24978 /** 24979 * Indicates the time at which drawing started to occur. 24980 */ 24981 long mDrawingTime; 24982 24983 /** 24984 * Indicates whether or not ignoring the DIRTY_MASK flags. 24985 */ 24986 boolean mIgnoreDirtyState; 24987 24988 /** 24989 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 24990 * to avoid clearing that flag prematurely. 24991 */ 24992 boolean mSetIgnoreDirtyState = false; 24993 24994 /** 24995 * Indicates whether the view's window is currently in touch mode. 24996 */ 24997 boolean mInTouchMode; 24998 24999 /** 25000 * Indicates whether the view has requested unbuffered input dispatching for the current 25001 * event stream. 25002 */ 25003 boolean mUnbufferedDispatchRequested; 25004 25005 /** 25006 * Indicates that ViewAncestor should trigger a global layout change 25007 * the next time it performs a traversal 25008 */ 25009 boolean mRecomputeGlobalAttributes; 25010 25011 /** 25012 * Always report new attributes at next traversal. 25013 */ 25014 boolean mForceReportNewAttributes; 25015 25016 /** 25017 * Set during a traveral if any views want to keep the screen on. 25018 */ 25019 boolean mKeepScreenOn; 25020 25021 /** 25022 * Set during a traveral if the light center needs to be updated. 25023 */ 25024 boolean mNeedsUpdateLightCenter; 25025 25026 /** 25027 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 25028 */ 25029 int mSystemUiVisibility; 25030 25031 /** 25032 * Hack to force certain system UI visibility flags to be cleared. 25033 */ 25034 int mDisabledSystemUiVisibility; 25035 25036 /** 25037 * Last global system UI visibility reported by the window manager. 25038 */ 25039 int mGlobalSystemUiVisibility = -1; 25040 25041 /** 25042 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 25043 * attached. 25044 */ 25045 boolean mHasSystemUiListeners; 25046 25047 /** 25048 * Set if the window has requested to extend into the overscan region 25049 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 25050 */ 25051 boolean mOverscanRequested; 25052 25053 /** 25054 * Set if the visibility of any views has changed. 25055 */ 25056 boolean mViewVisibilityChanged; 25057 25058 /** 25059 * Set to true if a view has been scrolled. 25060 */ 25061 boolean mViewScrollChanged; 25062 25063 /** 25064 * Set to true if high contrast mode enabled 25065 */ 25066 boolean mHighContrastText; 25067 25068 /** 25069 * Set to true if a pointer event is currently being handled. 25070 */ 25071 boolean mHandlingPointerEvent; 25072 25073 /** 25074 * Global to the view hierarchy used as a temporary for dealing with 25075 * x/y points in the transparent region computations. 25076 */ 25077 final int[] mTransparentLocation = new int[2]; 25078 25079 /** 25080 * Global to the view hierarchy used as a temporary for dealing with 25081 * x/y points in the ViewGroup.invalidateChild implementation. 25082 */ 25083 final int[] mInvalidateChildLocation = new int[2]; 25084 25085 /** 25086 * Global to the view hierarchy used as a temporary for dealing with 25087 * computing absolute on-screen location. 25088 */ 25089 final int[] mTmpLocation = new int[2]; 25090 25091 /** 25092 * Global to the view hierarchy used as a temporary for dealing with 25093 * x/y location when view is transformed. 25094 */ 25095 final float[] mTmpTransformLocation = new float[2]; 25096 25097 /** 25098 * The view tree observer used to dispatch global events like 25099 * layout, pre-draw, touch mode change, etc. 25100 */ 25101 final ViewTreeObserver mTreeObserver; 25102 25103 /** 25104 * A Canvas used by the view hierarchy to perform bitmap caching. 25105 */ 25106 Canvas mCanvas; 25107 25108 /** 25109 * The view root impl. 25110 */ 25111 final ViewRootImpl mViewRootImpl; 25112 25113 /** 25114 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 25115 * handler can be used to pump events in the UI events queue. 25116 */ 25117 final Handler mHandler; 25118 25119 /** 25120 * Temporary for use in computing invalidate rectangles while 25121 * calling up the hierarchy. 25122 */ 25123 final Rect mTmpInvalRect = new Rect(); 25124 25125 /** 25126 * Temporary for use in computing hit areas with transformed views 25127 */ 25128 final RectF mTmpTransformRect = new RectF(); 25129 25130 /** 25131 * Temporary for use in computing hit areas with transformed views 25132 */ 25133 final RectF mTmpTransformRect1 = new RectF(); 25134 25135 /** 25136 * Temporary list of rectanges. 25137 */ 25138 final List<RectF> mTmpRectList = new ArrayList<>(); 25139 25140 /** 25141 * Temporary for use in transforming invalidation rect 25142 */ 25143 final Matrix mTmpMatrix = new Matrix(); 25144 25145 /** 25146 * Temporary for use in transforming invalidation rect 25147 */ 25148 final Transformation mTmpTransformation = new Transformation(); 25149 25150 /** 25151 * Temporary for use in querying outlines from OutlineProviders 25152 */ 25153 final Outline mTmpOutline = new Outline(); 25154 25155 /** 25156 * Temporary list for use in collecting focusable descendents of a view. 25157 */ 25158 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 25159 25160 /** 25161 * The id of the window for accessibility purposes. 25162 */ 25163 int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 25164 25165 /** 25166 * Flags related to accessibility processing. 25167 * 25168 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 25169 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 25170 */ 25171 int mAccessibilityFetchFlags; 25172 25173 /** 25174 * The drawable for highlighting accessibility focus. 25175 */ 25176 Drawable mAccessibilityFocusDrawable; 25177 25178 /** 25179 * The drawable for highlighting autofilled views. 25180 * 25181 * @see #isAutofilled() 25182 */ 25183 Drawable mAutofilledDrawable; 25184 25185 /** 25186 * Show where the margins, bounds and layout bounds are for each view. 25187 */ 25188 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 25189 25190 /** 25191 * Point used to compute visible regions. 25192 */ 25193 final Point mPoint = new Point(); 25194 25195 /** 25196 * Used to track which View originated a requestLayout() call, used when 25197 * requestLayout() is called during layout. 25198 */ 25199 View mViewRequestingLayout; 25200 25201 /** 25202 * Used to track views that need (at least) a partial relayout at their current size 25203 * during the next traversal. 25204 */ 25205 List<View> mPartialLayoutViews = new ArrayList<>(); 25206 25207 /** 25208 * Swapped with mPartialLayoutViews during layout to avoid concurrent 25209 * modification. Lazily assigned during ViewRootImpl layout. 25210 */ 25211 List<View> mEmptyPartialLayoutViews; 25212 25213 /** 25214 * Used to track the identity of the current drag operation. 25215 */ 25216 IBinder mDragToken; 25217 25218 /** 25219 * The drag shadow surface for the current drag operation. 25220 */ 25221 public Surface mDragSurface; 25222 25223 25224 /** 25225 * The view that currently has a tooltip displayed. 25226 */ 25227 View mTooltipHost; 25228 25229 /** 25230 * Creates a new set of attachment information with the specified 25231 * events handler and thread. 25232 * 25233 * @param handler the events handler the view must use 25234 */ 25235 AttachInfo(IWindowSession session, IWindow window, Display display, 25236 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 25237 Context context) { 25238 mSession = session; 25239 mWindow = window; 25240 mWindowToken = window.asBinder(); 25241 mDisplay = display; 25242 mViewRootImpl = viewRootImpl; 25243 mHandler = handler; 25244 mRootCallbacks = effectPlayer; 25245 mTreeObserver = new ViewTreeObserver(context); 25246 } 25247 } 25248 25249 /** 25250 * <p>ScrollabilityCache holds various fields used by a View when scrolling 25251 * is supported. This avoids keeping too many unused fields in most 25252 * instances of View.</p> 25253 */ 25254 private static class ScrollabilityCache implements Runnable { 25255 25256 /** 25257 * Scrollbars are not visible 25258 */ 25259 public static final int OFF = 0; 25260 25261 /** 25262 * Scrollbars are visible 25263 */ 25264 public static final int ON = 1; 25265 25266 /** 25267 * Scrollbars are fading away 25268 */ 25269 public static final int FADING = 2; 25270 25271 public boolean fadeScrollBars; 25272 25273 public int fadingEdgeLength; 25274 public int scrollBarDefaultDelayBeforeFade; 25275 public int scrollBarFadeDuration; 25276 25277 public int scrollBarSize; 25278 public int scrollBarMinTouchTarget; 25279 public ScrollBarDrawable scrollBar; 25280 public float[] interpolatorValues; 25281 public View host; 25282 25283 public final Paint paint; 25284 public final Matrix matrix; 25285 public Shader shader; 25286 25287 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 25288 25289 private static final float[] OPAQUE = { 255 }; 25290 private static final float[] TRANSPARENT = { 0.0f }; 25291 25292 /** 25293 * When fading should start. This time moves into the future every time 25294 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 25295 */ 25296 public long fadeStartTime; 25297 25298 25299 /** 25300 * The current state of the scrollbars: ON, OFF, or FADING 25301 */ 25302 public int state = OFF; 25303 25304 private int mLastColor; 25305 25306 public final Rect mScrollBarBounds = new Rect(); 25307 public final Rect mScrollBarTouchBounds = new Rect(); 25308 25309 public static final int NOT_DRAGGING = 0; 25310 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 25311 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 25312 public int mScrollBarDraggingState = NOT_DRAGGING; 25313 25314 public float mScrollBarDraggingPos = 0; 25315 25316 public ScrollabilityCache(ViewConfiguration configuration, View host) { 25317 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 25318 scrollBarSize = configuration.getScaledScrollBarSize(); 25319 scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget(); 25320 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 25321 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 25322 25323 paint = new Paint(); 25324 matrix = new Matrix(); 25325 // use use a height of 1, and then wack the matrix each time we 25326 // actually use it. 25327 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25328 paint.setShader(shader); 25329 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25330 25331 this.host = host; 25332 } 25333 25334 public void setFadeColor(int color) { 25335 if (color != mLastColor) { 25336 mLastColor = color; 25337 25338 if (color != 0) { 25339 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 25340 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 25341 paint.setShader(shader); 25342 // Restore the default transfer mode (src_over) 25343 paint.setXfermode(null); 25344 } else { 25345 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25346 paint.setShader(shader); 25347 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25348 } 25349 } 25350 } 25351 25352 public void run() { 25353 long now = AnimationUtils.currentAnimationTimeMillis(); 25354 if (now >= fadeStartTime) { 25355 25356 // the animation fades the scrollbars out by changing 25357 // the opacity (alpha) from fully opaque to fully 25358 // transparent 25359 int nextFrame = (int) now; 25360 int framesCount = 0; 25361 25362 Interpolator interpolator = scrollBarInterpolator; 25363 25364 // Start opaque 25365 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 25366 25367 // End transparent 25368 nextFrame += scrollBarFadeDuration; 25369 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 25370 25371 state = FADING; 25372 25373 // Kick off the fade animation 25374 host.invalidate(true); 25375 } 25376 } 25377 } 25378 25379 /** 25380 * Resuable callback for sending 25381 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 25382 */ 25383 private class SendViewScrolledAccessibilityEvent implements Runnable { 25384 public volatile boolean mIsPending; 25385 25386 public void run() { 25387 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 25388 mIsPending = false; 25389 } 25390 } 25391 25392 /** 25393 * <p> 25394 * This class represents a delegate that can be registered in a {@link View} 25395 * to enhance accessibility support via composition rather via inheritance. 25396 * It is specifically targeted to widget developers that extend basic View 25397 * classes i.e. classes in package android.view, that would like their 25398 * applications to be backwards compatible. 25399 * </p> 25400 * <div class="special reference"> 25401 * <h3>Developer Guides</h3> 25402 * <p>For more information about making applications accessible, read the 25403 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 25404 * developer guide.</p> 25405 * </div> 25406 * <p> 25407 * A scenario in which a developer would like to use an accessibility delegate 25408 * is overriding a method introduced in a later API version than the minimal API 25409 * version supported by the application. For example, the method 25410 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 25411 * in API version 4 when the accessibility APIs were first introduced. If a 25412 * developer would like his application to run on API version 4 devices (assuming 25413 * all other APIs used by the application are version 4 or lower) and take advantage 25414 * of this method, instead of overriding the method which would break the application's 25415 * backwards compatibility, he can override the corresponding method in this 25416 * delegate and register the delegate in the target View if the API version of 25417 * the system is high enough, i.e. the API version is the same as or higher than the API 25418 * version that introduced 25419 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 25420 * </p> 25421 * <p> 25422 * Here is an example implementation: 25423 * </p> 25424 * <code><pre><p> 25425 * if (Build.VERSION.SDK_INT >= 14) { 25426 * // If the API version is equal of higher than the version in 25427 * // which onInitializeAccessibilityNodeInfo was introduced we 25428 * // register a delegate with a customized implementation. 25429 * View view = findViewById(R.id.view_id); 25430 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 25431 * public void onInitializeAccessibilityNodeInfo(View host, 25432 * AccessibilityNodeInfo info) { 25433 * // Let the default implementation populate the info. 25434 * super.onInitializeAccessibilityNodeInfo(host, info); 25435 * // Set some other information. 25436 * info.setEnabled(host.isEnabled()); 25437 * } 25438 * }); 25439 * } 25440 * </code></pre></p> 25441 * <p> 25442 * This delegate contains methods that correspond to the accessibility methods 25443 * in View. If a delegate has been specified the implementation in View hands 25444 * off handling to the corresponding method in this delegate. The default 25445 * implementation the delegate methods behaves exactly as the corresponding 25446 * method in View for the case of no accessibility delegate been set. Hence, 25447 * to customize the behavior of a View method, clients can override only the 25448 * corresponding delegate method without altering the behavior of the rest 25449 * accessibility related methods of the host view. 25450 * </p> 25451 * <p> 25452 * <strong>Note:</strong> On platform versions prior to 25453 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 25454 * views in the {@code android.widget.*} package are called <i>before</i> 25455 * host methods. This prevents certain properties such as class name from 25456 * being modified by overriding 25457 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 25458 * as any changes will be overwritten by the host class. 25459 * <p> 25460 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 25461 * methods are called <i>after</i> host methods, which all properties to be 25462 * modified without being overwritten by the host class. 25463 */ 25464 public static class AccessibilityDelegate { 25465 25466 /** 25467 * Sends an accessibility event of the given type. If accessibility is not 25468 * enabled this method has no effect. 25469 * <p> 25470 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 25471 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 25472 * been set. 25473 * </p> 25474 * 25475 * @param host The View hosting the delegate. 25476 * @param eventType The type of the event to send. 25477 * 25478 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 25479 */ 25480 public void sendAccessibilityEvent(View host, int eventType) { 25481 host.sendAccessibilityEventInternal(eventType); 25482 } 25483 25484 /** 25485 * Performs the specified accessibility action on the view. For 25486 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 25487 * <p> 25488 * The default implementation behaves as 25489 * {@link View#performAccessibilityAction(int, Bundle) 25490 * View#performAccessibilityAction(int, Bundle)} for the case of 25491 * no accessibility delegate been set. 25492 * </p> 25493 * 25494 * @param action The action to perform. 25495 * @return Whether the action was performed. 25496 * 25497 * @see View#performAccessibilityAction(int, Bundle) 25498 * View#performAccessibilityAction(int, Bundle) 25499 */ 25500 public boolean performAccessibilityAction(View host, int action, Bundle args) { 25501 return host.performAccessibilityActionInternal(action, args); 25502 } 25503 25504 /** 25505 * Sends an accessibility event. This method behaves exactly as 25506 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 25507 * empty {@link AccessibilityEvent} and does not perform a check whether 25508 * accessibility is enabled. 25509 * <p> 25510 * The default implementation behaves as 25511 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25512 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 25513 * the case of no accessibility delegate been set. 25514 * </p> 25515 * 25516 * @param host The View hosting the delegate. 25517 * @param event The event to send. 25518 * 25519 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25520 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25521 */ 25522 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 25523 host.sendAccessibilityEventUncheckedInternal(event); 25524 } 25525 25526 /** 25527 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 25528 * to its children for adding their text content to the event. 25529 * <p> 25530 * The default implementation behaves as 25531 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25532 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 25533 * the case of no accessibility delegate been set. 25534 * </p> 25535 * 25536 * @param host The View hosting the delegate. 25537 * @param event The event. 25538 * @return True if the event population was completed. 25539 * 25540 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25541 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25542 */ 25543 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25544 return host.dispatchPopulateAccessibilityEventInternal(event); 25545 } 25546 25547 /** 25548 * Gives a chance to the host View to populate the accessibility event with its 25549 * text content. 25550 * <p> 25551 * The default implementation behaves as 25552 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 25553 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 25554 * the case of no accessibility delegate been set. 25555 * </p> 25556 * 25557 * @param host The View hosting the delegate. 25558 * @param event The accessibility event which to populate. 25559 * 25560 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 25561 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 25562 */ 25563 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25564 host.onPopulateAccessibilityEventInternal(event); 25565 } 25566 25567 /** 25568 * Initializes an {@link AccessibilityEvent} with information about the 25569 * the host View which is the event source. 25570 * <p> 25571 * The default implementation behaves as 25572 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 25573 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 25574 * the case of no accessibility delegate been set. 25575 * </p> 25576 * 25577 * @param host The View hosting the delegate. 25578 * @param event The event to initialize. 25579 * 25580 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 25581 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 25582 */ 25583 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 25584 host.onInitializeAccessibilityEventInternal(event); 25585 } 25586 25587 /** 25588 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 25589 * <p> 25590 * The default implementation behaves as 25591 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25592 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 25593 * the case of no accessibility delegate been set. 25594 * </p> 25595 * 25596 * @param host The View hosting the delegate. 25597 * @param info The instance to initialize. 25598 * 25599 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25600 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25601 */ 25602 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 25603 host.onInitializeAccessibilityNodeInfoInternal(info); 25604 } 25605 25606 /** 25607 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 25608 * additional data. 25609 * <p> 25610 * This method only needs to be implemented if the View offers to provide additional data. 25611 * </p> 25612 * <p> 25613 * The default implementation behaves as 25614 * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for 25615 * the case where no accessibility delegate is set. 25616 * </p> 25617 * 25618 * @param host The View hosting the delegate. Never {@code null}. 25619 * @param info The info to which to add the extra data. Never {@code null}. 25620 * @param extraDataKey A key specifying the type of extra data to add to the info. The 25621 * extra data should be added to the {@link Bundle} returned by 25622 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 25623 * {@code null}. 25624 * @param arguments A {@link Bundle} holding any arguments relevant for this request. 25625 * May be {@code null} if the if the service provided no arguments. 25626 * 25627 * @see AccessibilityNodeInfo#setExtraAvailableData 25628 */ 25629 public void addExtraDataToAccessibilityNodeInfo(@NonNull View host, 25630 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 25631 @Nullable Bundle arguments) { 25632 host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments); 25633 } 25634 25635 /** 25636 * Called when a child of the host View has requested sending an 25637 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 25638 * to augment the event. 25639 * <p> 25640 * The default implementation behaves as 25641 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25642 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 25643 * the case of no accessibility delegate been set. 25644 * </p> 25645 * 25646 * @param host The View hosting the delegate. 25647 * @param child The child which requests sending the event. 25648 * @param event The event to be sent. 25649 * @return True if the event should be sent 25650 * 25651 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25652 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25653 */ 25654 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 25655 AccessibilityEvent event) { 25656 return host.onRequestSendAccessibilityEventInternal(child, event); 25657 } 25658 25659 /** 25660 * Gets the provider for managing a virtual view hierarchy rooted at this View 25661 * and reported to {@link android.accessibilityservice.AccessibilityService}s 25662 * that explore the window content. 25663 * <p> 25664 * The default implementation behaves as 25665 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 25666 * the case of no accessibility delegate been set. 25667 * </p> 25668 * 25669 * @return The provider. 25670 * 25671 * @see AccessibilityNodeProvider 25672 */ 25673 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 25674 return null; 25675 } 25676 25677 /** 25678 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 25679 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 25680 * This method is responsible for obtaining an accessibility node info from a 25681 * pool of reusable instances and calling 25682 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 25683 * view to initialize the former. 25684 * <p> 25685 * <strong>Note:</strong> The client is responsible for recycling the obtained 25686 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 25687 * creation. 25688 * </p> 25689 * <p> 25690 * The default implementation behaves as 25691 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 25692 * the case of no accessibility delegate been set. 25693 * </p> 25694 * @return A populated {@link AccessibilityNodeInfo}. 25695 * 25696 * @see AccessibilityNodeInfo 25697 * 25698 * @hide 25699 */ 25700 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 25701 return host.createAccessibilityNodeInfoInternal(); 25702 } 25703 } 25704 25705 private static class MatchIdPredicate implements Predicate<View> { 25706 public int mId; 25707 25708 @Override 25709 public boolean test(View view) { 25710 return (view.mID == mId); 25711 } 25712 } 25713 25714 private static class MatchLabelForPredicate implements Predicate<View> { 25715 private int mLabeledId; 25716 25717 @Override 25718 public boolean test(View view) { 25719 return (view.mLabelForId == mLabeledId); 25720 } 25721 } 25722 25723 private class SendViewStateChangedAccessibilityEvent implements Runnable { 25724 private int mChangeTypes = 0; 25725 private boolean mPosted; 25726 private boolean mPostedWithDelay; 25727 private long mLastEventTimeMillis; 25728 25729 @Override 25730 public void run() { 25731 mPosted = false; 25732 mPostedWithDelay = false; 25733 mLastEventTimeMillis = SystemClock.uptimeMillis(); 25734 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 25735 final AccessibilityEvent event = AccessibilityEvent.obtain(); 25736 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 25737 event.setContentChangeTypes(mChangeTypes); 25738 sendAccessibilityEventUnchecked(event); 25739 } 25740 mChangeTypes = 0; 25741 } 25742 25743 public void runOrPost(int changeType) { 25744 mChangeTypes |= changeType; 25745 25746 // If this is a live region or the child of a live region, collect 25747 // all events from this frame and send them on the next frame. 25748 if (inLiveRegion()) { 25749 // If we're already posted with a delay, remove that. 25750 if (mPostedWithDelay) { 25751 removeCallbacks(this); 25752 mPostedWithDelay = false; 25753 } 25754 // Only post if we're not already posted. 25755 if (!mPosted) { 25756 post(this); 25757 mPosted = true; 25758 } 25759 return; 25760 } 25761 25762 if (mPosted) { 25763 return; 25764 } 25765 25766 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 25767 final long minEventIntevalMillis = 25768 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 25769 if (timeSinceLastMillis >= minEventIntevalMillis) { 25770 removeCallbacks(this); 25771 run(); 25772 } else { 25773 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 25774 mPostedWithDelay = true; 25775 } 25776 } 25777 } 25778 25779 private boolean inLiveRegion() { 25780 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25781 return true; 25782 } 25783 25784 ViewParent parent = getParent(); 25785 while (parent instanceof View) { 25786 if (((View) parent).getAccessibilityLiveRegion() 25787 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25788 return true; 25789 } 25790 parent = parent.getParent(); 25791 } 25792 25793 return false; 25794 } 25795 25796 /** 25797 * Dump all private flags in readable format, useful for documentation and 25798 * sanity checking. 25799 */ 25800 private static void dumpFlags() { 25801 final HashMap<String, String> found = Maps.newHashMap(); 25802 try { 25803 for (Field field : View.class.getDeclaredFields()) { 25804 final int modifiers = field.getModifiers(); 25805 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 25806 if (field.getType().equals(int.class)) { 25807 final int value = field.getInt(null); 25808 dumpFlag(found, field.getName(), value); 25809 } else if (field.getType().equals(int[].class)) { 25810 final int[] values = (int[]) field.get(null); 25811 for (int i = 0; i < values.length; i++) { 25812 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 25813 } 25814 } 25815 } 25816 } 25817 } catch (IllegalAccessException e) { 25818 throw new RuntimeException(e); 25819 } 25820 25821 final ArrayList<String> keys = Lists.newArrayList(); 25822 keys.addAll(found.keySet()); 25823 Collections.sort(keys); 25824 for (String key : keys) { 25825 Log.d(VIEW_LOG_TAG, found.get(key)); 25826 } 25827 } 25828 25829 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 25830 // Sort flags by prefix, then by bits, always keeping unique keys 25831 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 25832 final int prefix = name.indexOf('_'); 25833 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 25834 final String output = bits + " " + name; 25835 found.put(key, output); 25836 } 25837 25838 /** {@hide} */ 25839 public void encode(@NonNull ViewHierarchyEncoder stream) { 25840 stream.beginObject(this); 25841 encodeProperties(stream); 25842 stream.endObject(); 25843 } 25844 25845 /** {@hide} */ 25846 @CallSuper 25847 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 25848 Object resolveId = ViewDebug.resolveId(getContext(), mID); 25849 if (resolveId instanceof String) { 25850 stream.addProperty("id", (String) resolveId); 25851 } else { 25852 stream.addProperty("id", mID); 25853 } 25854 25855 stream.addProperty("misc:transformation.alpha", 25856 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 25857 stream.addProperty("misc:transitionName", getTransitionName()); 25858 25859 // layout 25860 stream.addProperty("layout:left", mLeft); 25861 stream.addProperty("layout:right", mRight); 25862 stream.addProperty("layout:top", mTop); 25863 stream.addProperty("layout:bottom", mBottom); 25864 stream.addProperty("layout:width", getWidth()); 25865 stream.addProperty("layout:height", getHeight()); 25866 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 25867 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 25868 stream.addProperty("layout:hasTransientState", hasTransientState()); 25869 stream.addProperty("layout:baseline", getBaseline()); 25870 25871 // layout params 25872 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 25873 if (layoutParams != null) { 25874 stream.addPropertyKey("layoutParams"); 25875 layoutParams.encode(stream); 25876 } 25877 25878 // scrolling 25879 stream.addProperty("scrolling:scrollX", mScrollX); 25880 stream.addProperty("scrolling:scrollY", mScrollY); 25881 25882 // padding 25883 stream.addProperty("padding:paddingLeft", mPaddingLeft); 25884 stream.addProperty("padding:paddingRight", mPaddingRight); 25885 stream.addProperty("padding:paddingTop", mPaddingTop); 25886 stream.addProperty("padding:paddingBottom", mPaddingBottom); 25887 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 25888 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 25889 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 25890 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 25891 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 25892 25893 // measurement 25894 stream.addProperty("measurement:minHeight", mMinHeight); 25895 stream.addProperty("measurement:minWidth", mMinWidth); 25896 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 25897 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 25898 25899 // drawing 25900 stream.addProperty("drawing:elevation", getElevation()); 25901 stream.addProperty("drawing:translationX", getTranslationX()); 25902 stream.addProperty("drawing:translationY", getTranslationY()); 25903 stream.addProperty("drawing:translationZ", getTranslationZ()); 25904 stream.addProperty("drawing:rotation", getRotation()); 25905 stream.addProperty("drawing:rotationX", getRotationX()); 25906 stream.addProperty("drawing:rotationY", getRotationY()); 25907 stream.addProperty("drawing:scaleX", getScaleX()); 25908 stream.addProperty("drawing:scaleY", getScaleY()); 25909 stream.addProperty("drawing:pivotX", getPivotX()); 25910 stream.addProperty("drawing:pivotY", getPivotY()); 25911 stream.addProperty("drawing:opaque", isOpaque()); 25912 stream.addProperty("drawing:alpha", getAlpha()); 25913 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 25914 stream.addProperty("drawing:shadow", hasShadow()); 25915 stream.addProperty("drawing:solidColor", getSolidColor()); 25916 stream.addProperty("drawing:layerType", mLayerType); 25917 stream.addProperty("drawing:willNotDraw", willNotDraw()); 25918 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 25919 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 25920 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 25921 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 25922 25923 // focus 25924 stream.addProperty("focus:hasFocus", hasFocus()); 25925 stream.addProperty("focus:isFocused", isFocused()); 25926 stream.addProperty("focus:focusable", getFocusable()); 25927 stream.addProperty("focus:isFocusable", isFocusable()); 25928 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 25929 25930 stream.addProperty("misc:clickable", isClickable()); 25931 stream.addProperty("misc:pressed", isPressed()); 25932 stream.addProperty("misc:selected", isSelected()); 25933 stream.addProperty("misc:touchMode", isInTouchMode()); 25934 stream.addProperty("misc:hovered", isHovered()); 25935 stream.addProperty("misc:activated", isActivated()); 25936 25937 stream.addProperty("misc:visibility", getVisibility()); 25938 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 25939 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 25940 25941 stream.addProperty("misc:enabled", isEnabled()); 25942 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 25943 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 25944 25945 // theme attributes 25946 Resources.Theme theme = getContext().getTheme(); 25947 if (theme != null) { 25948 stream.addPropertyKey("theme"); 25949 theme.encode(stream); 25950 } 25951 25952 // view attribute information 25953 int n = mAttributes != null ? mAttributes.length : 0; 25954 stream.addProperty("meta:__attrCount__", n/2); 25955 for (int i = 0; i < n; i += 2) { 25956 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 25957 } 25958 25959 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 25960 25961 // text 25962 stream.addProperty("text:textDirection", getTextDirection()); 25963 stream.addProperty("text:textAlignment", getTextAlignment()); 25964 25965 // accessibility 25966 CharSequence contentDescription = getContentDescription(); 25967 stream.addProperty("accessibility:contentDescription", 25968 contentDescription == null ? "" : contentDescription.toString()); 25969 stream.addProperty("accessibility:labelFor", getLabelFor()); 25970 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 25971 } 25972 25973 /** 25974 * Determine if this view is rendered on a round wearable device and is the main view 25975 * on the screen. 25976 */ 25977 boolean shouldDrawRoundScrollbar() { 25978 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 25979 return false; 25980 } 25981 25982 final View rootView = getRootView(); 25983 final WindowInsets insets = getRootWindowInsets(); 25984 25985 int height = getHeight(); 25986 int width = getWidth(); 25987 int displayHeight = rootView.getHeight(); 25988 int displayWidth = rootView.getWidth(); 25989 25990 if (height != displayHeight || width != displayWidth) { 25991 return false; 25992 } 25993 25994 getLocationInWindow(mAttachInfo.mTmpLocation); 25995 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 25996 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 25997 } 25998 25999 /** 26000 * Sets the tooltip text which will be displayed in a small popup next to the view. 26001 * <p> 26002 * The tooltip will be displayed: 26003 * <ul> 26004 * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context 26005 * menu). </li> 26006 * <li>On hover, after a brief delay since the pointer has stopped moving </li> 26007 * </ul> 26008 * <p> 26009 * <strong>Note:</strong> Do not override this method, as it will have no 26010 * effect on the text displayed in the tooltip. 26011 * 26012 * @param tooltipText the tooltip text, or null if no tooltip is required 26013 * @see #getTooltipText() 26014 * @attr ref android.R.styleable#View_tooltipText 26015 */ 26016 public void setTooltipText(@Nullable CharSequence tooltipText) { 26017 if (TextUtils.isEmpty(tooltipText)) { 26018 setFlags(0, TOOLTIP); 26019 hideTooltip(); 26020 mTooltipInfo = null; 26021 } else { 26022 setFlags(TOOLTIP, TOOLTIP); 26023 if (mTooltipInfo == null) { 26024 mTooltipInfo = new TooltipInfo(); 26025 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip; 26026 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip; 26027 } 26028 mTooltipInfo.mTooltipText = tooltipText; 26029 if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) { 26030 mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText); 26031 } 26032 } 26033 } 26034 26035 /** 26036 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 26037 */ 26038 public void setTooltip(@Nullable CharSequence tooltipText) { 26039 setTooltipText(tooltipText); 26040 } 26041 26042 /** 26043 * Returns the view's tooltip text. 26044 * 26045 * <strong>Note:</strong> Do not override this method, as it will have no 26046 * effect on the text displayed in the tooltip. You must call 26047 * {@link #setTooltipText(CharSequence)} to modify the tooltip text. 26048 * 26049 * @return the tooltip text 26050 * @see #setTooltipText(CharSequence) 26051 * @attr ref android.R.styleable#View_tooltipText 26052 */ 26053 @Nullable 26054 public CharSequence getTooltipText() { 26055 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null; 26056 } 26057 26058 /** 26059 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 26060 */ 26061 @Nullable 26062 public CharSequence getTooltip() { 26063 return getTooltipText(); 26064 } 26065 26066 private boolean showTooltip(int x, int y, boolean fromLongClick) { 26067 if (mAttachInfo == null || mTooltipInfo == null) { 26068 return false; 26069 } 26070 if ((mViewFlags & ENABLED_MASK) != ENABLED) { 26071 return false; 26072 } 26073 if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) { 26074 return false; 26075 } 26076 hideTooltip(); 26077 mTooltipInfo.mTooltipFromLongClick = fromLongClick; 26078 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext()); 26079 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN; 26080 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText); 26081 mAttachInfo.mTooltipHost = this; 26082 return true; 26083 } 26084 26085 void hideTooltip() { 26086 if (mTooltipInfo == null) { 26087 return; 26088 } 26089 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26090 if (mTooltipInfo.mTooltipPopup == null) { 26091 return; 26092 } 26093 mTooltipInfo.mTooltipPopup.hide(); 26094 mTooltipInfo.mTooltipPopup = null; 26095 mTooltipInfo.mTooltipFromLongClick = false; 26096 if (mAttachInfo != null) { 26097 mAttachInfo.mTooltipHost = null; 26098 } 26099 } 26100 26101 private boolean showLongClickTooltip(int x, int y) { 26102 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26103 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26104 return showTooltip(x, y, true); 26105 } 26106 26107 private void showHoverTooltip() { 26108 showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false); 26109 } 26110 26111 boolean dispatchTooltipHoverEvent(MotionEvent event) { 26112 if (mTooltipInfo == null) { 26113 return false; 26114 } 26115 switch(event.getAction()) { 26116 case MotionEvent.ACTION_HOVER_MOVE: 26117 if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) { 26118 break; 26119 } 26120 if (!mTooltipInfo.mTooltipFromLongClick) { 26121 if (mTooltipInfo.mTooltipPopup == null) { 26122 // Schedule showing the tooltip after a timeout. 26123 mTooltipInfo.mAnchorX = (int) event.getX(); 26124 mTooltipInfo.mAnchorY = (int) event.getY(); 26125 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 26126 postDelayed(mTooltipInfo.mShowTooltipRunnable, 26127 ViewConfiguration.getHoverTooltipShowTimeout()); 26128 } 26129 26130 // Hide hover-triggered tooltip after a period of inactivity. 26131 // Match the timeout used by NativeInputManager to hide the mouse pointer 26132 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set). 26133 final int timeout; 26134 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE) 26135 == SYSTEM_UI_FLAG_LOW_PROFILE) { 26136 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout(); 26137 } else { 26138 timeout = ViewConfiguration.getHoverTooltipHideTimeout(); 26139 } 26140 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26141 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout); 26142 } 26143 return true; 26144 26145 case MotionEvent.ACTION_HOVER_EXIT: 26146 if (!mTooltipInfo.mTooltipFromLongClick) { 26147 hideTooltip(); 26148 } 26149 break; 26150 } 26151 return false; 26152 } 26153 26154 void handleTooltipKey(KeyEvent event) { 26155 switch (event.getAction()) { 26156 case KeyEvent.ACTION_DOWN: 26157 if (event.getRepeatCount() == 0) { 26158 hideTooltip(); 26159 } 26160 break; 26161 26162 case KeyEvent.ACTION_UP: 26163 handleTooltipUp(); 26164 break; 26165 } 26166 } 26167 26168 private void handleTooltipUp() { 26169 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 26170 return; 26171 } 26172 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 26173 postDelayed(mTooltipInfo.mHideTooltipRunnable, 26174 ViewConfiguration.getLongPressTooltipHideTimeout()); 26175 } 26176 26177 private int getFocusableAttribute(TypedArray attributes) { 26178 TypedValue val = new TypedValue(); 26179 if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) { 26180 if (val.type == TypedValue.TYPE_INT_BOOLEAN) { 26181 return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE); 26182 } else { 26183 return val.data; 26184 } 26185 } else { 26186 return FOCUSABLE_AUTO; 26187 } 26188 } 26189 26190 /** 26191 * @return The content view of the tooltip popup currently being shown, or null if the tooltip 26192 * is not showing. 26193 * @hide 26194 */ 26195 @TestApi 26196 public View getTooltipView() { 26197 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 26198 return null; 26199 } 26200 return mTooltipInfo.mTooltipPopup.getContentView(); 26201 } 26202} 26203