View.java revision 5c5e0ac419b7cb4bfcf08dd25852a2c7b2eeedd7
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; 20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; 21import static android.os.Build.VERSION_CODES.KITKAT; 22import static android.os.Build.VERSION_CODES.M; 23import static android.os.Build.VERSION_CODES.N; 24 25import static java.lang.Math.max; 26 27import android.animation.AnimatorInflater; 28import android.animation.StateListAnimator; 29import android.annotation.CallSuper; 30import android.annotation.ColorInt; 31import android.annotation.DrawableRes; 32import android.annotation.FloatRange; 33import android.annotation.IdRes; 34import android.annotation.IntDef; 35import android.annotation.IntRange; 36import android.annotation.LayoutRes; 37import android.annotation.NonNull; 38import android.annotation.Nullable; 39import android.annotation.Size; 40import android.annotation.TestApi; 41import android.annotation.UiThread; 42import android.app.Application.OnProvideAssistDataListener; 43import android.content.ClipData; 44import android.content.Context; 45import android.content.ContextWrapper; 46import android.content.Intent; 47import android.content.res.ColorStateList; 48import android.content.res.Configuration; 49import android.content.res.Resources; 50import android.content.res.TypedArray; 51import android.graphics.Bitmap; 52import android.graphics.Canvas; 53import android.graphics.Color; 54import android.graphics.Insets; 55import android.graphics.Interpolator; 56import android.graphics.LinearGradient; 57import android.graphics.Matrix; 58import android.graphics.Outline; 59import android.graphics.Paint; 60import android.graphics.PixelFormat; 61import android.graphics.Point; 62import android.graphics.PorterDuff; 63import android.graphics.PorterDuffXfermode; 64import android.graphics.Rect; 65import android.graphics.RectF; 66import android.graphics.Region; 67import android.graphics.Shader; 68import android.graphics.drawable.ColorDrawable; 69import android.graphics.drawable.Drawable; 70import android.hardware.display.DisplayManagerGlobal; 71import android.os.Build.VERSION_CODES; 72import android.os.Bundle; 73import android.os.Handler; 74import android.os.IBinder; 75import android.os.Parcel; 76import android.os.Parcelable; 77import android.os.RemoteException; 78import android.os.SystemClock; 79import android.os.SystemProperties; 80import android.os.Trace; 81import android.text.TextUtils; 82import android.util.AttributeSet; 83import android.util.FloatProperty; 84import android.util.LayoutDirection; 85import android.util.Log; 86import android.util.LongSparseLongArray; 87import android.util.Pools.SynchronizedPool; 88import android.util.Property; 89import android.util.SparseArray; 90import android.util.StateSet; 91import android.util.SuperNotCalledException; 92import android.util.TypedValue; 93import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 94import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 95import android.view.AccessibilityIterators.TextSegmentIterator; 96import android.view.AccessibilityIterators.WordTextSegmentIterator; 97import android.view.ContextMenu.ContextMenuInfo; 98import android.view.accessibility.AccessibilityEvent; 99import android.view.accessibility.AccessibilityEventSource; 100import android.view.accessibility.AccessibilityManager; 101import android.view.accessibility.AccessibilityNodeInfo; 102import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 103import android.view.accessibility.AccessibilityNodeProvider; 104import android.view.animation.Animation; 105import android.view.animation.AnimationUtils; 106import android.view.animation.Transformation; 107import android.view.autofill.AutoFillType; 108import android.view.autofill.AutoFillValue; 109import android.view.autofill.VirtualViewDelegate; 110import android.view.inputmethod.EditorInfo; 111import android.view.inputmethod.InputConnection; 112import android.view.inputmethod.InputMethodManager; 113import android.widget.Checkable; 114import android.widget.FrameLayout; 115import android.widget.ScrollBarDrawable; 116 117import com.android.internal.R; 118import com.android.internal.util.Predicate; 119import com.android.internal.view.TooltipPopup; 120import com.android.internal.view.menu.MenuBuilder; 121import com.android.internal.widget.ScrollBarUtils; 122 123import com.google.android.collect.Lists; 124import com.google.android.collect.Maps; 125 126import java.lang.annotation.Retention; 127import java.lang.annotation.RetentionPolicy; 128import java.lang.ref.WeakReference; 129import java.lang.reflect.Field; 130import java.lang.reflect.InvocationTargetException; 131import java.lang.reflect.Method; 132import java.lang.reflect.Modifier; 133import java.util.ArrayList; 134import java.util.Arrays; 135import java.util.Collection; 136import java.util.Collections; 137import java.util.HashMap; 138import java.util.List; 139import java.util.Locale; 140import java.util.Map; 141import java.util.concurrent.CopyOnWriteArrayList; 142import java.util.concurrent.atomic.AtomicInteger; 143 144/** 145 * <p> 146 * This class represents the basic building block for user interface components. A View 147 * occupies a rectangular area on the screen and is responsible for drawing and 148 * event handling. View is the base class for <em>widgets</em>, which are 149 * used to create interactive UI components (buttons, text fields, etc.). The 150 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 151 * are invisible containers that hold other Views (or other ViewGroups) and define 152 * their layout properties. 153 * </p> 154 * 155 * <div class="special reference"> 156 * <h3>Developer Guides</h3> 157 * <p>For information about using this class to develop your application's user interface, 158 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 159 * </div> 160 * 161 * <a name="Using"></a> 162 * <h3>Using Views</h3> 163 * <p> 164 * All of the views in a window are arranged in a single tree. You can add views 165 * either from code or by specifying a tree of views in one or more XML layout 166 * files. There are many specialized subclasses of views that act as controls or 167 * are capable of displaying text, images, or other content. 168 * </p> 169 * <p> 170 * Once you have created a tree of views, there are typically a few types of 171 * common operations you may wish to perform: 172 * <ul> 173 * <li><strong>Set properties:</strong> for example setting the text of a 174 * {@link android.widget.TextView}. The available properties and the methods 175 * that set them will vary among the different subclasses of views. Note that 176 * properties that are known at build time can be set in the XML layout 177 * files.</li> 178 * <li><strong>Set focus:</strong> The framework will handle moving focus in 179 * response to user input. To force focus to a specific view, call 180 * {@link #requestFocus}.</li> 181 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 182 * that will be notified when something interesting happens to the view. For 183 * example, all views will let you set a listener to be notified when the view 184 * gains or loses focus. You can register such a listener using 185 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 186 * Other view subclasses offer more specialized listeners. For example, a Button 187 * exposes a listener to notify clients when the button is clicked.</li> 188 * <li><strong>Set visibility:</strong> You can hide or show views using 189 * {@link #setVisibility(int)}.</li> 190 * </ul> 191 * </p> 192 * <p><em> 193 * Note: The Android framework is responsible for measuring, laying out and 194 * drawing views. You should not call methods that perform these actions on 195 * views yourself unless you are actually implementing a 196 * {@link android.view.ViewGroup}. 197 * </em></p> 198 * 199 * <a name="Lifecycle"></a> 200 * <h3>Implementing a Custom View</h3> 201 * 202 * <p> 203 * To implement a custom view, you will usually begin by providing overrides for 204 * some of the standard methods that the framework calls on all views. You do 205 * not need to override all of these methods. In fact, you can start by just 206 * overriding {@link #onDraw(android.graphics.Canvas)}. 207 * <table border="2" width="85%" align="center" cellpadding="5"> 208 * <thead> 209 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 210 * </thead> 211 * 212 * <tbody> 213 * <tr> 214 * <td rowspan="2">Creation</td> 215 * <td>Constructors</td> 216 * <td>There is a form of the constructor that are called when the view 217 * is created from code and a form that is called when the view is 218 * inflated from a layout file. The second form should parse and apply 219 * any attributes defined in the layout file. 220 * </td> 221 * </tr> 222 * <tr> 223 * <td><code>{@link #onFinishInflate()}</code></td> 224 * <td>Called after a view and all of its children has been inflated 225 * from XML.</td> 226 * </tr> 227 * 228 * <tr> 229 * <td rowspan="3">Layout</td> 230 * <td><code>{@link #onMeasure(int, int)}</code></td> 231 * <td>Called to determine the size requirements for this view and all 232 * of its children. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 237 * <td>Called when this view should assign a size and position to all 238 * of its children. 239 * </td> 240 * </tr> 241 * <tr> 242 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 243 * <td>Called when the size of this view has changed. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td>Drawing</td> 249 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 250 * <td>Called when the view should render its content. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td rowspan="4">Event processing</td> 256 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 257 * <td>Called when a new hardware key event occurs. 258 * </td> 259 * </tr> 260 * <tr> 261 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 262 * <td>Called when a hardware key up event occurs. 263 * </td> 264 * </tr> 265 * <tr> 266 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 267 * <td>Called when a trackball motion event occurs. 268 * </td> 269 * </tr> 270 * <tr> 271 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 272 * <td>Called when a touch screen motion event occurs. 273 * </td> 274 * </tr> 275 * 276 * <tr> 277 * <td rowspan="2">Focus</td> 278 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 279 * <td>Called when the view gains or loses focus. 280 * </td> 281 * </tr> 282 * 283 * <tr> 284 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 285 * <td>Called when the window containing the view gains or loses focus. 286 * </td> 287 * </tr> 288 * 289 * <tr> 290 * <td rowspan="3">Attaching</td> 291 * <td><code>{@link #onAttachedToWindow()}</code></td> 292 * <td>Called when the view is attached to a window. 293 * </td> 294 * </tr> 295 * 296 * <tr> 297 * <td><code>{@link #onDetachedFromWindow}</code></td> 298 * <td>Called when the view is detached from its window. 299 * </td> 300 * </tr> 301 * 302 * <tr> 303 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 304 * <td>Called when the visibility of the window containing the view 305 * has changed. 306 * </td> 307 * </tr> 308 * </tbody> 309 * 310 * </table> 311 * </p> 312 * 313 * <a name="IDs"></a> 314 * <h3>IDs</h3> 315 * Views may have an integer id associated with them. These ids are typically 316 * assigned in the layout XML files, and are used to find specific views within 317 * the view tree. A common pattern is to: 318 * <ul> 319 * <li>Define a Button in the layout file and assign it a unique ID. 320 * <pre> 321 * <Button 322 * android:id="@+id/my_button" 323 * android:layout_width="wrap_content" 324 * android:layout_height="wrap_content" 325 * android:text="@string/my_button_text"/> 326 * </pre></li> 327 * <li>From the onCreate method of an Activity, find the Button 328 * <pre class="prettyprint"> 329 * Button myButton = (Button) findViewById(R.id.my_button); 330 * </pre></li> 331 * </ul> 332 * <p> 333 * View IDs need not be unique throughout the tree, but it is good practice to 334 * ensure that they are at least unique within the part of the tree you are 335 * searching. 336 * </p> 337 * 338 * <a name="Position"></a> 339 * <h3>Position</h3> 340 * <p> 341 * The geometry of a view is that of a rectangle. A view has a location, 342 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 343 * two dimensions, expressed as a width and a height. The unit for location 344 * and dimensions is the pixel. 345 * </p> 346 * 347 * <p> 348 * It is possible to retrieve the location of a view by invoking the methods 349 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 350 * coordinate of the rectangle representing the view. The latter returns the 351 * top, or Y, coordinate of the rectangle representing the view. These methods 352 * both return the location of the view relative to its parent. For instance, 353 * when getLeft() returns 20, that means the view is located 20 pixels to the 354 * right of the left edge of its direct parent. 355 * </p> 356 * 357 * <p> 358 * In addition, several convenience methods are offered to avoid unnecessary 359 * computations, namely {@link #getRight()} and {@link #getBottom()}. 360 * These methods return the coordinates of the right and bottom edges of the 361 * rectangle representing the view. For instance, calling {@link #getRight()} 362 * is similar to the following computation: <code>getLeft() + getWidth()</code> 363 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 364 * </p> 365 * 366 * <a name="SizePaddingMargins"></a> 367 * <h3>Size, padding and margins</h3> 368 * <p> 369 * The size of a view is expressed with a width and a height. A view actually 370 * possess two pairs of width and height values. 371 * </p> 372 * 373 * <p> 374 * The first pair is known as <em>measured width</em> and 375 * <em>measured height</em>. These dimensions define how big a view wants to be 376 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 377 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 378 * and {@link #getMeasuredHeight()}. 379 * </p> 380 * 381 * <p> 382 * The second pair is simply known as <em>width</em> and <em>height</em>, or 383 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 384 * dimensions define the actual size of the view on screen, at drawing time and 385 * after layout. These values may, but do not have to, be different from the 386 * measured width and height. The width and height can be obtained by calling 387 * {@link #getWidth()} and {@link #getHeight()}. 388 * </p> 389 * 390 * <p> 391 * To measure its dimensions, a view takes into account its padding. The padding 392 * is expressed in pixels for the left, top, right and bottom parts of the view. 393 * Padding can be used to offset the content of the view by a specific amount of 394 * pixels. For instance, a left padding of 2 will push the view's content by 395 * 2 pixels to the right of the left edge. Padding can be set using the 396 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 397 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 398 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 399 * {@link #getPaddingEnd()}. 400 * </p> 401 * 402 * <p> 403 * Even though a view can define a padding, it does not provide any support for 404 * margins. However, view groups provide such a support. Refer to 405 * {@link android.view.ViewGroup} and 406 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 407 * </p> 408 * 409 * <a name="Layout"></a> 410 * <h3>Layout</h3> 411 * <p> 412 * Layout is a two pass process: a measure pass and a layout pass. The measuring 413 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 414 * of the view tree. Each view pushes dimension specifications down the tree 415 * during the recursion. At the end of the measure pass, every view has stored 416 * its measurements. The second pass happens in 417 * {@link #layout(int,int,int,int)} and is also top-down. During 418 * this pass each parent is responsible for positioning all of its children 419 * using the sizes computed in the measure pass. 420 * </p> 421 * 422 * <p> 423 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 424 * {@link #getMeasuredHeight()} values must be set, along with those for all of 425 * that view's descendants. A view's measured width and measured height values 426 * must respect the constraints imposed by the view's parents. This guarantees 427 * that at the end of the measure pass, all parents accept all of their 428 * children's measurements. A parent view may call measure() more than once on 429 * its children. For example, the parent may measure each child once with 430 * unspecified dimensions to find out how big they want to be, then call 431 * measure() on them again with actual numbers if the sum of all the children's 432 * unconstrained sizes is too big or too small. 433 * </p> 434 * 435 * <p> 436 * The measure pass uses two classes to communicate dimensions. The 437 * {@link MeasureSpec} class is used by views to tell their parents how they 438 * want to be measured and positioned. The base LayoutParams class just 439 * describes how big the view wants to be for both width and height. For each 440 * dimension, it can specify one of: 441 * <ul> 442 * <li> an exact number 443 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 444 * (minus padding) 445 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 446 * enclose its content (plus padding). 447 * </ul> 448 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 449 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 450 * an X and Y value. 451 * </p> 452 * 453 * <p> 454 * MeasureSpecs are used to push requirements down the tree from parent to 455 * child. A MeasureSpec can be in one of three modes: 456 * <ul> 457 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 458 * of a child view. For example, a LinearLayout may call measure() on its child 459 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 460 * tall the child view wants to be given a width of 240 pixels. 461 * <li>EXACTLY: This is used by the parent to impose an exact size on the 462 * child. The child must use this size, and guarantee that all of its 463 * descendants will fit within this size. 464 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 465 * child. The child must guarantee that it and all of its descendants will fit 466 * within this size. 467 * </ul> 468 * </p> 469 * 470 * <p> 471 * To initiate a layout, call {@link #requestLayout}. This method is typically 472 * called by a view on itself when it believes that is can no longer fit within 473 * its current bounds. 474 * </p> 475 * 476 * <a name="Drawing"></a> 477 * <h3>Drawing</h3> 478 * <p> 479 * Drawing is handled by walking the tree and recording the drawing commands of 480 * any View that needs to update. After this, the drawing commands of the 481 * entire tree are issued to screen, clipped to the newly damaged area. 482 * </p> 483 * 484 * <p> 485 * The tree is largely recorded and drawn in order, with parents drawn before 486 * (i.e., behind) their children, with siblings drawn in the order they appear 487 * in the tree. If you set a background drawable for a View, then the View will 488 * draw it before calling back to its <code>onDraw()</code> method. The child 489 * drawing order can be overridden with 490 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 491 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 492 * </p> 493 * 494 * <p> 495 * To force a view to draw, call {@link #invalidate()}. 496 * </p> 497 * 498 * <a name="EventHandlingThreading"></a> 499 * <h3>Event Handling and Threading</h3> 500 * <p> 501 * The basic cycle of a view is as follows: 502 * <ol> 503 * <li>An event comes in and is dispatched to the appropriate view. The view 504 * handles the event and notifies any listeners.</li> 505 * <li>If in the course of processing the event, the view's bounds may need 506 * to be changed, the view will call {@link #requestLayout()}.</li> 507 * <li>Similarly, if in the course of processing the event the view's appearance 508 * may need to be changed, the view will call {@link #invalidate()}.</li> 509 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 510 * the framework will take care of measuring, laying out, and drawing the tree 511 * as appropriate.</li> 512 * </ol> 513 * </p> 514 * 515 * <p><em>Note: The entire view tree is single threaded. You must always be on 516 * the UI thread when calling any method on any view.</em> 517 * If you are doing work on other threads and want to update the state of a view 518 * from that thread, you should use a {@link Handler}. 519 * </p> 520 * 521 * <a name="FocusHandling"></a> 522 * <h3>Focus Handling</h3> 523 * <p> 524 * The framework will handle routine focus movement in response to user input. 525 * This includes changing the focus as views are removed or hidden, or as new 526 * views become available. Views indicate their willingness to take focus 527 * through the {@link #isFocusable} method. To change whether a view can take 528 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 529 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 530 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 531 * </p> 532 * <p> 533 * Focus movement is based on an algorithm which finds the nearest neighbor in a 534 * given direction. In rare cases, the default algorithm may not match the 535 * intended behavior of the developer. In these situations, you can provide 536 * explicit overrides by using these XML attributes in the layout file: 537 * <pre> 538 * nextFocusDown 539 * nextFocusLeft 540 * nextFocusRight 541 * nextFocusUp 542 * </pre> 543 * </p> 544 * 545 * 546 * <p> 547 * To get a particular view to take focus, call {@link #requestFocus()}. 548 * </p> 549 * 550 * <a name="TouchMode"></a> 551 * <h3>Touch Mode</h3> 552 * <p> 553 * When a user is navigating a user interface via directional keys such as a D-pad, it is 554 * necessary to give focus to actionable items such as buttons so the user can see 555 * what will take input. If the device has touch capabilities, however, and the user 556 * begins interacting with the interface by touching it, it is no longer necessary to 557 * always highlight, or give focus to, a particular view. This motivates a mode 558 * for interaction named 'touch mode'. 559 * </p> 560 * <p> 561 * For a touch capable device, once the user touches the screen, the device 562 * will enter touch mode. From this point onward, only views for which 563 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 564 * Other views that are touchable, like buttons, will not take focus when touched; they will 565 * only fire the on click listeners. 566 * </p> 567 * <p> 568 * Any time a user hits a directional key, such as a D-pad direction, the view device will 569 * exit touch mode, and find a view to take focus, so that the user may resume interacting 570 * with the user interface without touching the screen again. 571 * </p> 572 * <p> 573 * The touch mode state is maintained across {@link android.app.Activity}s. Call 574 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 575 * </p> 576 * 577 * <a name="Scrolling"></a> 578 * <h3>Scrolling</h3> 579 * <p> 580 * The framework provides basic support for views that wish to internally 581 * scroll their content. This includes keeping track of the X and Y scroll 582 * offset as well as mechanisms for drawing scrollbars. See 583 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 584 * {@link #awakenScrollBars()} for more details. 585 * </p> 586 * 587 * <a name="Tags"></a> 588 * <h3>Tags</h3> 589 * <p> 590 * Unlike IDs, tags are not used to identify views. Tags are essentially an 591 * extra piece of information that can be associated with a view. They are most 592 * often used as a convenience to store data related to views in the views 593 * themselves rather than by putting them in a separate structure. 594 * </p> 595 * <p> 596 * Tags may be specified with character sequence values in layout XML as either 597 * a single tag using the {@link android.R.styleable#View_tag android:tag} 598 * attribute or multiple tags using the {@code <tag>} child element: 599 * <pre> 600 * <View ... 601 * android:tag="@string/mytag_value" /> 602 * <View ...> 603 * <tag android:id="@+id/mytag" 604 * android:value="@string/mytag_value" /> 605 * </View> 606 * </pre> 607 * </p> 608 * <p> 609 * Tags may also be specified with arbitrary objects from code using 610 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 611 * </p> 612 * 613 * <a name="Themes"></a> 614 * <h3>Themes</h3> 615 * <p> 616 * By default, Views are created using the theme of the Context object supplied 617 * to their constructor; however, a different theme may be specified by using 618 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 619 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 620 * code. 621 * </p> 622 * <p> 623 * When the {@link android.R.styleable#View_theme android:theme} attribute is 624 * used in XML, the specified theme is applied on top of the inflation 625 * context's theme (see {@link LayoutInflater}) and used for the view itself as 626 * well as any child elements. 627 * </p> 628 * <p> 629 * In the following example, both views will be created using the Material dark 630 * color scheme; however, because an overlay theme is used which only defines a 631 * subset of attributes, the value of 632 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 633 * the inflation context's theme (e.g. the Activity theme) will be preserved. 634 * <pre> 635 * <LinearLayout 636 * ... 637 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 638 * <View ...> 639 * </LinearLayout> 640 * </pre> 641 * </p> 642 * 643 * <a name="Properties"></a> 644 * <h3>Properties</h3> 645 * <p> 646 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 647 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 648 * available both in the {@link Property} form as well as in similarly-named setter/getter 649 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 650 * be used to set persistent state associated with these rendering-related properties on the view. 651 * The properties and methods can also be used in conjunction with 652 * {@link android.animation.Animator Animator}-based animations, described more in the 653 * <a href="#Animation">Animation</a> section. 654 * </p> 655 * 656 * <a name="Animation"></a> 657 * <h3>Animation</h3> 658 * <p> 659 * Starting with Android 3.0, the preferred way of animating views is to use the 660 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 661 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 662 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 663 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 664 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 665 * makes animating these View properties particularly easy and efficient. 666 * </p> 667 * <p> 668 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 669 * You can attach an {@link Animation} object to a view using 670 * {@link #setAnimation(Animation)} or 671 * {@link #startAnimation(Animation)}. The animation can alter the scale, 672 * rotation, translation and alpha of a view over time. If the animation is 673 * attached to a view that has children, the animation will affect the entire 674 * subtree rooted by that node. When an animation is started, the framework will 675 * take care of redrawing the appropriate views until the animation completes. 676 * </p> 677 * 678 * <a name="Security"></a> 679 * <h3>Security</h3> 680 * <p> 681 * Sometimes it is essential that an application be able to verify that an action 682 * is being performed with the full knowledge and consent of the user, such as 683 * granting a permission request, making a purchase or clicking on an advertisement. 684 * Unfortunately, a malicious application could try to spoof the user into 685 * performing these actions, unaware, by concealing the intended purpose of the view. 686 * As a remedy, the framework offers a touch filtering mechanism that can be used to 687 * improve the security of views that provide access to sensitive functionality. 688 * </p><p> 689 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 690 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 691 * will discard touches that are received whenever the view's window is obscured by 692 * another visible window. As a result, the view will not receive touches whenever a 693 * toast, dialog or other window appears above the view's window. 694 * </p><p> 695 * For more fine-grained control over security, consider overriding the 696 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 697 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 698 * </p> 699 * 700 * @attr ref android.R.styleable#View_alpha 701 * @attr ref android.R.styleable#View_background 702 * @attr ref android.R.styleable#View_clickable 703 * @attr ref android.R.styleable#View_contentDescription 704 * @attr ref android.R.styleable#View_drawingCacheQuality 705 * @attr ref android.R.styleable#View_duplicateParentState 706 * @attr ref android.R.styleable#View_id 707 * @attr ref android.R.styleable#View_requiresFadingEdge 708 * @attr ref android.R.styleable#View_fadeScrollbars 709 * @attr ref android.R.styleable#View_fadingEdgeLength 710 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 711 * @attr ref android.R.styleable#View_fitsSystemWindows 712 * @attr ref android.R.styleable#View_isScrollContainer 713 * @attr ref android.R.styleable#View_focusable 714 * @attr ref android.R.styleable#View_focusableInTouchMode 715 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 716 * @attr ref android.R.styleable#View_keepScreenOn 717 * @attr ref android.R.styleable#View_layerType 718 * @attr ref android.R.styleable#View_layoutDirection 719 * @attr ref android.R.styleable#View_longClickable 720 * @attr ref android.R.styleable#View_minHeight 721 * @attr ref android.R.styleable#View_minWidth 722 * @attr ref android.R.styleable#View_nextFocusDown 723 * @attr ref android.R.styleable#View_nextFocusLeft 724 * @attr ref android.R.styleable#View_nextFocusRight 725 * @attr ref android.R.styleable#View_nextFocusUp 726 * @attr ref android.R.styleable#View_onClick 727 * @attr ref android.R.styleable#View_padding 728 * @attr ref android.R.styleable#View_paddingBottom 729 * @attr ref android.R.styleable#View_paddingLeft 730 * @attr ref android.R.styleable#View_paddingRight 731 * @attr ref android.R.styleable#View_paddingTop 732 * @attr ref android.R.styleable#View_paddingStart 733 * @attr ref android.R.styleable#View_paddingEnd 734 * @attr ref android.R.styleable#View_saveEnabled 735 * @attr ref android.R.styleable#View_rotation 736 * @attr ref android.R.styleable#View_rotationX 737 * @attr ref android.R.styleable#View_rotationY 738 * @attr ref android.R.styleable#View_scaleX 739 * @attr ref android.R.styleable#View_scaleY 740 * @attr ref android.R.styleable#View_scrollX 741 * @attr ref android.R.styleable#View_scrollY 742 * @attr ref android.R.styleable#View_scrollbarSize 743 * @attr ref android.R.styleable#View_scrollbarStyle 744 * @attr ref android.R.styleable#View_scrollbars 745 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 746 * @attr ref android.R.styleable#View_scrollbarFadeDuration 747 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 748 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 749 * @attr ref android.R.styleable#View_scrollbarThumbVertical 750 * @attr ref android.R.styleable#View_scrollbarTrackVertical 751 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 752 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 753 * @attr ref android.R.styleable#View_stateListAnimator 754 * @attr ref android.R.styleable#View_transitionName 755 * @attr ref android.R.styleable#View_soundEffectsEnabled 756 * @attr ref android.R.styleable#View_tag 757 * @attr ref android.R.styleable#View_textAlignment 758 * @attr ref android.R.styleable#View_textDirection 759 * @attr ref android.R.styleable#View_transformPivotX 760 * @attr ref android.R.styleable#View_transformPivotY 761 * @attr ref android.R.styleable#View_translationX 762 * @attr ref android.R.styleable#View_translationY 763 * @attr ref android.R.styleable#View_translationZ 764 * @attr ref android.R.styleable#View_visibility 765 * @attr ref android.R.styleable#View_theme 766 * 767 * @see android.view.ViewGroup 768 */ 769@UiThread 770public class View implements Drawable.Callback, KeyEvent.Callback, 771 AccessibilityEventSource { 772 private static final boolean DBG = false; 773 774 /** @hide */ 775 public static boolean DEBUG_DRAW = false; 776 777 /** 778 * The logging tag used by this class with android.util.Log. 779 */ 780 protected static final String VIEW_LOG_TAG = "View"; 781 782 /** 783 * When set to true, apps will draw debugging information about their layouts. 784 * 785 * @hide 786 */ 787 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 788 789 /** 790 * When set to true, this view will save its attribute data. 791 * 792 * @hide 793 */ 794 public static boolean mDebugViewAttributes = false; 795 796 /** 797 * Used to mark a View that has no ID. 798 */ 799 public static final int NO_ID = -1; 800 801 /** 802 * Signals that compatibility booleans have been initialized according to 803 * target SDK versions. 804 */ 805 private static boolean sCompatibilityDone = false; 806 807 /** 808 * Use the old (broken) way of building MeasureSpecs. 809 */ 810 private static boolean sUseBrokenMakeMeasureSpec = false; 811 812 /** 813 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 814 */ 815 static boolean sUseZeroUnspecifiedMeasureSpec = false; 816 817 /** 818 * Ignore any optimizations using the measure cache. 819 */ 820 private static boolean sIgnoreMeasureCache = false; 821 822 /** 823 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 824 */ 825 private static boolean sAlwaysRemeasureExactly = false; 826 827 /** 828 * Relax constraints around whether setLayoutParams() must be called after 829 * modifying the layout params. 830 */ 831 private static boolean sLayoutParamsAlwaysChanged = false; 832 833 /** 834 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 835 * without throwing 836 */ 837 static boolean sTextureViewIgnoresDrawableSetters = false; 838 839 /** 840 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 841 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 842 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 843 * check is implemented for backwards compatibility. 844 * 845 * {@hide} 846 */ 847 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 848 849 /** 850 * Prior to N, when drag enters into child of a view that has already received an 851 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 852 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 853 * false from its event handler for these events. 854 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 855 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 856 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 857 */ 858 static boolean sCascadedDragDrop; 859 860 /** 861 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 862 * calling setFlags. 863 */ 864 private static final int NOT_FOCUSABLE = 0x00000000; 865 866 /** 867 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 868 * setFlags. 869 */ 870 private static final int FOCUSABLE = 0x00000001; 871 872 /** 873 * Mask for use with setFlags indicating bits used for focus. 874 */ 875 private static final int FOCUSABLE_MASK = 0x00000001; 876 877 /** 878 * This view will adjust its padding to fit sytem windows (e.g. status bar) 879 */ 880 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 881 882 /** @hide */ 883 @IntDef({VISIBLE, INVISIBLE, GONE}) 884 @Retention(RetentionPolicy.SOURCE) 885 public @interface Visibility {} 886 887 /** 888 * This view is visible. 889 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 890 * android:visibility}. 891 */ 892 public static final int VISIBLE = 0x00000000; 893 894 /** 895 * This view is invisible, but it still takes up space for layout purposes. 896 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 897 * android:visibility}. 898 */ 899 public static final int INVISIBLE = 0x00000004; 900 901 /** 902 * This view is invisible, and it doesn't take any space for layout 903 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 904 * android:visibility}. 905 */ 906 public static final int GONE = 0x00000008; 907 908 /** 909 * Mask for use with setFlags indicating bits used for visibility. 910 * {@hide} 911 */ 912 static final int VISIBILITY_MASK = 0x0000000C; 913 914 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 915 916 /** 917 * This view is enabled. Interpretation varies by subclass. 918 * Use with ENABLED_MASK when calling setFlags. 919 * {@hide} 920 */ 921 static final int ENABLED = 0x00000000; 922 923 /** 924 * This view is disabled. Interpretation varies by subclass. 925 * Use with ENABLED_MASK when calling setFlags. 926 * {@hide} 927 */ 928 static final int DISABLED = 0x00000020; 929 930 /** 931 * Mask for use with setFlags indicating bits used for indicating whether 932 * this view is enabled 933 * {@hide} 934 */ 935 static final int ENABLED_MASK = 0x00000020; 936 937 /** 938 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 939 * called and further optimizations will be performed. It is okay to have 940 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 941 * {@hide} 942 */ 943 static final int WILL_NOT_DRAW = 0x00000080; 944 945 /** 946 * Mask for use with setFlags indicating bits used for indicating whether 947 * this view is will draw 948 * {@hide} 949 */ 950 static final int DRAW_MASK = 0x00000080; 951 952 /** 953 * <p>This view doesn't show scrollbars.</p> 954 * {@hide} 955 */ 956 static final int SCROLLBARS_NONE = 0x00000000; 957 958 /** 959 * <p>This view shows horizontal scrollbars.</p> 960 * {@hide} 961 */ 962 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 963 964 /** 965 * <p>This view shows vertical scrollbars.</p> 966 * {@hide} 967 */ 968 static final int SCROLLBARS_VERTICAL = 0x00000200; 969 970 /** 971 * <p>Mask for use with setFlags indicating bits used for indicating which 972 * scrollbars are enabled.</p> 973 * {@hide} 974 */ 975 static final int SCROLLBARS_MASK = 0x00000300; 976 977 /** 978 * Indicates that the view should filter touches when its window is obscured. 979 * Refer to the class comments for more information about this security feature. 980 * {@hide} 981 */ 982 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 983 984 /** 985 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 986 * that they are optional and should be skipped if the window has 987 * requested system UI flags that ignore those insets for layout. 988 */ 989 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 990 991 /** 992 * <p>This view doesn't show fading edges.</p> 993 * {@hide} 994 */ 995 static final int FADING_EDGE_NONE = 0x00000000; 996 997 /** 998 * <p>This view shows horizontal fading edges.</p> 999 * {@hide} 1000 */ 1001 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 1002 1003 /** 1004 * <p>This view shows vertical fading edges.</p> 1005 * {@hide} 1006 */ 1007 static final int FADING_EDGE_VERTICAL = 0x00002000; 1008 1009 /** 1010 * <p>Mask for use with setFlags indicating bits used for indicating which 1011 * fading edges are enabled.</p> 1012 * {@hide} 1013 */ 1014 static final int FADING_EDGE_MASK = 0x00003000; 1015 1016 /** 1017 * <p>Indicates this view can be clicked. When clickable, a View reacts 1018 * to clicks by notifying the OnClickListener.<p> 1019 * {@hide} 1020 */ 1021 static final int CLICKABLE = 0x00004000; 1022 1023 /** 1024 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1025 * {@hide} 1026 */ 1027 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1028 1029 /** 1030 * <p>Indicates that no icicle should be saved for this view.<p> 1031 * {@hide} 1032 */ 1033 static final int SAVE_DISABLED = 0x000010000; 1034 1035 /** 1036 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1037 * property.</p> 1038 * {@hide} 1039 */ 1040 static final int SAVE_DISABLED_MASK = 0x000010000; 1041 1042 /** 1043 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1044 * {@hide} 1045 */ 1046 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1047 1048 /** 1049 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1050 * {@hide} 1051 */ 1052 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1053 1054 /** @hide */ 1055 @Retention(RetentionPolicy.SOURCE) 1056 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1057 public @interface DrawingCacheQuality {} 1058 1059 /** 1060 * <p>Enables low quality mode for the drawing cache.</p> 1061 */ 1062 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1063 1064 /** 1065 * <p>Enables high quality mode for the drawing cache.</p> 1066 */ 1067 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1068 1069 /** 1070 * <p>Enables automatic quality mode for the drawing cache.</p> 1071 */ 1072 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1073 1074 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1075 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1076 }; 1077 1078 /** 1079 * <p>Mask for use with setFlags indicating bits used for the cache 1080 * quality property.</p> 1081 * {@hide} 1082 */ 1083 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1084 1085 /** 1086 * <p> 1087 * Indicates this view can be long clicked. When long clickable, a View 1088 * reacts to long clicks by notifying the OnLongClickListener or showing a 1089 * context menu. 1090 * </p> 1091 * {@hide} 1092 */ 1093 static final int LONG_CLICKABLE = 0x00200000; 1094 1095 /** 1096 * <p>Indicates that this view gets its drawable states from its direct parent 1097 * and ignores its original internal states.</p> 1098 * 1099 * @hide 1100 */ 1101 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1102 1103 /** 1104 * <p> 1105 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1106 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1107 * OnContextClickListener. 1108 * </p> 1109 * {@hide} 1110 */ 1111 static final int CONTEXT_CLICKABLE = 0x00800000; 1112 1113 1114 /** @hide */ 1115 @IntDef({ 1116 SCROLLBARS_INSIDE_OVERLAY, 1117 SCROLLBARS_INSIDE_INSET, 1118 SCROLLBARS_OUTSIDE_OVERLAY, 1119 SCROLLBARS_OUTSIDE_INSET 1120 }) 1121 @Retention(RetentionPolicy.SOURCE) 1122 public @interface ScrollBarStyle {} 1123 1124 /** 1125 * The scrollbar style to display the scrollbars inside the content area, 1126 * without increasing the padding. The scrollbars will be overlaid with 1127 * translucency on the view's content. 1128 */ 1129 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1130 1131 /** 1132 * The scrollbar style to display the scrollbars inside the padded area, 1133 * increasing the padding of the view. The scrollbars will not overlap the 1134 * content area of the view. 1135 */ 1136 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1137 1138 /** 1139 * The scrollbar style to display the scrollbars at the edge of the view, 1140 * without increasing the padding. The scrollbars will be overlaid with 1141 * translucency. 1142 */ 1143 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1144 1145 /** 1146 * The scrollbar style to display the scrollbars at the edge of the view, 1147 * increasing the padding of the view. The scrollbars will only overlap the 1148 * background, if any. 1149 */ 1150 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1151 1152 /** 1153 * Mask to check if the scrollbar style is overlay or inset. 1154 * {@hide} 1155 */ 1156 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1157 1158 /** 1159 * Mask to check if the scrollbar style is inside or outside. 1160 * {@hide} 1161 */ 1162 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1163 1164 /** 1165 * Mask for scrollbar style. 1166 * {@hide} 1167 */ 1168 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1169 1170 /** 1171 * View flag indicating that the screen should remain on while the 1172 * window containing this view is visible to the user. This effectively 1173 * takes care of automatically setting the WindowManager's 1174 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1175 */ 1176 public static final int KEEP_SCREEN_ON = 0x04000000; 1177 1178 /** 1179 * View flag indicating whether this view should have sound effects enabled 1180 * for events such as clicking and touching. 1181 */ 1182 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1183 1184 /** 1185 * View flag indicating whether this view should have haptic feedback 1186 * enabled for events such as long presses. 1187 */ 1188 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1189 1190 /** 1191 * <p>Indicates that the view hierarchy should stop saving state when 1192 * it reaches this view. If state saving is initiated immediately at 1193 * the view, it will be allowed. 1194 * {@hide} 1195 */ 1196 static final int PARENT_SAVE_DISABLED = 0x20000000; 1197 1198 /** 1199 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1200 * {@hide} 1201 */ 1202 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1203 1204 private static Paint sDebugPaint; 1205 1206 /** 1207 * <p>Indicates this view can display a tooltip on hover or long press.</p> 1208 * {@hide} 1209 */ 1210 static final int TOOLTIP = 0x40000000; 1211 1212 /** @hide */ 1213 @IntDef(flag = true, 1214 value = { 1215 FOCUSABLES_ALL, 1216 FOCUSABLES_TOUCH_MODE 1217 }) 1218 @Retention(RetentionPolicy.SOURCE) 1219 public @interface FocusableMode {} 1220 1221 /** 1222 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1223 * should add all focusable Views regardless if they are focusable in touch mode. 1224 */ 1225 public static final int FOCUSABLES_ALL = 0x00000000; 1226 1227 /** 1228 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1229 * should add only Views focusable in touch mode. 1230 */ 1231 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1232 1233 /** @hide */ 1234 @IntDef({ 1235 FOCUS_BACKWARD, 1236 FOCUS_FORWARD, 1237 FOCUS_LEFT, 1238 FOCUS_UP, 1239 FOCUS_RIGHT, 1240 FOCUS_DOWN 1241 }) 1242 @Retention(RetentionPolicy.SOURCE) 1243 public @interface FocusDirection {} 1244 1245 /** @hide */ 1246 @IntDef({ 1247 FOCUS_LEFT, 1248 FOCUS_UP, 1249 FOCUS_RIGHT, 1250 FOCUS_DOWN 1251 }) 1252 @Retention(RetentionPolicy.SOURCE) 1253 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1254 1255 /** 1256 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1257 * item. 1258 */ 1259 public static final int FOCUS_BACKWARD = 0x00000001; 1260 1261 /** 1262 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1263 * item. 1264 */ 1265 public static final int FOCUS_FORWARD = 0x00000002; 1266 1267 /** 1268 * Use with {@link #focusSearch(int)}. Move focus to the left. 1269 */ 1270 public static final int FOCUS_LEFT = 0x00000011; 1271 1272 /** 1273 * Use with {@link #focusSearch(int)}. Move focus up. 1274 */ 1275 public static final int FOCUS_UP = 0x00000021; 1276 1277 /** 1278 * Use with {@link #focusSearch(int)}. Move focus to the right. 1279 */ 1280 public static final int FOCUS_RIGHT = 0x00000042; 1281 1282 /** 1283 * Use with {@link #focusSearch(int)}. Move focus down. 1284 */ 1285 public static final int FOCUS_DOWN = 0x00000082; 1286 1287 /** 1288 * Bits of {@link #getMeasuredWidthAndState()} and 1289 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1290 */ 1291 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1292 1293 /** 1294 * Bits of {@link #getMeasuredWidthAndState()} and 1295 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1296 */ 1297 public static final int MEASURED_STATE_MASK = 0xff000000; 1298 1299 /** 1300 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1301 * for functions that combine both width and height into a single int, 1302 * such as {@link #getMeasuredState()} and the childState argument of 1303 * {@link #resolveSizeAndState(int, int, int)}. 1304 */ 1305 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1306 1307 /** 1308 * Bit of {@link #getMeasuredWidthAndState()} and 1309 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1310 * is smaller that the space the view would like to have. 1311 */ 1312 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1313 1314 /** 1315 * Base View state sets 1316 */ 1317 // Singles 1318 /** 1319 * Indicates the view has no states set. States are used with 1320 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1321 * view depending on its state. 1322 * 1323 * @see android.graphics.drawable.Drawable 1324 * @see #getDrawableState() 1325 */ 1326 protected static final int[] EMPTY_STATE_SET; 1327 /** 1328 * Indicates the view is enabled. States are used with 1329 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1330 * view depending on its state. 1331 * 1332 * @see android.graphics.drawable.Drawable 1333 * @see #getDrawableState() 1334 */ 1335 protected static final int[] ENABLED_STATE_SET; 1336 /** 1337 * Indicates the view is focused. States are used with 1338 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1339 * view depending on its state. 1340 * 1341 * @see android.graphics.drawable.Drawable 1342 * @see #getDrawableState() 1343 */ 1344 protected static final int[] FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is selected. States are used with 1347 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1348 * view depending on its state. 1349 * 1350 * @see android.graphics.drawable.Drawable 1351 * @see #getDrawableState() 1352 */ 1353 protected static final int[] SELECTED_STATE_SET; 1354 /** 1355 * Indicates the view is pressed. States are used with 1356 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1357 * view depending on its state. 1358 * 1359 * @see android.graphics.drawable.Drawable 1360 * @see #getDrawableState() 1361 */ 1362 protected static final int[] PRESSED_STATE_SET; 1363 /** 1364 * Indicates the view's window has focus. States are used with 1365 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1366 * view depending on its state. 1367 * 1368 * @see android.graphics.drawable.Drawable 1369 * @see #getDrawableState() 1370 */ 1371 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1372 // Doubles 1373 /** 1374 * Indicates the view is enabled and has the focus. 1375 * 1376 * @see #ENABLED_STATE_SET 1377 * @see #FOCUSED_STATE_SET 1378 */ 1379 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1380 /** 1381 * Indicates the view is enabled and selected. 1382 * 1383 * @see #ENABLED_STATE_SET 1384 * @see #SELECTED_STATE_SET 1385 */ 1386 protected static final int[] ENABLED_SELECTED_STATE_SET; 1387 /** 1388 * Indicates the view is enabled and that its window has focus. 1389 * 1390 * @see #ENABLED_STATE_SET 1391 * @see #WINDOW_FOCUSED_STATE_SET 1392 */ 1393 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1394 /** 1395 * Indicates the view is focused and selected. 1396 * 1397 * @see #FOCUSED_STATE_SET 1398 * @see #SELECTED_STATE_SET 1399 */ 1400 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1401 /** 1402 * Indicates the view has the focus and that its window has the focus. 1403 * 1404 * @see #FOCUSED_STATE_SET 1405 * @see #WINDOW_FOCUSED_STATE_SET 1406 */ 1407 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1408 /** 1409 * Indicates the view is selected and that its window has the focus. 1410 * 1411 * @see #SELECTED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1415 // Triples 1416 /** 1417 * Indicates the view is enabled, focused and selected. 1418 * 1419 * @see #ENABLED_STATE_SET 1420 * @see #FOCUSED_STATE_SET 1421 * @see #SELECTED_STATE_SET 1422 */ 1423 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1424 /** 1425 * Indicates the view is enabled, focused and its window has the focus. 1426 * 1427 * @see #ENABLED_STATE_SET 1428 * @see #FOCUSED_STATE_SET 1429 * @see #WINDOW_FOCUSED_STATE_SET 1430 */ 1431 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1432 /** 1433 * Indicates the view is enabled, selected and its window has the focus. 1434 * 1435 * @see #ENABLED_STATE_SET 1436 * @see #SELECTED_STATE_SET 1437 * @see #WINDOW_FOCUSED_STATE_SET 1438 */ 1439 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1440 /** 1441 * Indicates the view is focused, selected and its window has the focus. 1442 * 1443 * @see #FOCUSED_STATE_SET 1444 * @see #SELECTED_STATE_SET 1445 * @see #WINDOW_FOCUSED_STATE_SET 1446 */ 1447 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1448 /** 1449 * Indicates the view is enabled, focused, selected and its window 1450 * has the focus. 1451 * 1452 * @see #ENABLED_STATE_SET 1453 * @see #FOCUSED_STATE_SET 1454 * @see #SELECTED_STATE_SET 1455 * @see #WINDOW_FOCUSED_STATE_SET 1456 */ 1457 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1458 /** 1459 * Indicates the view is pressed and its window has the focus. 1460 * 1461 * @see #PRESSED_STATE_SET 1462 * @see #WINDOW_FOCUSED_STATE_SET 1463 */ 1464 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1465 /** 1466 * Indicates the view is pressed and selected. 1467 * 1468 * @see #PRESSED_STATE_SET 1469 * @see #SELECTED_STATE_SET 1470 */ 1471 protected static final int[] PRESSED_SELECTED_STATE_SET; 1472 /** 1473 * Indicates the view is pressed, selected and its window has the focus. 1474 * 1475 * @see #PRESSED_STATE_SET 1476 * @see #SELECTED_STATE_SET 1477 * @see #WINDOW_FOCUSED_STATE_SET 1478 */ 1479 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1480 /** 1481 * Indicates the view is pressed and focused. 1482 * 1483 * @see #PRESSED_STATE_SET 1484 * @see #FOCUSED_STATE_SET 1485 */ 1486 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1487 /** 1488 * Indicates the view is pressed, focused and its window has the focus. 1489 * 1490 * @see #PRESSED_STATE_SET 1491 * @see #FOCUSED_STATE_SET 1492 * @see #WINDOW_FOCUSED_STATE_SET 1493 */ 1494 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1495 /** 1496 * Indicates the view is pressed, focused and selected. 1497 * 1498 * @see #PRESSED_STATE_SET 1499 * @see #SELECTED_STATE_SET 1500 * @see #FOCUSED_STATE_SET 1501 */ 1502 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1503 /** 1504 * Indicates the view is pressed, focused, selected and its window has the focus. 1505 * 1506 * @see #PRESSED_STATE_SET 1507 * @see #FOCUSED_STATE_SET 1508 * @see #SELECTED_STATE_SET 1509 * @see #WINDOW_FOCUSED_STATE_SET 1510 */ 1511 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1512 /** 1513 * Indicates the view is pressed and enabled. 1514 * 1515 * @see #PRESSED_STATE_SET 1516 * @see #ENABLED_STATE_SET 1517 */ 1518 protected static final int[] PRESSED_ENABLED_STATE_SET; 1519 /** 1520 * Indicates the view is pressed, enabled and its window has the focus. 1521 * 1522 * @see #PRESSED_STATE_SET 1523 * @see #ENABLED_STATE_SET 1524 * @see #WINDOW_FOCUSED_STATE_SET 1525 */ 1526 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1527 /** 1528 * Indicates the view is pressed, enabled and selected. 1529 * 1530 * @see #PRESSED_STATE_SET 1531 * @see #ENABLED_STATE_SET 1532 * @see #SELECTED_STATE_SET 1533 */ 1534 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1535 /** 1536 * Indicates the view is pressed, enabled, selected and its window has the 1537 * focus. 1538 * 1539 * @see #PRESSED_STATE_SET 1540 * @see #ENABLED_STATE_SET 1541 * @see #SELECTED_STATE_SET 1542 * @see #WINDOW_FOCUSED_STATE_SET 1543 */ 1544 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1545 /** 1546 * Indicates the view is pressed, enabled and focused. 1547 * 1548 * @see #PRESSED_STATE_SET 1549 * @see #ENABLED_STATE_SET 1550 * @see #FOCUSED_STATE_SET 1551 */ 1552 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1553 /** 1554 * Indicates the view is pressed, enabled, focused and its window has the 1555 * focus. 1556 * 1557 * @see #PRESSED_STATE_SET 1558 * @see #ENABLED_STATE_SET 1559 * @see #FOCUSED_STATE_SET 1560 * @see #WINDOW_FOCUSED_STATE_SET 1561 */ 1562 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1563 /** 1564 * Indicates the view is pressed, enabled, focused and selected. 1565 * 1566 * @see #PRESSED_STATE_SET 1567 * @see #ENABLED_STATE_SET 1568 * @see #SELECTED_STATE_SET 1569 * @see #FOCUSED_STATE_SET 1570 */ 1571 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1572 /** 1573 * Indicates the view is pressed, enabled, focused, selected and its window 1574 * has the focus. 1575 * 1576 * @see #PRESSED_STATE_SET 1577 * @see #ENABLED_STATE_SET 1578 * @see #SELECTED_STATE_SET 1579 * @see #FOCUSED_STATE_SET 1580 * @see #WINDOW_FOCUSED_STATE_SET 1581 */ 1582 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1583 1584 static { 1585 EMPTY_STATE_SET = StateSet.get(0); 1586 1587 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1588 1589 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1590 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1591 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1592 1593 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1594 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1595 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1596 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1597 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1598 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1599 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1600 | StateSet.VIEW_STATE_FOCUSED); 1601 1602 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1603 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1604 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1605 ENABLED_SELECTED_STATE_SET = StateSet.get( 1606 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1607 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1608 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1609 | StateSet.VIEW_STATE_ENABLED); 1610 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1611 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1612 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1613 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1614 | StateSet.VIEW_STATE_ENABLED); 1615 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1616 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1617 | StateSet.VIEW_STATE_ENABLED); 1618 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1619 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1620 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1621 1622 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1623 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1624 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1625 PRESSED_SELECTED_STATE_SET = StateSet.get( 1626 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1627 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1628 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1629 | StateSet.VIEW_STATE_PRESSED); 1630 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1631 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1632 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1633 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1634 | StateSet.VIEW_STATE_PRESSED); 1635 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1636 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1637 | StateSet.VIEW_STATE_PRESSED); 1638 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1639 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1640 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1641 PRESSED_ENABLED_STATE_SET = StateSet.get( 1642 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1643 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1644 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1645 | StateSet.VIEW_STATE_PRESSED); 1646 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1647 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1648 | StateSet.VIEW_STATE_PRESSED); 1649 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1650 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1651 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1652 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1653 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1654 | StateSet.VIEW_STATE_PRESSED); 1655 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1656 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1657 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1658 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1659 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1660 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1661 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1662 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1663 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1664 | StateSet.VIEW_STATE_PRESSED); 1665 } 1666 1667 /** 1668 * Accessibility event types that are dispatched for text population. 1669 */ 1670 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1671 AccessibilityEvent.TYPE_VIEW_CLICKED 1672 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1673 | AccessibilityEvent.TYPE_VIEW_SELECTED 1674 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1675 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1676 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1677 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1678 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1679 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1680 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1681 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1682 1683 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255); 1684 1685 static final int DEBUG_CORNERS_SIZE_DIP = 8; 1686 1687 /** 1688 * Temporary Rect currently for use in setBackground(). This will probably 1689 * be extended in the future to hold our own class with more than just 1690 * a Rect. :) 1691 */ 1692 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1693 1694 /** 1695 * Map used to store views' tags. 1696 */ 1697 private SparseArray<Object> mKeyedTags; 1698 1699 /** 1700 * The next available accessibility id. 1701 */ 1702 private static int sNextAccessibilityViewId; 1703 1704 /** 1705 * The animation currently associated with this view. 1706 * @hide 1707 */ 1708 protected Animation mCurrentAnimation = null; 1709 1710 /** 1711 * Width as measured during measure pass. 1712 * {@hide} 1713 */ 1714 @ViewDebug.ExportedProperty(category = "measurement") 1715 int mMeasuredWidth; 1716 1717 /** 1718 * Height as measured during measure pass. 1719 * {@hide} 1720 */ 1721 @ViewDebug.ExportedProperty(category = "measurement") 1722 int mMeasuredHeight; 1723 1724 /** 1725 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1726 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1727 * its display list. This flag, used only when hw accelerated, allows us to clear the 1728 * flag while retaining this information until it's needed (at getDisplayList() time and 1729 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1730 * 1731 * {@hide} 1732 */ 1733 boolean mRecreateDisplayList = false; 1734 1735 /** 1736 * The view's identifier. 1737 * {@hide} 1738 * 1739 * @see #setId(int) 1740 * @see #getId() 1741 */ 1742 @IdRes 1743 @ViewDebug.ExportedProperty(resolveId = true) 1744 int mID = NO_ID; 1745 1746 /** 1747 * The stable ID of this view for accessibility purposes. 1748 */ 1749 int mAccessibilityViewId = NO_ID; 1750 1751 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1752 1753 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1754 1755 /** 1756 * The view's tag. 1757 * {@hide} 1758 * 1759 * @see #setTag(Object) 1760 * @see #getTag() 1761 */ 1762 protected Object mTag = null; 1763 1764 // for mPrivateFlags: 1765 /** {@hide} */ 1766 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1767 /** {@hide} */ 1768 static final int PFLAG_FOCUSED = 0x00000002; 1769 /** {@hide} */ 1770 static final int PFLAG_SELECTED = 0x00000004; 1771 /** {@hide} */ 1772 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1773 /** {@hide} */ 1774 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1775 /** {@hide} */ 1776 static final int PFLAG_DRAWN = 0x00000020; 1777 /** 1778 * When this flag is set, this view is running an animation on behalf of its 1779 * children and should therefore not cancel invalidate requests, even if they 1780 * lie outside of this view's bounds. 1781 * 1782 * {@hide} 1783 */ 1784 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1785 /** {@hide} */ 1786 static final int PFLAG_SKIP_DRAW = 0x00000080; 1787 /** {@hide} */ 1788 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1789 /** {@hide} */ 1790 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1791 /** {@hide} */ 1792 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1793 /** {@hide} */ 1794 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1795 /** {@hide} */ 1796 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1797 1798 private static final int PFLAG_PRESSED = 0x00004000; 1799 1800 /** {@hide} */ 1801 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1802 /** 1803 * Flag used to indicate that this view should be drawn once more (and only once 1804 * more) after its animation has completed. 1805 * {@hide} 1806 */ 1807 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1808 1809 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1810 1811 /** 1812 * Indicates that the View returned true when onSetAlpha() was called and that 1813 * the alpha must be restored. 1814 * {@hide} 1815 */ 1816 static final int PFLAG_ALPHA_SET = 0x00040000; 1817 1818 /** 1819 * Set by {@link #setScrollContainer(boolean)}. 1820 */ 1821 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1822 1823 /** 1824 * Set by {@link #setScrollContainer(boolean)}. 1825 */ 1826 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1827 1828 /** 1829 * View flag indicating whether this view was invalidated (fully or partially.) 1830 * 1831 * @hide 1832 */ 1833 static final int PFLAG_DIRTY = 0x00200000; 1834 1835 /** 1836 * View flag indicating whether this view was invalidated by an opaque 1837 * invalidate request. 1838 * 1839 * @hide 1840 */ 1841 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1842 1843 /** 1844 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1845 * 1846 * @hide 1847 */ 1848 static final int PFLAG_DIRTY_MASK = 0x00600000; 1849 1850 /** 1851 * Indicates whether the background is opaque. 1852 * 1853 * @hide 1854 */ 1855 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1856 1857 /** 1858 * Indicates whether the scrollbars are opaque. 1859 * 1860 * @hide 1861 */ 1862 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1863 1864 /** 1865 * Indicates whether the view is opaque. 1866 * 1867 * @hide 1868 */ 1869 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1870 1871 /** 1872 * Indicates a prepressed state; 1873 * the short time between ACTION_DOWN and recognizing 1874 * a 'real' press. Prepressed is used to recognize quick taps 1875 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1876 * 1877 * @hide 1878 */ 1879 private static final int PFLAG_PREPRESSED = 0x02000000; 1880 1881 /** 1882 * Indicates whether the view is temporarily detached. 1883 * 1884 * @hide 1885 */ 1886 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1887 1888 /** 1889 * Indicates that we should awaken scroll bars once attached 1890 * 1891 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1892 * during window attachment and it is no longer needed. Feel free to repurpose it. 1893 * 1894 * @hide 1895 */ 1896 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1897 1898 /** 1899 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1900 * @hide 1901 */ 1902 private static final int PFLAG_HOVERED = 0x10000000; 1903 1904 /** 1905 * no longer needed, should be reused 1906 */ 1907 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1908 1909 /** {@hide} */ 1910 static final int PFLAG_ACTIVATED = 0x40000000; 1911 1912 /** 1913 * Indicates that this view was specifically invalidated, not just dirtied because some 1914 * child view was invalidated. The flag is used to determine when we need to recreate 1915 * a view's display list (as opposed to just returning a reference to its existing 1916 * display list). 1917 * 1918 * @hide 1919 */ 1920 static final int PFLAG_INVALIDATED = 0x80000000; 1921 1922 /** 1923 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1924 * 1925 * |-------|-------|-------|-------| 1926 * 1 PFLAG2_DRAG_CAN_ACCEPT 1927 * 1 PFLAG2_DRAG_HOVERED 1928 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1929 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1930 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1931 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1932 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1933 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1934 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1935 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1936 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1937 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1938 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1939 * 111 PFLAG2_TEXT_DIRECTION_MASK 1940 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1941 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1942 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1943 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1944 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1945 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1946 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1947 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1948 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1949 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1950 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1951 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1952 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1953 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1954 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1955 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1956 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1957 * 1 PFLAG2_VIEW_QUICK_REJECTED 1958 * 1 PFLAG2_PADDING_RESOLVED 1959 * 1 PFLAG2_DRAWABLE_RESOLVED 1960 * 1 PFLAG2_HAS_TRANSIENT_STATE 1961 * |-------|-------|-------|-------| 1962 */ 1963 1964 /** 1965 * Indicates that this view has reported that it can accept the current drag's content. 1966 * Cleared when the drag operation concludes. 1967 * @hide 1968 */ 1969 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1970 1971 /** 1972 * Indicates that this view is currently directly under the drag location in a 1973 * drag-and-drop operation involving content that it can accept. Cleared when 1974 * the drag exits the view, or when the drag operation concludes. 1975 * @hide 1976 */ 1977 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1978 1979 /** @hide */ 1980 @IntDef({ 1981 LAYOUT_DIRECTION_LTR, 1982 LAYOUT_DIRECTION_RTL, 1983 LAYOUT_DIRECTION_INHERIT, 1984 LAYOUT_DIRECTION_LOCALE 1985 }) 1986 @Retention(RetentionPolicy.SOURCE) 1987 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1988 public @interface LayoutDir {} 1989 1990 /** @hide */ 1991 @IntDef({ 1992 LAYOUT_DIRECTION_LTR, 1993 LAYOUT_DIRECTION_RTL 1994 }) 1995 @Retention(RetentionPolicy.SOURCE) 1996 public @interface ResolvedLayoutDir {} 1997 1998 /** 1999 * A flag to indicate that the layout direction of this view has not been defined yet. 2000 * @hide 2001 */ 2002 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 2003 2004 /** 2005 * Horizontal layout direction of this view is from Left to Right. 2006 * Use with {@link #setLayoutDirection}. 2007 */ 2008 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 2009 2010 /** 2011 * Horizontal layout direction of this view is from Right to Left. 2012 * Use with {@link #setLayoutDirection}. 2013 */ 2014 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 2015 2016 /** 2017 * Horizontal layout direction of this view is inherited from its parent. 2018 * Use with {@link #setLayoutDirection}. 2019 */ 2020 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 2021 2022 /** 2023 * Horizontal layout direction of this view is from deduced from the default language 2024 * script for the locale. Use with {@link #setLayoutDirection}. 2025 */ 2026 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 2027 2028 /** 2029 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2030 * @hide 2031 */ 2032 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2033 2034 /** 2035 * Mask for use with private flags indicating bits used for horizontal layout direction. 2036 * @hide 2037 */ 2038 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2039 2040 /** 2041 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2042 * right-to-left direction. 2043 * @hide 2044 */ 2045 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2046 2047 /** 2048 * Indicates whether the view horizontal layout direction has been resolved. 2049 * @hide 2050 */ 2051 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2052 2053 /** 2054 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2055 * @hide 2056 */ 2057 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2058 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2059 2060 /* 2061 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2062 * flag value. 2063 * @hide 2064 */ 2065 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2066 LAYOUT_DIRECTION_LTR, 2067 LAYOUT_DIRECTION_RTL, 2068 LAYOUT_DIRECTION_INHERIT, 2069 LAYOUT_DIRECTION_LOCALE 2070 }; 2071 2072 /** 2073 * Default horizontal layout direction. 2074 */ 2075 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2076 2077 /** 2078 * Default horizontal layout direction. 2079 * @hide 2080 */ 2081 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2082 2083 /** 2084 * Text direction is inherited through {@link ViewGroup} 2085 */ 2086 public static final int TEXT_DIRECTION_INHERIT = 0; 2087 2088 /** 2089 * Text direction is using "first strong algorithm". The first strong directional character 2090 * determines the paragraph direction. If there is no strong directional character, the 2091 * paragraph direction is the view's resolved layout direction. 2092 */ 2093 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2094 2095 /** 2096 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2097 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2098 * If there are neither, the paragraph direction is the view's resolved layout direction. 2099 */ 2100 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2101 2102 /** 2103 * Text direction is forced to LTR. 2104 */ 2105 public static final int TEXT_DIRECTION_LTR = 3; 2106 2107 /** 2108 * Text direction is forced to RTL. 2109 */ 2110 public static final int TEXT_DIRECTION_RTL = 4; 2111 2112 /** 2113 * Text direction is coming from the system Locale. 2114 */ 2115 public static final int TEXT_DIRECTION_LOCALE = 5; 2116 2117 /** 2118 * Text direction is using "first strong algorithm". The first strong directional character 2119 * determines the paragraph direction. If there is no strong directional character, the 2120 * paragraph direction is LTR. 2121 */ 2122 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2123 2124 /** 2125 * Text direction is using "first strong algorithm". The first strong directional character 2126 * determines the paragraph direction. If there is no strong directional character, the 2127 * paragraph direction is RTL. 2128 */ 2129 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2130 2131 /** 2132 * Default text direction is inherited 2133 */ 2134 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2135 2136 /** 2137 * Default resolved text direction 2138 * @hide 2139 */ 2140 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2141 2142 /** 2143 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2147 2148 /** 2149 * Mask for use with private flags indicating bits used for text direction. 2150 * @hide 2151 */ 2152 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2153 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2154 2155 /** 2156 * Array of text direction flags for mapping attribute "textDirection" to correct 2157 * flag value. 2158 * @hide 2159 */ 2160 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2161 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2162 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2163 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2164 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2165 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2166 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2167 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2168 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2169 }; 2170 2171 /** 2172 * Indicates whether the view text direction has been resolved. 2173 * @hide 2174 */ 2175 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2176 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2177 2178 /** 2179 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2180 * @hide 2181 */ 2182 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2183 2184 /** 2185 * Mask for use with private flags indicating bits used for resolved text direction. 2186 * @hide 2187 */ 2188 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2189 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2190 2191 /** 2192 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2193 * @hide 2194 */ 2195 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2196 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2197 2198 /** @hide */ 2199 @IntDef({ 2200 TEXT_ALIGNMENT_INHERIT, 2201 TEXT_ALIGNMENT_GRAVITY, 2202 TEXT_ALIGNMENT_CENTER, 2203 TEXT_ALIGNMENT_TEXT_START, 2204 TEXT_ALIGNMENT_TEXT_END, 2205 TEXT_ALIGNMENT_VIEW_START, 2206 TEXT_ALIGNMENT_VIEW_END 2207 }) 2208 @Retention(RetentionPolicy.SOURCE) 2209 public @interface TextAlignment {} 2210 2211 /** 2212 * Default text alignment. The text alignment of this View is inherited from its parent. 2213 * Use with {@link #setTextAlignment(int)} 2214 */ 2215 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2216 2217 /** 2218 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2219 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2220 * 2221 * Use with {@link #setTextAlignment(int)} 2222 */ 2223 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2224 2225 /** 2226 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2227 * 2228 * Use with {@link #setTextAlignment(int)} 2229 */ 2230 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2231 2232 /** 2233 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2234 * 2235 * Use with {@link #setTextAlignment(int)} 2236 */ 2237 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2238 2239 /** 2240 * Center the paragraph, e.g. ALIGN_CENTER. 2241 * 2242 * Use with {@link #setTextAlignment(int)} 2243 */ 2244 public static final int TEXT_ALIGNMENT_CENTER = 4; 2245 2246 /** 2247 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2248 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2249 * 2250 * Use with {@link #setTextAlignment(int)} 2251 */ 2252 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2253 2254 /** 2255 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2256 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2257 * 2258 * Use with {@link #setTextAlignment(int)} 2259 */ 2260 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2261 2262 /** 2263 * Default text alignment is inherited 2264 */ 2265 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2266 2267 /** 2268 * Default resolved text alignment 2269 * @hide 2270 */ 2271 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2272 2273 /** 2274 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2275 * @hide 2276 */ 2277 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2278 2279 /** 2280 * Mask for use with private flags indicating bits used for text alignment. 2281 * @hide 2282 */ 2283 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2284 2285 /** 2286 * Array of text direction flags for mapping attribute "textAlignment" to correct 2287 * flag value. 2288 * @hide 2289 */ 2290 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2291 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2292 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2293 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2294 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2295 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2296 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2297 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2298 }; 2299 2300 /** 2301 * Indicates whether the view text alignment has been resolved. 2302 * @hide 2303 */ 2304 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2305 2306 /** 2307 * Bit shift to get the resolved text alignment. 2308 * @hide 2309 */ 2310 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2311 2312 /** 2313 * Mask for use with private flags indicating bits used for text alignment. 2314 * @hide 2315 */ 2316 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2317 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2318 2319 /** 2320 * Indicates whether if the view text alignment has been resolved to gravity 2321 */ 2322 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2323 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2324 2325 // Accessiblity constants for mPrivateFlags2 2326 2327 /** 2328 * Shift for the bits in {@link #mPrivateFlags2} related to the 2329 * "importantForAccessibility" attribute. 2330 */ 2331 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2332 2333 /** 2334 * Automatically determine whether a view is important for accessibility. 2335 */ 2336 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2337 2338 /** 2339 * The view is important for accessibility. 2340 */ 2341 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2342 2343 /** 2344 * The view is not important for accessibility. 2345 */ 2346 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2347 2348 /** 2349 * The view is not important for accessibility, nor are any of its 2350 * descendant views. 2351 */ 2352 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2353 2354 /** 2355 * The default whether the view is important for accessibility. 2356 */ 2357 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2358 2359 /** 2360 * Mask for obtaining the bits which specify how to determine 2361 * whether a view is important for accessibility. 2362 */ 2363 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2364 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2365 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2366 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2367 2368 /** 2369 * Shift for the bits in {@link #mPrivateFlags2} related to the 2370 * "accessibilityLiveRegion" attribute. 2371 */ 2372 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2373 2374 /** 2375 * Live region mode specifying that accessibility services should not 2376 * automatically announce changes to this view. This is the default live 2377 * region mode for most views. 2378 * <p> 2379 * Use with {@link #setAccessibilityLiveRegion(int)}. 2380 */ 2381 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2382 2383 /** 2384 * Live region mode specifying that accessibility services should announce 2385 * changes to this view. 2386 * <p> 2387 * Use with {@link #setAccessibilityLiveRegion(int)}. 2388 */ 2389 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2390 2391 /** 2392 * Live region mode specifying that accessibility services should interrupt 2393 * ongoing speech to immediately announce changes to this view. 2394 * <p> 2395 * Use with {@link #setAccessibilityLiveRegion(int)}. 2396 */ 2397 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2398 2399 /** 2400 * The default whether the view is important for accessibility. 2401 */ 2402 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2403 2404 /** 2405 * Mask for obtaining the bits which specify a view's accessibility live 2406 * region mode. 2407 */ 2408 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2409 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2410 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2411 2412 /** 2413 * Flag indicating whether a view has accessibility focus. 2414 */ 2415 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2416 2417 /** 2418 * Flag whether the accessibility state of the subtree rooted at this view changed. 2419 */ 2420 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2421 2422 /** 2423 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2424 * is used to check whether later changes to the view's transform should invalidate the 2425 * view to force the quickReject test to run again. 2426 */ 2427 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2428 2429 /** 2430 * Flag indicating that start/end padding has been resolved into left/right padding 2431 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2432 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2433 * during measurement. In some special cases this is required such as when an adapter-based 2434 * view measures prospective children without attaching them to a window. 2435 */ 2436 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2437 2438 /** 2439 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2440 */ 2441 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2442 2443 /** 2444 * Indicates that the view is tracking some sort of transient state 2445 * that the app should not need to be aware of, but that the framework 2446 * should take special care to preserve. 2447 */ 2448 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2449 2450 /** 2451 * Group of bits indicating that RTL properties resolution is done. 2452 */ 2453 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2454 PFLAG2_TEXT_DIRECTION_RESOLVED | 2455 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2456 PFLAG2_PADDING_RESOLVED | 2457 PFLAG2_DRAWABLE_RESOLVED; 2458 2459 // There are a couple of flags left in mPrivateFlags2 2460 2461 /* End of masks for mPrivateFlags2 */ 2462 2463 /** 2464 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2465 * 2466 * |-------|-------|-------|-------| 2467 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2468 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2469 * 1 PFLAG3_IS_LAID_OUT 2470 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2471 * 1 PFLAG3_CALLED_SUPER 2472 * 1 PFLAG3_APPLYING_INSETS 2473 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2474 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2475 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2476 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2477 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2478 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2479 * 1 PFLAG3_SCROLL_INDICATOR_START 2480 * 1 PFLAG3_SCROLL_INDICATOR_END 2481 * 1 PFLAG3_ASSIST_BLOCKED 2482 * 1 PFLAG3_CLUSTER 2483 * x * NO LONGER NEEDED, SHOULD BE REUSED * 2484 * 1 PFLAG3_FINGER_DOWN 2485 * 1 PFLAG3_FOCUSED_BY_DEFAULT 2486 * xxxx * NO LONGER NEEDED, SHOULD BE REUSED * 2487 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2488 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2489 * 1 PFLAG3_TEMPORARY_DETACH 2490 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2491 * |-------|-------|-------|-------| 2492 */ 2493 2494 /** 2495 * Flag indicating that view has a transform animation set on it. This is used to track whether 2496 * an animation is cleared between successive frames, in order to tell the associated 2497 * DisplayList to clear its animation matrix. 2498 */ 2499 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2500 2501 /** 2502 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2503 * animation is cleared between successive frames, in order to tell the associated 2504 * DisplayList to restore its alpha value. 2505 */ 2506 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2507 2508 /** 2509 * Flag indicating that the view has been through at least one layout since it 2510 * was last attached to a window. 2511 */ 2512 static final int PFLAG3_IS_LAID_OUT = 0x4; 2513 2514 /** 2515 * Flag indicating that a call to measure() was skipped and should be done 2516 * instead when layout() is invoked. 2517 */ 2518 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2519 2520 /** 2521 * Flag indicating that an overridden method correctly called down to 2522 * the superclass implementation as required by the API spec. 2523 */ 2524 static final int PFLAG3_CALLED_SUPER = 0x10; 2525 2526 /** 2527 * Flag indicating that we're in the process of applying window insets. 2528 */ 2529 static final int PFLAG3_APPLYING_INSETS = 0x20; 2530 2531 /** 2532 * Flag indicating that we're in the process of fitting system windows using the old method. 2533 */ 2534 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2535 2536 /** 2537 * Flag indicating that nested scrolling is enabled for this view. 2538 * The view will optionally cooperate with views up its parent chain to allow for 2539 * integrated nested scrolling along the same axis. 2540 */ 2541 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2542 2543 /** 2544 * Flag indicating that the bottom scroll indicator should be displayed 2545 * when this view can scroll up. 2546 */ 2547 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2548 2549 /** 2550 * Flag indicating that the bottom scroll indicator should be displayed 2551 * when this view can scroll down. 2552 */ 2553 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2554 2555 /** 2556 * Flag indicating that the left scroll indicator should be displayed 2557 * when this view can scroll left. 2558 */ 2559 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2560 2561 /** 2562 * Flag indicating that the right scroll indicator should be displayed 2563 * when this view can scroll right. 2564 */ 2565 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2566 2567 /** 2568 * Flag indicating that the start scroll indicator should be displayed 2569 * when this view can scroll in the start direction. 2570 */ 2571 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2572 2573 /** 2574 * Flag indicating that the end scroll indicator should be displayed 2575 * when this view can scroll in the end direction. 2576 */ 2577 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2578 2579 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2580 2581 static final int SCROLL_INDICATORS_NONE = 0x0000; 2582 2583 /** 2584 * Mask for use with setFlags indicating bits used for indicating which 2585 * scroll indicators are enabled. 2586 */ 2587 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2588 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2589 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2590 | PFLAG3_SCROLL_INDICATOR_END; 2591 2592 /** 2593 * Left-shift required to translate between public scroll indicator flags 2594 * and internal PFLAGS3 flags. When used as a right-shift, translates 2595 * PFLAGS3 flags to public flags. 2596 */ 2597 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2598 2599 /** @hide */ 2600 @Retention(RetentionPolicy.SOURCE) 2601 @IntDef(flag = true, 2602 value = { 2603 SCROLL_INDICATOR_TOP, 2604 SCROLL_INDICATOR_BOTTOM, 2605 SCROLL_INDICATOR_LEFT, 2606 SCROLL_INDICATOR_RIGHT, 2607 SCROLL_INDICATOR_START, 2608 SCROLL_INDICATOR_END, 2609 }) 2610 public @interface ScrollIndicators {} 2611 2612 /** 2613 * Scroll indicator direction for the top edge of the view. 2614 * 2615 * @see #setScrollIndicators(int) 2616 * @see #setScrollIndicators(int, int) 2617 * @see #getScrollIndicators() 2618 */ 2619 public static final int SCROLL_INDICATOR_TOP = 2620 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2621 2622 /** 2623 * Scroll indicator direction for the bottom edge of the view. 2624 * 2625 * @see #setScrollIndicators(int) 2626 * @see #setScrollIndicators(int, int) 2627 * @see #getScrollIndicators() 2628 */ 2629 public static final int SCROLL_INDICATOR_BOTTOM = 2630 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2631 2632 /** 2633 * Scroll indicator direction for the left edge of the view. 2634 * 2635 * @see #setScrollIndicators(int) 2636 * @see #setScrollIndicators(int, int) 2637 * @see #getScrollIndicators() 2638 */ 2639 public static final int SCROLL_INDICATOR_LEFT = 2640 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2641 2642 /** 2643 * Scroll indicator direction for the right edge of the view. 2644 * 2645 * @see #setScrollIndicators(int) 2646 * @see #setScrollIndicators(int, int) 2647 * @see #getScrollIndicators() 2648 */ 2649 public static final int SCROLL_INDICATOR_RIGHT = 2650 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2651 2652 /** 2653 * Scroll indicator direction for the starting edge of the view. 2654 * <p> 2655 * Resolved according to the view's layout direction, see 2656 * {@link #getLayoutDirection()} for more information. 2657 * 2658 * @see #setScrollIndicators(int) 2659 * @see #setScrollIndicators(int, int) 2660 * @see #getScrollIndicators() 2661 */ 2662 public static final int SCROLL_INDICATOR_START = 2663 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2664 2665 /** 2666 * Scroll indicator direction for the ending edge of the view. 2667 * <p> 2668 * Resolved according to the view's layout direction, see 2669 * {@link #getLayoutDirection()} for more information. 2670 * 2671 * @see #setScrollIndicators(int) 2672 * @see #setScrollIndicators(int, int) 2673 * @see #getScrollIndicators() 2674 */ 2675 public static final int SCROLL_INDICATOR_END = 2676 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2677 2678 /** 2679 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2680 * into this view.<p> 2681 */ 2682 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2683 2684 /** 2685 * Flag indicating that the view is a root of a keyboard navigation cluster. 2686 * 2687 * @see #isKeyboardNavigationCluster() 2688 * @see #setKeyboardNavigationCluster(boolean) 2689 */ 2690 private static final int PFLAG3_CLUSTER = 0x8000; 2691 2692 /** 2693 * Indicates that the user is currently touching the screen. 2694 * Currently used for the tooltip positioning only. 2695 */ 2696 private static final int PFLAG3_FINGER_DOWN = 0x20000; 2697 2698 /** 2699 * Flag indicating that this view is the default-focus view. 2700 * 2701 * @see #isFocusedByDefault() 2702 * @see #setFocusedByDefault(boolean) 2703 */ 2704 private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000; 2705 2706 /** 2707 * Whether this view has rendered elements that overlap (see {@link 2708 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 2709 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 2710 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 2711 * determined by whatever {@link #hasOverlappingRendering()} returns. 2712 */ 2713 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 2714 2715 /** 2716 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 2717 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 2718 */ 2719 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 2720 2721 /** 2722 * Flag indicating that the view is temporarily detached from the parent view. 2723 * 2724 * @see #onStartTemporaryDetach() 2725 * @see #onFinishTemporaryDetach() 2726 */ 2727 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 2728 2729 /** 2730 * Flag indicating that the view does not wish to be revealed within its parent 2731 * hierarchy when it gains focus. Expressed in the negative since the historical 2732 * default behavior is to reveal on focus; this flag suppresses that behavior. 2733 * 2734 * @see #setRevealOnFocusHint(boolean) 2735 * @see #getRevealOnFocusHint() 2736 */ 2737 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 2738 2739 /* End of masks for mPrivateFlags3 */ 2740 2741 /** 2742 * Always allow a user to over-scroll this view, provided it is a 2743 * view that can scroll. 2744 * 2745 * @see #getOverScrollMode() 2746 * @see #setOverScrollMode(int) 2747 */ 2748 public static final int OVER_SCROLL_ALWAYS = 0; 2749 2750 /** 2751 * Allow a user to over-scroll this view only if the content is large 2752 * enough to meaningfully scroll, provided it is a view that can scroll. 2753 * 2754 * @see #getOverScrollMode() 2755 * @see #setOverScrollMode(int) 2756 */ 2757 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2758 2759 /** 2760 * Never allow a user to over-scroll this view. 2761 * 2762 * @see #getOverScrollMode() 2763 * @see #setOverScrollMode(int) 2764 */ 2765 public static final int OVER_SCROLL_NEVER = 2; 2766 2767 /** 2768 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2769 * requested the system UI (status bar) to be visible (the default). 2770 * 2771 * @see #setSystemUiVisibility(int) 2772 */ 2773 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2774 2775 /** 2776 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2777 * system UI to enter an unobtrusive "low profile" mode. 2778 * 2779 * <p>This is for use in games, book readers, video players, or any other 2780 * "immersive" application where the usual system chrome is deemed too distracting. 2781 * 2782 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2783 * 2784 * @see #setSystemUiVisibility(int) 2785 */ 2786 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2787 2788 /** 2789 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2790 * system navigation be temporarily hidden. 2791 * 2792 * <p>This is an even less obtrusive state than that called for by 2793 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2794 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2795 * those to disappear. This is useful (in conjunction with the 2796 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2797 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2798 * window flags) for displaying content using every last pixel on the display. 2799 * 2800 * <p>There is a limitation: because navigation controls are so important, the least user 2801 * interaction will cause them to reappear immediately. When this happens, both 2802 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2803 * so that both elements reappear at the same time. 2804 * 2805 * @see #setSystemUiVisibility(int) 2806 */ 2807 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2808 2809 /** 2810 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2811 * into the normal fullscreen mode so that its content can take over the screen 2812 * while still allowing the user to interact with the application. 2813 * 2814 * <p>This has the same visual effect as 2815 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2816 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2817 * meaning that non-critical screen decorations (such as the status bar) will be 2818 * hidden while the user is in the View's window, focusing the experience on 2819 * that content. Unlike the window flag, if you are using ActionBar in 2820 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2821 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2822 * hide the action bar. 2823 * 2824 * <p>This approach to going fullscreen is best used over the window flag when 2825 * it is a transient state -- that is, the application does this at certain 2826 * points in its user interaction where it wants to allow the user to focus 2827 * on content, but not as a continuous state. For situations where the application 2828 * would like to simply stay full screen the entire time (such as a game that 2829 * wants to take over the screen), the 2830 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2831 * is usually a better approach. The state set here will be removed by the system 2832 * in various situations (such as the user moving to another application) like 2833 * the other system UI states. 2834 * 2835 * <p>When using this flag, the application should provide some easy facility 2836 * for the user to go out of it. A common example would be in an e-book 2837 * reader, where tapping on the screen brings back whatever screen and UI 2838 * decorations that had been hidden while the user was immersed in reading 2839 * the book. 2840 * 2841 * @see #setSystemUiVisibility(int) 2842 */ 2843 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2844 2845 /** 2846 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2847 * flags, we would like a stable view of the content insets given to 2848 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2849 * will always represent the worst case that the application can expect 2850 * as a continuous state. In the stock Android UI this is the space for 2851 * the system bar, nav bar, and status bar, but not more transient elements 2852 * such as an input method. 2853 * 2854 * The stable layout your UI sees is based on the system UI modes you can 2855 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2856 * then you will get a stable layout for changes of the 2857 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2858 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2859 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2860 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2861 * with a stable layout. (Note that you should avoid using 2862 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2863 * 2864 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2865 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2866 * then a hidden status bar will be considered a "stable" state for purposes 2867 * here. This allows your UI to continually hide the status bar, while still 2868 * using the system UI flags to hide the action bar while still retaining 2869 * a stable layout. Note that changing the window fullscreen flag will never 2870 * provide a stable layout for a clean transition. 2871 * 2872 * <p>If you are using ActionBar in 2873 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2874 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2875 * insets it adds to those given to the application. 2876 */ 2877 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2878 2879 /** 2880 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2881 * to be laid out as if it has requested 2882 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2883 * allows it to avoid artifacts when switching in and out of that mode, at 2884 * the expense that some of its user interface may be covered by screen 2885 * decorations when they are shown. You can perform layout of your inner 2886 * UI elements to account for the navigation system UI through the 2887 * {@link #fitSystemWindows(Rect)} method. 2888 */ 2889 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2890 2891 /** 2892 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2893 * to be laid out as if it has requested 2894 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2895 * allows it to avoid artifacts when switching in and out of that mode, at 2896 * the expense that some of its user interface may be covered by screen 2897 * decorations when they are shown. You can perform layout of your inner 2898 * UI elements to account for non-fullscreen system UI through the 2899 * {@link #fitSystemWindows(Rect)} method. 2900 */ 2901 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2902 2903 /** 2904 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2905 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2906 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2907 * user interaction. 2908 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2909 * has an effect when used in combination with that flag.</p> 2910 */ 2911 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2912 2913 /** 2914 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2915 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2916 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2917 * experience while also hiding the system bars. If this flag is not set, 2918 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2919 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2920 * if the user swipes from the top of the screen. 2921 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2922 * system gestures, such as swiping from the top of the screen. These transient system bars 2923 * will overlay app’s content, may have some degree of transparency, and will automatically 2924 * hide after a short timeout. 2925 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2926 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2927 * with one or both of those flags.</p> 2928 */ 2929 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2930 2931 /** 2932 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2933 * is compatible with light status bar backgrounds. 2934 * 2935 * <p>For this to take effect, the window must request 2936 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2937 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2938 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2939 * FLAG_TRANSLUCENT_STATUS}. 2940 * 2941 * @see android.R.attr#windowLightStatusBar 2942 */ 2943 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2944 2945 /** 2946 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 2947 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 2948 */ 2949 private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000; 2950 2951 /** 2952 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 2953 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 2954 */ 2955 private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000; 2956 2957 /** 2958 * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode 2959 * that is compatible with light navigation bar backgrounds. 2960 * 2961 * <p>For this to take effect, the window must request 2962 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2963 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2964 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION 2965 * FLAG_TRANSLUCENT_NAVIGATION}. 2966 */ 2967 public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010; 2968 2969 /** 2970 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2971 */ 2972 @Deprecated 2973 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2974 2975 /** 2976 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2977 */ 2978 @Deprecated 2979 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2980 2981 /** 2982 * @hide 2983 * 2984 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2985 * out of the public fields to keep the undefined bits out of the developer's way. 2986 * 2987 * Flag to make the status bar not expandable. Unless you also 2988 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2989 */ 2990 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2991 2992 /** 2993 * @hide 2994 * 2995 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2996 * out of the public fields to keep the undefined bits out of the developer's way. 2997 * 2998 * Flag to hide notification icons and scrolling ticker text. 2999 */ 3000 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 3001 3002 /** 3003 * @hide 3004 * 3005 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3006 * out of the public fields to keep the undefined bits out of the developer's way. 3007 * 3008 * Flag to disable incoming notification alerts. This will not block 3009 * icons, but it will block sound, vibrating and other visual or aural notifications. 3010 */ 3011 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 3012 3013 /** 3014 * @hide 3015 * 3016 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3017 * out of the public fields to keep the undefined bits out of the developer's way. 3018 * 3019 * Flag to hide only the scrolling ticker. Note that 3020 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 3021 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 3022 */ 3023 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 3024 3025 /** 3026 * @hide 3027 * 3028 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3029 * out of the public fields to keep the undefined bits out of the developer's way. 3030 * 3031 * Flag to hide the center system info area. 3032 */ 3033 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 3034 3035 /** 3036 * @hide 3037 * 3038 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3039 * out of the public fields to keep the undefined bits out of the developer's way. 3040 * 3041 * Flag to hide only the home button. Don't use this 3042 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3043 */ 3044 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 3045 3046 /** 3047 * @hide 3048 * 3049 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3050 * out of the public fields to keep the undefined bits out of the developer's way. 3051 * 3052 * Flag to hide only the back button. Don't use this 3053 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3054 */ 3055 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 3056 3057 /** 3058 * @hide 3059 * 3060 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3061 * out of the public fields to keep the undefined bits out of the developer's way. 3062 * 3063 * Flag to hide only the clock. You might use this if your activity has 3064 * its own clock making the status bar's clock redundant. 3065 */ 3066 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 3067 3068 /** 3069 * @hide 3070 * 3071 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3072 * out of the public fields to keep the undefined bits out of the developer's way. 3073 * 3074 * Flag to hide only the recent apps button. Don't use this 3075 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3076 */ 3077 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 3078 3079 /** 3080 * @hide 3081 * 3082 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3083 * out of the public fields to keep the undefined bits out of the developer's way. 3084 * 3085 * Flag to disable the global search gesture. Don't use this 3086 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3087 */ 3088 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3089 3090 /** 3091 * @hide 3092 * 3093 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3094 * out of the public fields to keep the undefined bits out of the developer's way. 3095 * 3096 * Flag to specify that the status bar is displayed in transient mode. 3097 */ 3098 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3099 3100 /** 3101 * @hide 3102 * 3103 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3104 * out of the public fields to keep the undefined bits out of the developer's way. 3105 * 3106 * Flag to specify that the navigation bar is displayed in transient mode. 3107 */ 3108 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3109 3110 /** 3111 * @hide 3112 * 3113 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3114 * out of the public fields to keep the undefined bits out of the developer's way. 3115 * 3116 * Flag to specify that the hidden status bar would like to be shown. 3117 */ 3118 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3119 3120 /** 3121 * @hide 3122 * 3123 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3124 * out of the public fields to keep the undefined bits out of the developer's way. 3125 * 3126 * Flag to specify that the hidden navigation bar would like to be shown. 3127 */ 3128 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3129 3130 /** 3131 * @hide 3132 * 3133 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3134 * out of the public fields to keep the undefined bits out of the developer's way. 3135 * 3136 * Flag to specify that the status bar is displayed in translucent mode. 3137 */ 3138 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3139 3140 /** 3141 * @hide 3142 * 3143 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3144 * out of the public fields to keep the undefined bits out of the developer's way. 3145 * 3146 * Flag to specify that the navigation bar is displayed in translucent mode. 3147 */ 3148 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3149 3150 /** 3151 * @hide 3152 * 3153 * Makes navigation bar transparent (but not the status bar). 3154 */ 3155 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3156 3157 /** 3158 * @hide 3159 * 3160 * Makes status bar transparent (but not the navigation bar). 3161 */ 3162 public static final int STATUS_BAR_TRANSPARENT = 0x00000008; 3163 3164 /** 3165 * @hide 3166 * 3167 * Makes both status bar and navigation bar transparent. 3168 */ 3169 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3170 | STATUS_BAR_TRANSPARENT; 3171 3172 /** 3173 * @hide 3174 */ 3175 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3176 3177 /** 3178 * These are the system UI flags that can be cleared by events outside 3179 * of an application. Currently this is just the ability to tap on the 3180 * screen while hiding the navigation bar to have it return. 3181 * @hide 3182 */ 3183 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3184 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3185 | SYSTEM_UI_FLAG_FULLSCREEN; 3186 3187 /** 3188 * Flags that can impact the layout in relation to system UI. 3189 */ 3190 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3191 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3192 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3193 3194 /** @hide */ 3195 @IntDef(flag = true, 3196 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3197 @Retention(RetentionPolicy.SOURCE) 3198 public @interface FindViewFlags {} 3199 3200 /** 3201 * Find views that render the specified text. 3202 * 3203 * @see #findViewsWithText(ArrayList, CharSequence, int) 3204 */ 3205 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3206 3207 /** 3208 * Find find views that contain the specified content description. 3209 * 3210 * @see #findViewsWithText(ArrayList, CharSequence, int) 3211 */ 3212 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3213 3214 /** 3215 * Find views that contain {@link AccessibilityNodeProvider}. Such 3216 * a View is a root of virtual view hierarchy and may contain the searched 3217 * text. If this flag is set Views with providers are automatically 3218 * added and it is a responsibility of the client to call the APIs of 3219 * the provider to determine whether the virtual tree rooted at this View 3220 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3221 * representing the virtual views with this text. 3222 * 3223 * @see #findViewsWithText(ArrayList, CharSequence, int) 3224 * 3225 * @hide 3226 */ 3227 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3228 3229 /** 3230 * The undefined cursor position. 3231 * 3232 * @hide 3233 */ 3234 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3235 3236 /** 3237 * Indicates that the screen has changed state and is now off. 3238 * 3239 * @see #onScreenStateChanged(int) 3240 */ 3241 public static final int SCREEN_STATE_OFF = 0x0; 3242 3243 /** 3244 * Indicates that the screen has changed state and is now on. 3245 * 3246 * @see #onScreenStateChanged(int) 3247 */ 3248 public static final int SCREEN_STATE_ON = 0x1; 3249 3250 /** 3251 * Indicates no axis of view scrolling. 3252 */ 3253 public static final int SCROLL_AXIS_NONE = 0; 3254 3255 /** 3256 * Indicates scrolling along the horizontal axis. 3257 */ 3258 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3259 3260 /** 3261 * Indicates scrolling along the vertical axis. 3262 */ 3263 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3264 3265 /** 3266 * Controls the over-scroll mode for this view. 3267 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3268 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3269 * and {@link #OVER_SCROLL_NEVER}. 3270 */ 3271 private int mOverScrollMode; 3272 3273 /** 3274 * The parent this view is attached to. 3275 * {@hide} 3276 * 3277 * @see #getParent() 3278 */ 3279 protected ViewParent mParent; 3280 3281 /** 3282 * {@hide} 3283 */ 3284 AttachInfo mAttachInfo; 3285 3286 /** 3287 * {@hide} 3288 */ 3289 @ViewDebug.ExportedProperty(flagMapping = { 3290 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3291 name = "FORCE_LAYOUT"), 3292 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3293 name = "LAYOUT_REQUIRED"), 3294 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3295 name = "DRAWING_CACHE_INVALID", outputIf = false), 3296 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3297 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3298 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3299 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3300 }, formatToHexString = true) 3301 3302 /* @hide */ 3303 public int mPrivateFlags; 3304 int mPrivateFlags2; 3305 int mPrivateFlags3; 3306 3307 /** 3308 * This view's request for the visibility of the status bar. 3309 * @hide 3310 */ 3311 @ViewDebug.ExportedProperty(flagMapping = { 3312 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3313 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3314 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3315 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3316 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3317 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3318 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3319 equals = SYSTEM_UI_FLAG_VISIBLE, 3320 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3321 }, formatToHexString = true) 3322 int mSystemUiVisibility; 3323 3324 /** 3325 * Reference count for transient state. 3326 * @see #setHasTransientState(boolean) 3327 */ 3328 int mTransientStateCount = 0; 3329 3330 /** 3331 * Count of how many windows this view has been attached to. 3332 */ 3333 int mWindowAttachCount; 3334 3335 /** 3336 * The layout parameters associated with this view and used by the parent 3337 * {@link android.view.ViewGroup} to determine how this view should be 3338 * laid out. 3339 * {@hide} 3340 */ 3341 protected ViewGroup.LayoutParams mLayoutParams; 3342 3343 /** 3344 * The view flags hold various views states. 3345 * {@hide} 3346 */ 3347 @ViewDebug.ExportedProperty(formatToHexString = true) 3348 int mViewFlags; 3349 3350 static class TransformationInfo { 3351 /** 3352 * The transform matrix for the View. This transform is calculated internally 3353 * based on the translation, rotation, and scale properties. 3354 * 3355 * Do *not* use this variable directly; instead call getMatrix(), which will 3356 * load the value from the View's RenderNode. 3357 */ 3358 private final Matrix mMatrix = new Matrix(); 3359 3360 /** 3361 * The inverse transform matrix for the View. This transform is calculated 3362 * internally based on the translation, rotation, and scale properties. 3363 * 3364 * Do *not* use this variable directly; instead call getInverseMatrix(), 3365 * which will load the value from the View's RenderNode. 3366 */ 3367 private Matrix mInverseMatrix; 3368 3369 /** 3370 * The opacity of the View. This is a value from 0 to 1, where 0 means 3371 * completely transparent and 1 means completely opaque. 3372 */ 3373 @ViewDebug.ExportedProperty 3374 float mAlpha = 1f; 3375 3376 /** 3377 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3378 * property only used by transitions, which is composited with the other alpha 3379 * values to calculate the final visual alpha value. 3380 */ 3381 float mTransitionAlpha = 1f; 3382 } 3383 3384 /** @hide */ 3385 public TransformationInfo mTransformationInfo; 3386 3387 /** 3388 * Current clip bounds. to which all drawing of this view are constrained. 3389 */ 3390 Rect mClipBounds = null; 3391 3392 private boolean mLastIsOpaque; 3393 3394 /** 3395 * The distance in pixels from the left edge of this view's parent 3396 * to the left edge of this view. 3397 * {@hide} 3398 */ 3399 @ViewDebug.ExportedProperty(category = "layout") 3400 protected int mLeft; 3401 /** 3402 * The distance in pixels from the left edge of this view's parent 3403 * to the right edge of this view. 3404 * {@hide} 3405 */ 3406 @ViewDebug.ExportedProperty(category = "layout") 3407 protected int mRight; 3408 /** 3409 * The distance in pixels from the top edge of this view's parent 3410 * to the top edge of this view. 3411 * {@hide} 3412 */ 3413 @ViewDebug.ExportedProperty(category = "layout") 3414 protected int mTop; 3415 /** 3416 * The distance in pixels from the top edge of this view's parent 3417 * to the bottom edge of this view. 3418 * {@hide} 3419 */ 3420 @ViewDebug.ExportedProperty(category = "layout") 3421 protected int mBottom; 3422 3423 /** 3424 * The offset, in pixels, by which the content of this view is scrolled 3425 * horizontally. 3426 * {@hide} 3427 */ 3428 @ViewDebug.ExportedProperty(category = "scrolling") 3429 protected int mScrollX; 3430 /** 3431 * The offset, in pixels, by which the content of this view is scrolled 3432 * vertically. 3433 * {@hide} 3434 */ 3435 @ViewDebug.ExportedProperty(category = "scrolling") 3436 protected int mScrollY; 3437 3438 /** 3439 * The left padding in pixels, that is the distance in pixels between the 3440 * left edge of this view and the left edge of its content. 3441 * {@hide} 3442 */ 3443 @ViewDebug.ExportedProperty(category = "padding") 3444 protected int mPaddingLeft = 0; 3445 /** 3446 * The right padding in pixels, that is the distance in pixels between the 3447 * right edge of this view and the right edge of its content. 3448 * {@hide} 3449 */ 3450 @ViewDebug.ExportedProperty(category = "padding") 3451 protected int mPaddingRight = 0; 3452 /** 3453 * The top padding in pixels, that is the distance in pixels between the 3454 * top edge of this view and the top edge of its content. 3455 * {@hide} 3456 */ 3457 @ViewDebug.ExportedProperty(category = "padding") 3458 protected int mPaddingTop; 3459 /** 3460 * The bottom padding in pixels, that is the distance in pixels between the 3461 * bottom edge of this view and the bottom edge of its content. 3462 * {@hide} 3463 */ 3464 @ViewDebug.ExportedProperty(category = "padding") 3465 protected int mPaddingBottom; 3466 3467 /** 3468 * The layout insets in pixels, that is the distance in pixels between the 3469 * visible edges of this view its bounds. 3470 */ 3471 private Insets mLayoutInsets; 3472 3473 /** 3474 * Briefly describes the view and is primarily used for accessibility support. 3475 */ 3476 private CharSequence mContentDescription; 3477 3478 /** 3479 * Specifies the id of a view for which this view serves as a label for 3480 * accessibility purposes. 3481 */ 3482 private int mLabelForId = View.NO_ID; 3483 3484 /** 3485 * Predicate for matching labeled view id with its label for 3486 * accessibility purposes. 3487 */ 3488 private MatchLabelForPredicate mMatchLabelForPredicate; 3489 3490 /** 3491 * Specifies a view before which this one is visited in accessibility traversal. 3492 */ 3493 private int mAccessibilityTraversalBeforeId = NO_ID; 3494 3495 /** 3496 * Specifies a view after which this one is visited in accessibility traversal. 3497 */ 3498 private int mAccessibilityTraversalAfterId = NO_ID; 3499 3500 /** 3501 * Predicate for matching a view by its id. 3502 */ 3503 private MatchIdPredicate mMatchIdPredicate; 3504 3505 /** 3506 * Cache the paddingRight set by the user to append to the scrollbar's size. 3507 * 3508 * @hide 3509 */ 3510 @ViewDebug.ExportedProperty(category = "padding") 3511 protected int mUserPaddingRight; 3512 3513 /** 3514 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3515 * 3516 * @hide 3517 */ 3518 @ViewDebug.ExportedProperty(category = "padding") 3519 protected int mUserPaddingBottom; 3520 3521 /** 3522 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3523 * 3524 * @hide 3525 */ 3526 @ViewDebug.ExportedProperty(category = "padding") 3527 protected int mUserPaddingLeft; 3528 3529 /** 3530 * Cache the paddingStart set by the user to append to the scrollbar's size. 3531 * 3532 */ 3533 @ViewDebug.ExportedProperty(category = "padding") 3534 int mUserPaddingStart; 3535 3536 /** 3537 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3538 * 3539 */ 3540 @ViewDebug.ExportedProperty(category = "padding") 3541 int mUserPaddingEnd; 3542 3543 /** 3544 * Cache initial left padding. 3545 * 3546 * @hide 3547 */ 3548 int mUserPaddingLeftInitial; 3549 3550 /** 3551 * Cache initial right padding. 3552 * 3553 * @hide 3554 */ 3555 int mUserPaddingRightInitial; 3556 3557 /** 3558 * Default undefined padding 3559 */ 3560 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3561 3562 /** 3563 * Cache if a left padding has been defined 3564 */ 3565 private boolean mLeftPaddingDefined = false; 3566 3567 /** 3568 * Cache if a right padding has been defined 3569 */ 3570 private boolean mRightPaddingDefined = false; 3571 3572 /** 3573 * @hide 3574 */ 3575 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3576 /** 3577 * @hide 3578 */ 3579 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3580 3581 private LongSparseLongArray mMeasureCache; 3582 3583 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3584 private Drawable mBackground; 3585 private TintInfo mBackgroundTint; 3586 3587 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3588 private ForegroundInfo mForegroundInfo; 3589 3590 private Drawable mScrollIndicatorDrawable; 3591 3592 /** 3593 * RenderNode used for backgrounds. 3594 * <p> 3595 * When non-null and valid, this is expected to contain an up-to-date copy 3596 * of the background drawable. It is cleared on temporary detach, and reset 3597 * on cleanup. 3598 */ 3599 private RenderNode mBackgroundRenderNode; 3600 3601 private int mBackgroundResource; 3602 private boolean mBackgroundSizeChanged; 3603 3604 private String mTransitionName; 3605 3606 static class TintInfo { 3607 ColorStateList mTintList; 3608 PorterDuff.Mode mTintMode; 3609 boolean mHasTintMode; 3610 boolean mHasTintList; 3611 } 3612 3613 private static class ForegroundInfo { 3614 private Drawable mDrawable; 3615 private TintInfo mTintInfo; 3616 private int mGravity = Gravity.FILL; 3617 private boolean mInsidePadding = true; 3618 private boolean mBoundsChanged = true; 3619 private final Rect mSelfBounds = new Rect(); 3620 private final Rect mOverlayBounds = new Rect(); 3621 } 3622 3623 static class ListenerInfo { 3624 /** 3625 * Listener used to dispatch focus change events. 3626 * This field should be made private, so it is hidden from the SDK. 3627 * {@hide} 3628 */ 3629 protected OnFocusChangeListener mOnFocusChangeListener; 3630 3631 /** 3632 * Listeners for layout change events. 3633 */ 3634 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3635 3636 protected OnScrollChangeListener mOnScrollChangeListener; 3637 3638 /** 3639 * Listeners for attach events. 3640 */ 3641 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3642 3643 /** 3644 * Listener used to dispatch click events. 3645 * This field should be made private, so it is hidden from the SDK. 3646 * {@hide} 3647 */ 3648 public OnClickListener mOnClickListener; 3649 3650 /** 3651 * Listener used to dispatch long click events. 3652 * This field should be made private, so it is hidden from the SDK. 3653 * {@hide} 3654 */ 3655 protected OnLongClickListener mOnLongClickListener; 3656 3657 /** 3658 * Listener used to dispatch context click events. This field should be made private, so it 3659 * is hidden from the SDK. 3660 * {@hide} 3661 */ 3662 protected OnContextClickListener mOnContextClickListener; 3663 3664 /** 3665 * Listener used to build the context menu. 3666 * This field should be made private, so it is hidden from the SDK. 3667 * {@hide} 3668 */ 3669 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3670 3671 private OnKeyListener mOnKeyListener; 3672 3673 private OnTouchListener mOnTouchListener; 3674 3675 private OnHoverListener mOnHoverListener; 3676 3677 private OnGenericMotionListener mOnGenericMotionListener; 3678 3679 private OnDragListener mOnDragListener; 3680 3681 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3682 3683 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3684 } 3685 3686 ListenerInfo mListenerInfo; 3687 3688 private static class TooltipInfo { 3689 /** 3690 * Text to be displayed in a tooltip popup. 3691 */ 3692 @Nullable 3693 CharSequence mTooltipText; 3694 3695 /** 3696 * View-relative position of the tooltip anchor point. 3697 */ 3698 int mAnchorX; 3699 int mAnchorY; 3700 3701 /** 3702 * The tooltip popup. 3703 */ 3704 @Nullable 3705 TooltipPopup mTooltipPopup; 3706 3707 /** 3708 * Set to true if the tooltip was shown as a result of a long click. 3709 */ 3710 boolean mTooltipFromLongClick; 3711 3712 /** 3713 * Keep these Runnables so that they can be used to reschedule. 3714 */ 3715 Runnable mShowTooltipRunnable; 3716 Runnable mHideTooltipRunnable; 3717 } 3718 3719 TooltipInfo mTooltipInfo; 3720 3721 // Temporary values used to hold (x,y) coordinates when delegating from the 3722 // two-arg performLongClick() method to the legacy no-arg version. 3723 private float mLongClickX = Float.NaN; 3724 private float mLongClickY = Float.NaN; 3725 3726 /** 3727 * The application environment this view lives in. 3728 * This field should be made private, so it is hidden from the SDK. 3729 * {@hide} 3730 */ 3731 @ViewDebug.ExportedProperty(deepExport = true) 3732 protected Context mContext; 3733 3734 private final Resources mResources; 3735 3736 private ScrollabilityCache mScrollCache; 3737 3738 private int[] mDrawableState = null; 3739 3740 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3741 3742 /** 3743 * Animator that automatically runs based on state changes. 3744 */ 3745 private StateListAnimator mStateListAnimator; 3746 3747 /** 3748 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3749 * the user may specify which view to go to next. 3750 */ 3751 private int mNextFocusLeftId = View.NO_ID; 3752 3753 /** 3754 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3755 * the user may specify which view to go to next. 3756 */ 3757 private int mNextFocusRightId = View.NO_ID; 3758 3759 /** 3760 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3761 * the user may specify which view to go to next. 3762 */ 3763 private int mNextFocusUpId = View.NO_ID; 3764 3765 /** 3766 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3767 * the user may specify which view to go to next. 3768 */ 3769 private int mNextFocusDownId = View.NO_ID; 3770 3771 /** 3772 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3773 * the user may specify which view to go to next. 3774 */ 3775 int mNextFocusForwardId = View.NO_ID; 3776 3777 /** 3778 * User-specified next keyboard navigation cluster. 3779 */ 3780 int mNextClusterForwardId = View.NO_ID; 3781 3782 private CheckForLongPress mPendingCheckForLongPress; 3783 private CheckForTap mPendingCheckForTap = null; 3784 private PerformClick mPerformClick; 3785 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3786 3787 private UnsetPressedState mUnsetPressedState; 3788 3789 /** 3790 * Whether the long press's action has been invoked. The tap's action is invoked on the 3791 * up event while a long press is invoked as soon as the long press duration is reached, so 3792 * a long press could be performed before the tap is checked, in which case the tap's action 3793 * should not be invoked. 3794 */ 3795 private boolean mHasPerformedLongPress; 3796 3797 /** 3798 * Whether a context click button is currently pressed down. This is true when the stylus is 3799 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3800 * pressed. This is false once the button is released or if the stylus has been lifted. 3801 */ 3802 private boolean mInContextButtonPress; 3803 3804 /** 3805 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3806 * true after a stylus button press has occured, when the next up event should not be recognized 3807 * as a tap. 3808 */ 3809 private boolean mIgnoreNextUpEvent; 3810 3811 /** 3812 * The minimum height of the view. We'll try our best to have the height 3813 * of this view to at least this amount. 3814 */ 3815 @ViewDebug.ExportedProperty(category = "measurement") 3816 private int mMinHeight; 3817 3818 /** 3819 * The minimum width of the view. We'll try our best to have the width 3820 * of this view to at least this amount. 3821 */ 3822 @ViewDebug.ExportedProperty(category = "measurement") 3823 private int mMinWidth; 3824 3825 /** 3826 * The delegate to handle touch events that are physically in this view 3827 * but should be handled by another view. 3828 */ 3829 private TouchDelegate mTouchDelegate = null; 3830 3831 /** 3832 * Solid color to use as a background when creating the drawing cache. Enables 3833 * the cache to use 16 bit bitmaps instead of 32 bit. 3834 */ 3835 private int mDrawingCacheBackgroundColor = 0; 3836 3837 /** 3838 * Special tree observer used when mAttachInfo is null. 3839 */ 3840 private ViewTreeObserver mFloatingTreeObserver; 3841 3842 /** 3843 * Cache the touch slop from the context that created the view. 3844 */ 3845 private int mTouchSlop; 3846 3847 /** 3848 * Object that handles automatic animation of view properties. 3849 */ 3850 private ViewPropertyAnimator mAnimator = null; 3851 3852 /** 3853 * List of registered FrameMetricsObservers. 3854 */ 3855 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3856 3857 /** 3858 * Flag indicating that a drag can cross window boundaries. When 3859 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3860 * with this flag set, all visible applications with targetSdkVersion >= 3861 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 3862 * in the drag operation and receive the dragged content. 3863 * 3864 * <p>If this is the only flag set, then the drag recipient will only have access to text data 3865 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3866 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 3867 */ 3868 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3869 3870 /** 3871 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3872 * request read access to the content URI(s) contained in the {@link ClipData} object. 3873 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3874 */ 3875 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3876 3877 /** 3878 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3879 * request write access to the content URI(s) contained in the {@link ClipData} object. 3880 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3881 */ 3882 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3883 3884 /** 3885 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3886 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3887 * reboots until explicitly revoked with 3888 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3889 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3890 */ 3891 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3892 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3893 3894 /** 3895 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3896 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3897 * match against the original granted URI. 3898 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3899 */ 3900 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3901 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3902 3903 /** 3904 * Flag indicating that the drag shadow will be opaque. When 3905 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3906 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3907 */ 3908 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3909 3910 /** 3911 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3912 */ 3913 private float mVerticalScrollFactor; 3914 3915 /** 3916 * Position of the vertical scroll bar. 3917 */ 3918 private int mVerticalScrollbarPosition; 3919 3920 /** 3921 * Position the scroll bar at the default position as determined by the system. 3922 */ 3923 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3924 3925 /** 3926 * Position the scroll bar along the left edge. 3927 */ 3928 public static final int SCROLLBAR_POSITION_LEFT = 1; 3929 3930 /** 3931 * Position the scroll bar along the right edge. 3932 */ 3933 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3934 3935 /** 3936 * Indicates that the view does not have a layer. 3937 * 3938 * @see #getLayerType() 3939 * @see #setLayerType(int, android.graphics.Paint) 3940 * @see #LAYER_TYPE_SOFTWARE 3941 * @see #LAYER_TYPE_HARDWARE 3942 */ 3943 public static final int LAYER_TYPE_NONE = 0; 3944 3945 /** 3946 * <p>Indicates that the view has a software layer. A software layer is backed 3947 * by a bitmap and causes the view to be rendered using Android's software 3948 * rendering pipeline, even if hardware acceleration is enabled.</p> 3949 * 3950 * <p>Software layers have various usages:</p> 3951 * <p>When the application is not using hardware acceleration, a software layer 3952 * is useful to apply a specific color filter and/or blending mode and/or 3953 * translucency to a view and all its children.</p> 3954 * <p>When the application is using hardware acceleration, a software layer 3955 * is useful to render drawing primitives not supported by the hardware 3956 * accelerated pipeline. It can also be used to cache a complex view tree 3957 * into a texture and reduce the complexity of drawing operations. For instance, 3958 * when animating a complex view tree with a translation, a software layer can 3959 * be used to render the view tree only once.</p> 3960 * <p>Software layers should be avoided when the affected view tree updates 3961 * often. Every update will require to re-render the software layer, which can 3962 * potentially be slow (particularly when hardware acceleration is turned on 3963 * since the layer will have to be uploaded into a hardware texture after every 3964 * update.)</p> 3965 * 3966 * @see #getLayerType() 3967 * @see #setLayerType(int, android.graphics.Paint) 3968 * @see #LAYER_TYPE_NONE 3969 * @see #LAYER_TYPE_HARDWARE 3970 */ 3971 public static final int LAYER_TYPE_SOFTWARE = 1; 3972 3973 /** 3974 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3975 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3976 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3977 * rendering pipeline, but only if hardware acceleration is turned on for the 3978 * view hierarchy. When hardware acceleration is turned off, hardware layers 3979 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3980 * 3981 * <p>A hardware layer is useful to apply a specific color filter and/or 3982 * blending mode and/or translucency to a view and all its children.</p> 3983 * <p>A hardware layer can be used to cache a complex view tree into a 3984 * texture and reduce the complexity of drawing operations. For instance, 3985 * when animating a complex view tree with a translation, a hardware layer can 3986 * be used to render the view tree only once.</p> 3987 * <p>A hardware layer can also be used to increase the rendering quality when 3988 * rotation transformations are applied on a view. It can also be used to 3989 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3990 * 3991 * @see #getLayerType() 3992 * @see #setLayerType(int, android.graphics.Paint) 3993 * @see #LAYER_TYPE_NONE 3994 * @see #LAYER_TYPE_SOFTWARE 3995 */ 3996 public static final int LAYER_TYPE_HARDWARE = 2; 3997 3998 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3999 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 4000 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 4001 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 4002 }) 4003 int mLayerType = LAYER_TYPE_NONE; 4004 Paint mLayerPaint; 4005 4006 4007 /** 4008 * Set when a request was made to decide if views in an {@link android.app.Activity} can be 4009 * auto-filled by an {@link android.service.autofill.AutoFillService}. 4010 * 4011 * <p>Since this request is made without a explicit user consent, the resulting 4012 * {@link android.app.assist.AssistStructure} should not contain any PII 4013 * (Personally Identifiable Information). 4014 * 4015 * <p>Examples: 4016 * <ul> 4017 * <li>{@link android.widget.TextView} texts should only be included when they were set by 4018 * static resources. 4019 * <li>{@link android.webkit.WebView} virtual children should be restricted to a subset of 4020 * input fields and tags (like {@code id}). 4021 * </ul> 4022 */ 4023 // TODO(b/33197203) (b/34078930): improve documentation: mention all cases, show examples, etc. 4024 // In particular, be more specific about webview restrictions 4025 public static final int AUTO_FILL_FLAG_TYPE_FILL = 0x1; 4026 4027 /** 4028 * Set when the user explicitly asked a {@link android.service.autofill.AutoFillService} to save 4029 * the value of the {@link View}s in an {@link android.app.Activity}. 4030 * 4031 * <p>The resulting {@link android.app.assist.AssistStructure} can contain any kind of PII 4032 * (Personally Identifiable Information). For example, the text of password fields should be 4033 * included since that's what's typically saved. 4034 */ 4035 public static final int AUTO_FILL_FLAG_TYPE_SAVE = 0x2; 4036 4037 /** 4038 * Set to true when drawing cache is enabled and cannot be created. 4039 * 4040 * @hide 4041 */ 4042 public boolean mCachingFailed; 4043 private Bitmap mDrawingCache; 4044 private Bitmap mUnscaledDrawingCache; 4045 4046 /** 4047 * RenderNode holding View properties, potentially holding a DisplayList of View content. 4048 * <p> 4049 * When non-null and valid, this is expected to contain an up-to-date copy 4050 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 4051 * cleanup. 4052 */ 4053 final RenderNode mRenderNode; 4054 4055 /** 4056 * Set to true when the view is sending hover accessibility events because it 4057 * is the innermost hovered view. 4058 */ 4059 private boolean mSendingHoverAccessibilityEvents; 4060 4061 /** 4062 * Delegate for injecting accessibility functionality. 4063 */ 4064 AccessibilityDelegate mAccessibilityDelegate; 4065 4066 /** 4067 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 4068 * and add/remove objects to/from the overlay directly through the Overlay methods. 4069 */ 4070 ViewOverlay mOverlay; 4071 4072 /** 4073 * The currently active parent view for receiving delegated nested scrolling events. 4074 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 4075 * by {@link #stopNestedScroll()} at the same point where we clear 4076 * requestDisallowInterceptTouchEvent. 4077 */ 4078 private ViewParent mNestedScrollingParent; 4079 4080 /** 4081 * Consistency verifier for debugging purposes. 4082 * @hide 4083 */ 4084 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 4085 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 4086 new InputEventConsistencyVerifier(this, 0) : null; 4087 4088 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 4089 4090 private int[] mTempNestedScrollConsumed; 4091 4092 /** 4093 * An overlay is going to draw this View instead of being drawn as part of this 4094 * View's parent. mGhostView is the View in the Overlay that must be invalidated 4095 * when this view is invalidated. 4096 */ 4097 GhostView mGhostView; 4098 4099 /** 4100 * Holds pairs of adjacent attribute data: attribute name followed by its value. 4101 * @hide 4102 */ 4103 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 4104 public String[] mAttributes; 4105 4106 /** 4107 * Maps a Resource id to its name. 4108 */ 4109 private static SparseArray<String> mAttributeMap; 4110 4111 /** 4112 * Queue of pending runnables. Used to postpone calls to post() until this 4113 * view is attached and has a handler. 4114 */ 4115 private HandlerActionQueue mRunQueue; 4116 4117 /** 4118 * The pointer icon when the mouse hovers on this view. The default is null. 4119 */ 4120 private PointerIcon mPointerIcon; 4121 4122 /** 4123 * @hide 4124 */ 4125 String mStartActivityRequestWho; 4126 4127 @Nullable 4128 private RoundScrollbarRenderer mRoundScrollbarRenderer; 4129 4130 /** 4131 * Simple constructor to use when creating a view from code. 4132 * 4133 * @param context The Context the view is running in, through which it can 4134 * access the current theme, resources, etc. 4135 */ 4136 public View(Context context) { 4137 mContext = context; 4138 mResources = context != null ? context.getResources() : null; 4139 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 4140 // Set some flags defaults 4141 mPrivateFlags2 = 4142 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 4143 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 4144 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 4145 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4146 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4147 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4148 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4149 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4150 mUserPaddingStart = UNDEFINED_PADDING; 4151 mUserPaddingEnd = UNDEFINED_PADDING; 4152 mRenderNode = RenderNode.create(getClass().getName(), this); 4153 4154 if (!sCompatibilityDone && context != null) { 4155 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4156 4157 // Older apps may need this compatibility hack for measurement. 4158 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4159 4160 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4161 // of whether a layout was requested on that View. 4162 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4163 4164 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4165 4166 // In M and newer, our widgets can pass a "hint" value in the size 4167 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4168 // know what the expected parent size is going to be, so e.g. list items can size 4169 // themselves at 1/3 the size of their container. It breaks older apps though, 4170 // specifically apps that use some popular open source libraries. 4171 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4172 4173 // Old versions of the platform would give different results from 4174 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4175 // modes, so we always need to run an additional EXACTLY pass. 4176 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4177 4178 // Prior to N, layout params could change without requiring a 4179 // subsequent call to setLayoutParams() and they would usually 4180 // work. Partial layout breaks this assumption. 4181 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4182 4183 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4184 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4185 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4186 4187 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4188 // in apps so we target check it to avoid breaking existing apps. 4189 sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N; 4190 4191 sCascadedDragDrop = targetSdkVersion < N; 4192 4193 sCompatibilityDone = true; 4194 } 4195 } 4196 4197 /** 4198 * Constructor that is called when inflating a view from XML. This is called 4199 * when a view is being constructed from an XML file, supplying attributes 4200 * that were specified in the XML file. This version uses a default style of 4201 * 0, so the only attribute values applied are those in the Context's Theme 4202 * and the given AttributeSet. 4203 * 4204 * <p> 4205 * The method onFinishInflate() will be called after all children have been 4206 * added. 4207 * 4208 * @param context The Context the view is running in, through which it can 4209 * access the current theme, resources, etc. 4210 * @param attrs The attributes of the XML tag that is inflating the view. 4211 * @see #View(Context, AttributeSet, int) 4212 */ 4213 public View(Context context, @Nullable AttributeSet attrs) { 4214 this(context, attrs, 0); 4215 } 4216 4217 /** 4218 * Perform inflation from XML and apply a class-specific base style from a 4219 * theme attribute. This constructor of View allows subclasses to use their 4220 * own base style when they are inflating. For example, a Button class's 4221 * constructor would call this version of the super class constructor and 4222 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4223 * allows the theme's button style to modify all of the base view attributes 4224 * (in particular its background) as well as the Button class's attributes. 4225 * 4226 * @param context The Context the view is running in, through which it can 4227 * access the current theme, resources, etc. 4228 * @param attrs The attributes of the XML tag that is inflating the view. 4229 * @param defStyleAttr An attribute in the current theme that contains a 4230 * reference to a style resource that supplies default values for 4231 * the view. Can be 0 to not look for defaults. 4232 * @see #View(Context, AttributeSet) 4233 */ 4234 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4235 this(context, attrs, defStyleAttr, 0); 4236 } 4237 4238 /** 4239 * Perform inflation from XML and apply a class-specific base style from a 4240 * theme attribute or style resource. This constructor of View allows 4241 * subclasses to use their own base style when they are inflating. 4242 * <p> 4243 * When determining the final value of a particular attribute, there are 4244 * four inputs that come into play: 4245 * <ol> 4246 * <li>Any attribute values in the given AttributeSet. 4247 * <li>The style resource specified in the AttributeSet (named "style"). 4248 * <li>The default style specified by <var>defStyleAttr</var>. 4249 * <li>The default style specified by <var>defStyleRes</var>. 4250 * <li>The base values in this theme. 4251 * </ol> 4252 * <p> 4253 * Each of these inputs is considered in-order, with the first listed taking 4254 * precedence over the following ones. In other words, if in the 4255 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4256 * , then the button's text will <em>always</em> be black, regardless of 4257 * what is specified in any of the styles. 4258 * 4259 * @param context The Context the view is running in, through which it can 4260 * access the current theme, resources, etc. 4261 * @param attrs The attributes of the XML tag that is inflating the view. 4262 * @param defStyleAttr An attribute in the current theme that contains a 4263 * reference to a style resource that supplies default values for 4264 * the view. Can be 0 to not look for defaults. 4265 * @param defStyleRes A resource identifier of a style resource that 4266 * supplies default values for the view, used only if 4267 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4268 * to not look for defaults. 4269 * @see #View(Context, AttributeSet, int) 4270 */ 4271 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4272 this(context); 4273 4274 final TypedArray a = context.obtainStyledAttributes( 4275 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4276 4277 if (mDebugViewAttributes) { 4278 saveAttributeData(attrs, a); 4279 } 4280 4281 Drawable background = null; 4282 4283 int leftPadding = -1; 4284 int topPadding = -1; 4285 int rightPadding = -1; 4286 int bottomPadding = -1; 4287 int startPadding = UNDEFINED_PADDING; 4288 int endPadding = UNDEFINED_PADDING; 4289 4290 int padding = -1; 4291 int paddingHorizontal = -1; 4292 int paddingVertical = -1; 4293 4294 int viewFlagValues = 0; 4295 int viewFlagMasks = 0; 4296 4297 boolean setScrollContainer = false; 4298 4299 int x = 0; 4300 int y = 0; 4301 4302 float tx = 0; 4303 float ty = 0; 4304 float tz = 0; 4305 float elevation = 0; 4306 float rotation = 0; 4307 float rotationX = 0; 4308 float rotationY = 0; 4309 float sx = 1f; 4310 float sy = 1f; 4311 boolean transformSet = false; 4312 4313 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4314 int overScrollMode = mOverScrollMode; 4315 boolean initializeScrollbars = false; 4316 boolean initializeScrollIndicators = false; 4317 4318 boolean startPaddingDefined = false; 4319 boolean endPaddingDefined = false; 4320 boolean leftPaddingDefined = false; 4321 boolean rightPaddingDefined = false; 4322 4323 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4324 4325 final int N = a.getIndexCount(); 4326 for (int i = 0; i < N; i++) { 4327 int attr = a.getIndex(i); 4328 switch (attr) { 4329 case com.android.internal.R.styleable.View_background: 4330 background = a.getDrawable(attr); 4331 break; 4332 case com.android.internal.R.styleable.View_padding: 4333 padding = a.getDimensionPixelSize(attr, -1); 4334 mUserPaddingLeftInitial = padding; 4335 mUserPaddingRightInitial = padding; 4336 leftPaddingDefined = true; 4337 rightPaddingDefined = true; 4338 break; 4339 case com.android.internal.R.styleable.View_paddingHorizontal: 4340 paddingHorizontal = a.getDimensionPixelSize(attr, -1); 4341 mUserPaddingLeftInitial = paddingHorizontal; 4342 mUserPaddingRightInitial = paddingHorizontal; 4343 leftPaddingDefined = true; 4344 rightPaddingDefined = true; 4345 break; 4346 case com.android.internal.R.styleable.View_paddingVertical: 4347 paddingVertical = a.getDimensionPixelSize(attr, -1); 4348 break; 4349 case com.android.internal.R.styleable.View_paddingLeft: 4350 leftPadding = a.getDimensionPixelSize(attr, -1); 4351 mUserPaddingLeftInitial = leftPadding; 4352 leftPaddingDefined = true; 4353 break; 4354 case com.android.internal.R.styleable.View_paddingTop: 4355 topPadding = a.getDimensionPixelSize(attr, -1); 4356 break; 4357 case com.android.internal.R.styleable.View_paddingRight: 4358 rightPadding = a.getDimensionPixelSize(attr, -1); 4359 mUserPaddingRightInitial = rightPadding; 4360 rightPaddingDefined = true; 4361 break; 4362 case com.android.internal.R.styleable.View_paddingBottom: 4363 bottomPadding = a.getDimensionPixelSize(attr, -1); 4364 break; 4365 case com.android.internal.R.styleable.View_paddingStart: 4366 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4367 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4368 break; 4369 case com.android.internal.R.styleable.View_paddingEnd: 4370 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4371 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4372 break; 4373 case com.android.internal.R.styleable.View_scrollX: 4374 x = a.getDimensionPixelOffset(attr, 0); 4375 break; 4376 case com.android.internal.R.styleable.View_scrollY: 4377 y = a.getDimensionPixelOffset(attr, 0); 4378 break; 4379 case com.android.internal.R.styleable.View_alpha: 4380 setAlpha(a.getFloat(attr, 1f)); 4381 break; 4382 case com.android.internal.R.styleable.View_transformPivotX: 4383 setPivotX(a.getDimension(attr, 0)); 4384 break; 4385 case com.android.internal.R.styleable.View_transformPivotY: 4386 setPivotY(a.getDimension(attr, 0)); 4387 break; 4388 case com.android.internal.R.styleable.View_translationX: 4389 tx = a.getDimension(attr, 0); 4390 transformSet = true; 4391 break; 4392 case com.android.internal.R.styleable.View_translationY: 4393 ty = a.getDimension(attr, 0); 4394 transformSet = true; 4395 break; 4396 case com.android.internal.R.styleable.View_translationZ: 4397 tz = a.getDimension(attr, 0); 4398 transformSet = true; 4399 break; 4400 case com.android.internal.R.styleable.View_elevation: 4401 elevation = a.getDimension(attr, 0); 4402 transformSet = true; 4403 break; 4404 case com.android.internal.R.styleable.View_rotation: 4405 rotation = a.getFloat(attr, 0); 4406 transformSet = true; 4407 break; 4408 case com.android.internal.R.styleable.View_rotationX: 4409 rotationX = a.getFloat(attr, 0); 4410 transformSet = true; 4411 break; 4412 case com.android.internal.R.styleable.View_rotationY: 4413 rotationY = a.getFloat(attr, 0); 4414 transformSet = true; 4415 break; 4416 case com.android.internal.R.styleable.View_scaleX: 4417 sx = a.getFloat(attr, 1f); 4418 transformSet = true; 4419 break; 4420 case com.android.internal.R.styleable.View_scaleY: 4421 sy = a.getFloat(attr, 1f); 4422 transformSet = true; 4423 break; 4424 case com.android.internal.R.styleable.View_id: 4425 mID = a.getResourceId(attr, NO_ID); 4426 break; 4427 case com.android.internal.R.styleable.View_tag: 4428 mTag = a.getText(attr); 4429 break; 4430 case com.android.internal.R.styleable.View_fitsSystemWindows: 4431 if (a.getBoolean(attr, false)) { 4432 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4433 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4434 } 4435 break; 4436 case com.android.internal.R.styleable.View_focusable: 4437 if (a.getBoolean(attr, false)) { 4438 viewFlagValues |= FOCUSABLE; 4439 viewFlagMasks |= FOCUSABLE_MASK; 4440 } 4441 break; 4442 case com.android.internal.R.styleable.View_focusableInTouchMode: 4443 if (a.getBoolean(attr, false)) { 4444 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4445 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4446 } 4447 break; 4448 case com.android.internal.R.styleable.View_clickable: 4449 if (a.getBoolean(attr, false)) { 4450 viewFlagValues |= CLICKABLE; 4451 viewFlagMasks |= CLICKABLE; 4452 } 4453 break; 4454 case com.android.internal.R.styleable.View_longClickable: 4455 if (a.getBoolean(attr, false)) { 4456 viewFlagValues |= LONG_CLICKABLE; 4457 viewFlagMasks |= LONG_CLICKABLE; 4458 } 4459 break; 4460 case com.android.internal.R.styleable.View_contextClickable: 4461 if (a.getBoolean(attr, false)) { 4462 viewFlagValues |= CONTEXT_CLICKABLE; 4463 viewFlagMasks |= CONTEXT_CLICKABLE; 4464 } 4465 break; 4466 case com.android.internal.R.styleable.View_saveEnabled: 4467 if (!a.getBoolean(attr, true)) { 4468 viewFlagValues |= SAVE_DISABLED; 4469 viewFlagMasks |= SAVE_DISABLED_MASK; 4470 } 4471 break; 4472 case com.android.internal.R.styleable.View_duplicateParentState: 4473 if (a.getBoolean(attr, false)) { 4474 viewFlagValues |= DUPLICATE_PARENT_STATE; 4475 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4476 } 4477 break; 4478 case com.android.internal.R.styleable.View_visibility: 4479 final int visibility = a.getInt(attr, 0); 4480 if (visibility != 0) { 4481 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4482 viewFlagMasks |= VISIBILITY_MASK; 4483 } 4484 break; 4485 case com.android.internal.R.styleable.View_layoutDirection: 4486 // Clear any layout direction flags (included resolved bits) already set 4487 mPrivateFlags2 &= 4488 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4489 // Set the layout direction flags depending on the value of the attribute 4490 final int layoutDirection = a.getInt(attr, -1); 4491 final int value = (layoutDirection != -1) ? 4492 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4493 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4494 break; 4495 case com.android.internal.R.styleable.View_drawingCacheQuality: 4496 final int cacheQuality = a.getInt(attr, 0); 4497 if (cacheQuality != 0) { 4498 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4499 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4500 } 4501 break; 4502 case com.android.internal.R.styleable.View_contentDescription: 4503 setContentDescription(a.getString(attr)); 4504 break; 4505 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4506 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4507 break; 4508 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4509 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4510 break; 4511 case com.android.internal.R.styleable.View_labelFor: 4512 setLabelFor(a.getResourceId(attr, NO_ID)); 4513 break; 4514 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4515 if (!a.getBoolean(attr, true)) { 4516 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4517 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4518 } 4519 break; 4520 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4521 if (!a.getBoolean(attr, true)) { 4522 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4523 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4524 } 4525 break; 4526 case R.styleable.View_scrollbars: 4527 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4528 if (scrollbars != SCROLLBARS_NONE) { 4529 viewFlagValues |= scrollbars; 4530 viewFlagMasks |= SCROLLBARS_MASK; 4531 initializeScrollbars = true; 4532 } 4533 break; 4534 //noinspection deprecation 4535 case R.styleable.View_fadingEdge: 4536 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4537 // Ignore the attribute starting with ICS 4538 break; 4539 } 4540 // With builds < ICS, fall through and apply fading edges 4541 case R.styleable.View_requiresFadingEdge: 4542 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4543 if (fadingEdge != FADING_EDGE_NONE) { 4544 viewFlagValues |= fadingEdge; 4545 viewFlagMasks |= FADING_EDGE_MASK; 4546 initializeFadingEdgeInternal(a); 4547 } 4548 break; 4549 case R.styleable.View_scrollbarStyle: 4550 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4551 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4552 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4553 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4554 } 4555 break; 4556 case R.styleable.View_isScrollContainer: 4557 setScrollContainer = true; 4558 if (a.getBoolean(attr, false)) { 4559 setScrollContainer(true); 4560 } 4561 break; 4562 case com.android.internal.R.styleable.View_keepScreenOn: 4563 if (a.getBoolean(attr, false)) { 4564 viewFlagValues |= KEEP_SCREEN_ON; 4565 viewFlagMasks |= KEEP_SCREEN_ON; 4566 } 4567 break; 4568 case R.styleable.View_filterTouchesWhenObscured: 4569 if (a.getBoolean(attr, false)) { 4570 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4571 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4572 } 4573 break; 4574 case R.styleable.View_nextFocusLeft: 4575 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4576 break; 4577 case R.styleable.View_nextFocusRight: 4578 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4579 break; 4580 case R.styleable.View_nextFocusUp: 4581 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4582 break; 4583 case R.styleable.View_nextFocusDown: 4584 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4585 break; 4586 case R.styleable.View_nextFocusForward: 4587 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4588 break; 4589 case R.styleable.View_nextClusterForward: 4590 mNextClusterForwardId = a.getResourceId(attr, View.NO_ID); 4591 break; 4592 case R.styleable.View_minWidth: 4593 mMinWidth = a.getDimensionPixelSize(attr, 0); 4594 break; 4595 case R.styleable.View_minHeight: 4596 mMinHeight = a.getDimensionPixelSize(attr, 0); 4597 break; 4598 case R.styleable.View_onClick: 4599 if (context.isRestricted()) { 4600 throw new IllegalStateException("The android:onClick attribute cannot " 4601 + "be used within a restricted context"); 4602 } 4603 4604 final String handlerName = a.getString(attr); 4605 if (handlerName != null) { 4606 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4607 } 4608 break; 4609 case R.styleable.View_overScrollMode: 4610 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4611 break; 4612 case R.styleable.View_verticalScrollbarPosition: 4613 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4614 break; 4615 case R.styleable.View_layerType: 4616 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4617 break; 4618 case R.styleable.View_textDirection: 4619 // Clear any text direction flag already set 4620 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4621 // Set the text direction flags depending on the value of the attribute 4622 final int textDirection = a.getInt(attr, -1); 4623 if (textDirection != -1) { 4624 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4625 } 4626 break; 4627 case R.styleable.View_textAlignment: 4628 // Clear any text alignment flag already set 4629 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4630 // Set the text alignment flag depending on the value of the attribute 4631 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4632 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4633 break; 4634 case R.styleable.View_importantForAccessibility: 4635 setImportantForAccessibility(a.getInt(attr, 4636 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4637 break; 4638 case R.styleable.View_accessibilityLiveRegion: 4639 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4640 break; 4641 case R.styleable.View_transitionName: 4642 setTransitionName(a.getString(attr)); 4643 break; 4644 case R.styleable.View_nestedScrollingEnabled: 4645 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4646 break; 4647 case R.styleable.View_stateListAnimator: 4648 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4649 a.getResourceId(attr, 0))); 4650 break; 4651 case R.styleable.View_backgroundTint: 4652 // This will get applied later during setBackground(). 4653 if (mBackgroundTint == null) { 4654 mBackgroundTint = new TintInfo(); 4655 } 4656 mBackgroundTint.mTintList = a.getColorStateList( 4657 R.styleable.View_backgroundTint); 4658 mBackgroundTint.mHasTintList = true; 4659 break; 4660 case R.styleable.View_backgroundTintMode: 4661 // This will get applied later during setBackground(). 4662 if (mBackgroundTint == null) { 4663 mBackgroundTint = new TintInfo(); 4664 } 4665 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4666 R.styleable.View_backgroundTintMode, -1), null); 4667 mBackgroundTint.mHasTintMode = true; 4668 break; 4669 case R.styleable.View_outlineProvider: 4670 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4671 PROVIDER_BACKGROUND)); 4672 break; 4673 case R.styleable.View_foreground: 4674 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4675 setForeground(a.getDrawable(attr)); 4676 } 4677 break; 4678 case R.styleable.View_foregroundGravity: 4679 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4680 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4681 } 4682 break; 4683 case R.styleable.View_foregroundTintMode: 4684 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4685 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4686 } 4687 break; 4688 case R.styleable.View_foregroundTint: 4689 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4690 setForegroundTintList(a.getColorStateList(attr)); 4691 } 4692 break; 4693 case R.styleable.View_foregroundInsidePadding: 4694 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4695 if (mForegroundInfo == null) { 4696 mForegroundInfo = new ForegroundInfo(); 4697 } 4698 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4699 mForegroundInfo.mInsidePadding); 4700 } 4701 break; 4702 case R.styleable.View_scrollIndicators: 4703 final int scrollIndicators = 4704 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4705 & SCROLL_INDICATORS_PFLAG3_MASK; 4706 if (scrollIndicators != 0) { 4707 mPrivateFlags3 |= scrollIndicators; 4708 initializeScrollIndicators = true; 4709 } 4710 break; 4711 case R.styleable.View_pointerIcon: 4712 final int resourceId = a.getResourceId(attr, 0); 4713 if (resourceId != 0) { 4714 setPointerIcon(PointerIcon.load( 4715 context.getResources(), resourceId)); 4716 } else { 4717 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 4718 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 4719 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 4720 } 4721 } 4722 break; 4723 case R.styleable.View_forceHasOverlappingRendering: 4724 if (a.peekValue(attr) != null) { 4725 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4726 } 4727 break; 4728 case R.styleable.View_tooltipText: 4729 setTooltipText(a.getText(attr)); 4730 break; 4731 case R.styleable.View_keyboardNavigationCluster: 4732 if (a.peekValue(attr) != null) { 4733 setKeyboardNavigationCluster(a.getBoolean(attr, true)); 4734 } 4735 break; 4736 case R.styleable.View_focusedByDefault: 4737 if (a.peekValue(attr) != null) { 4738 setFocusedByDefault(a.getBoolean(attr, true)); 4739 } 4740 break; 4741 } 4742 } 4743 4744 setOverScrollMode(overScrollMode); 4745 4746 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4747 // the resolved layout direction). Those cached values will be used later during padding 4748 // resolution. 4749 mUserPaddingStart = startPadding; 4750 mUserPaddingEnd = endPadding; 4751 4752 if (background != null) { 4753 setBackground(background); 4754 } 4755 4756 // setBackground above will record that padding is currently provided by the background. 4757 // If we have padding specified via xml, record that here instead and use it. 4758 mLeftPaddingDefined = leftPaddingDefined; 4759 mRightPaddingDefined = rightPaddingDefined; 4760 4761 if (padding >= 0) { 4762 leftPadding = padding; 4763 topPadding = padding; 4764 rightPadding = padding; 4765 bottomPadding = padding; 4766 mUserPaddingLeftInitial = padding; 4767 mUserPaddingRightInitial = padding; 4768 } else { 4769 if (paddingHorizontal >= 0) { 4770 leftPadding = paddingHorizontal; 4771 rightPadding = paddingHorizontal; 4772 mUserPaddingLeftInitial = paddingHorizontal; 4773 mUserPaddingRightInitial = paddingHorizontal; 4774 } 4775 if (paddingVertical >= 0) { 4776 topPadding = paddingVertical; 4777 bottomPadding = paddingVertical; 4778 } 4779 } 4780 4781 if (isRtlCompatibilityMode()) { 4782 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4783 // left / right padding are used if defined (meaning here nothing to do). If they are not 4784 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4785 // start / end and resolve them as left / right (layout direction is not taken into account). 4786 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4787 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4788 // defined. 4789 if (!mLeftPaddingDefined && startPaddingDefined) { 4790 leftPadding = startPadding; 4791 } 4792 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4793 if (!mRightPaddingDefined && endPaddingDefined) { 4794 rightPadding = endPadding; 4795 } 4796 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4797 } else { 4798 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4799 // values defined. Otherwise, left /right values are used. 4800 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4801 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4802 // defined. 4803 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4804 4805 if (mLeftPaddingDefined && !hasRelativePadding) { 4806 mUserPaddingLeftInitial = leftPadding; 4807 } 4808 if (mRightPaddingDefined && !hasRelativePadding) { 4809 mUserPaddingRightInitial = rightPadding; 4810 } 4811 } 4812 4813 internalSetPadding( 4814 mUserPaddingLeftInitial, 4815 topPadding >= 0 ? topPadding : mPaddingTop, 4816 mUserPaddingRightInitial, 4817 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4818 4819 if (viewFlagMasks != 0) { 4820 setFlags(viewFlagValues, viewFlagMasks); 4821 } 4822 4823 if (initializeScrollbars) { 4824 initializeScrollbarsInternal(a); 4825 } 4826 4827 if (initializeScrollIndicators) { 4828 initializeScrollIndicatorsInternal(); 4829 } 4830 4831 a.recycle(); 4832 4833 // Needs to be called after mViewFlags is set 4834 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4835 recomputePadding(); 4836 } 4837 4838 if (x != 0 || y != 0) { 4839 scrollTo(x, y); 4840 } 4841 4842 if (transformSet) { 4843 setTranslationX(tx); 4844 setTranslationY(ty); 4845 setTranslationZ(tz); 4846 setElevation(elevation); 4847 setRotation(rotation); 4848 setRotationX(rotationX); 4849 setRotationY(rotationY); 4850 setScaleX(sx); 4851 setScaleY(sy); 4852 } 4853 4854 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4855 setScrollContainer(true); 4856 } 4857 4858 computeOpaqueFlags(); 4859 } 4860 4861 /** 4862 * An implementation of OnClickListener that attempts to lazily load a 4863 * named click handling method from a parent or ancestor context. 4864 */ 4865 private static class DeclaredOnClickListener implements OnClickListener { 4866 private final View mHostView; 4867 private final String mMethodName; 4868 4869 private Method mResolvedMethod; 4870 private Context mResolvedContext; 4871 4872 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4873 mHostView = hostView; 4874 mMethodName = methodName; 4875 } 4876 4877 @Override 4878 public void onClick(@NonNull View v) { 4879 if (mResolvedMethod == null) { 4880 resolveMethod(mHostView.getContext(), mMethodName); 4881 } 4882 4883 try { 4884 mResolvedMethod.invoke(mResolvedContext, v); 4885 } catch (IllegalAccessException e) { 4886 throw new IllegalStateException( 4887 "Could not execute non-public method for android:onClick", e); 4888 } catch (InvocationTargetException e) { 4889 throw new IllegalStateException( 4890 "Could not execute method for android:onClick", e); 4891 } 4892 } 4893 4894 @NonNull 4895 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4896 while (context != null) { 4897 try { 4898 if (!context.isRestricted()) { 4899 final Method method = context.getClass().getMethod(mMethodName, View.class); 4900 if (method != null) { 4901 mResolvedMethod = method; 4902 mResolvedContext = context; 4903 return; 4904 } 4905 } 4906 } catch (NoSuchMethodException e) { 4907 // Failed to find method, keep searching up the hierarchy. 4908 } 4909 4910 if (context instanceof ContextWrapper) { 4911 context = ((ContextWrapper) context).getBaseContext(); 4912 } else { 4913 // Can't search up the hierarchy, null out and fail. 4914 context = null; 4915 } 4916 } 4917 4918 final int id = mHostView.getId(); 4919 final String idText = id == NO_ID ? "" : " with id '" 4920 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4921 throw new IllegalStateException("Could not find method " + mMethodName 4922 + "(View) in a parent or ancestor Context for android:onClick " 4923 + "attribute defined on view " + mHostView.getClass() + idText); 4924 } 4925 } 4926 4927 /** 4928 * Non-public constructor for use in testing 4929 */ 4930 View() { 4931 mResources = null; 4932 mRenderNode = RenderNode.create(getClass().getName(), this); 4933 } 4934 4935 final boolean debugDraw() { 4936 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout; 4937 } 4938 4939 private static SparseArray<String> getAttributeMap() { 4940 if (mAttributeMap == null) { 4941 mAttributeMap = new SparseArray<>(); 4942 } 4943 return mAttributeMap; 4944 } 4945 4946 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4947 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4948 final int indexCount = t.getIndexCount(); 4949 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4950 4951 int i = 0; 4952 4953 // Store raw XML attributes. 4954 for (int j = 0; j < attrsCount; ++j) { 4955 attributes[i] = attrs.getAttributeName(j); 4956 attributes[i + 1] = attrs.getAttributeValue(j); 4957 i += 2; 4958 } 4959 4960 // Store resolved styleable attributes. 4961 final Resources res = t.getResources(); 4962 final SparseArray<String> attributeMap = getAttributeMap(); 4963 for (int j = 0; j < indexCount; ++j) { 4964 final int index = t.getIndex(j); 4965 if (!t.hasValueOrEmpty(index)) { 4966 // Value is undefined. Skip it. 4967 continue; 4968 } 4969 4970 final int resourceId = t.getResourceId(index, 0); 4971 if (resourceId == 0) { 4972 // Value is not a reference. Skip it. 4973 continue; 4974 } 4975 4976 String resourceName = attributeMap.get(resourceId); 4977 if (resourceName == null) { 4978 try { 4979 resourceName = res.getResourceName(resourceId); 4980 } catch (Resources.NotFoundException e) { 4981 resourceName = "0x" + Integer.toHexString(resourceId); 4982 } 4983 attributeMap.put(resourceId, resourceName); 4984 } 4985 4986 attributes[i] = resourceName; 4987 attributes[i + 1] = t.getString(index); 4988 i += 2; 4989 } 4990 4991 // Trim to fit contents. 4992 final String[] trimmed = new String[i]; 4993 System.arraycopy(attributes, 0, trimmed, 0, i); 4994 mAttributes = trimmed; 4995 } 4996 4997 public String toString() { 4998 StringBuilder out = new StringBuilder(128); 4999 out.append(getClass().getName()); 5000 out.append('{'); 5001 out.append(Integer.toHexString(System.identityHashCode(this))); 5002 out.append(' '); 5003 switch (mViewFlags&VISIBILITY_MASK) { 5004 case VISIBLE: out.append('V'); break; 5005 case INVISIBLE: out.append('I'); break; 5006 case GONE: out.append('G'); break; 5007 default: out.append('.'); break; 5008 } 5009 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 5010 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 5011 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 5012 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 5013 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 5014 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 5015 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 5016 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 5017 out.append(' '); 5018 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 5019 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 5020 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 5021 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 5022 out.append('p'); 5023 } else { 5024 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 5025 } 5026 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 5027 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 5028 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 5029 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 5030 out.append(' '); 5031 out.append(mLeft); 5032 out.append(','); 5033 out.append(mTop); 5034 out.append('-'); 5035 out.append(mRight); 5036 out.append(','); 5037 out.append(mBottom); 5038 final int id = getId(); 5039 if (id != NO_ID) { 5040 out.append(" #"); 5041 out.append(Integer.toHexString(id)); 5042 final Resources r = mResources; 5043 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 5044 try { 5045 String pkgname; 5046 switch (id&0xff000000) { 5047 case 0x7f000000: 5048 pkgname="app"; 5049 break; 5050 case 0x01000000: 5051 pkgname="android"; 5052 break; 5053 default: 5054 pkgname = r.getResourcePackageName(id); 5055 break; 5056 } 5057 String typename = r.getResourceTypeName(id); 5058 String entryname = r.getResourceEntryName(id); 5059 out.append(" "); 5060 out.append(pkgname); 5061 out.append(":"); 5062 out.append(typename); 5063 out.append("/"); 5064 out.append(entryname); 5065 } catch (Resources.NotFoundException e) { 5066 } 5067 } 5068 } 5069 out.append("}"); 5070 return out.toString(); 5071 } 5072 5073 /** 5074 * <p> 5075 * Initializes the fading edges from a given set of styled attributes. This 5076 * method should be called by subclasses that need fading edges and when an 5077 * instance of these subclasses is created programmatically rather than 5078 * being inflated from XML. This method is automatically called when the XML 5079 * is inflated. 5080 * </p> 5081 * 5082 * @param a the styled attributes set to initialize the fading edges from 5083 * 5084 * @removed 5085 */ 5086 protected void initializeFadingEdge(TypedArray a) { 5087 // This method probably shouldn't have been included in the SDK to begin with. 5088 // It relies on 'a' having been initialized using an attribute filter array that is 5089 // not publicly available to the SDK. The old method has been renamed 5090 // to initializeFadingEdgeInternal and hidden for framework use only; 5091 // this one initializes using defaults to make it safe to call for apps. 5092 5093 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5094 5095 initializeFadingEdgeInternal(arr); 5096 5097 arr.recycle(); 5098 } 5099 5100 /** 5101 * <p> 5102 * Initializes the fading edges from a given set of styled attributes. This 5103 * method should be called by subclasses that need fading edges and when an 5104 * instance of these subclasses is created programmatically rather than 5105 * being inflated from XML. This method is automatically called when the XML 5106 * is inflated. 5107 * </p> 5108 * 5109 * @param a the styled attributes set to initialize the fading edges from 5110 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 5111 */ 5112 protected void initializeFadingEdgeInternal(TypedArray a) { 5113 initScrollCache(); 5114 5115 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 5116 R.styleable.View_fadingEdgeLength, 5117 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 5118 } 5119 5120 /** 5121 * Returns the size of the vertical faded edges used to indicate that more 5122 * content in this view is visible. 5123 * 5124 * @return The size in pixels of the vertical faded edge or 0 if vertical 5125 * faded edges are not enabled for this view. 5126 * @attr ref android.R.styleable#View_fadingEdgeLength 5127 */ 5128 public int getVerticalFadingEdgeLength() { 5129 if (isVerticalFadingEdgeEnabled()) { 5130 ScrollabilityCache cache = mScrollCache; 5131 if (cache != null) { 5132 return cache.fadingEdgeLength; 5133 } 5134 } 5135 return 0; 5136 } 5137 5138 /** 5139 * Set the size of the faded edge used to indicate that more content in this 5140 * view is available. Will not change whether the fading edge is enabled; use 5141 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 5142 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 5143 * for the vertical or horizontal fading edges. 5144 * 5145 * @param length The size in pixels of the faded edge used to indicate that more 5146 * content in this view is visible. 5147 */ 5148 public void setFadingEdgeLength(int length) { 5149 initScrollCache(); 5150 mScrollCache.fadingEdgeLength = length; 5151 } 5152 5153 /** 5154 * Returns the size of the horizontal faded edges used to indicate that more 5155 * content in this view is visible. 5156 * 5157 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 5158 * faded edges are not enabled for this view. 5159 * @attr ref android.R.styleable#View_fadingEdgeLength 5160 */ 5161 public int getHorizontalFadingEdgeLength() { 5162 if (isHorizontalFadingEdgeEnabled()) { 5163 ScrollabilityCache cache = mScrollCache; 5164 if (cache != null) { 5165 return cache.fadingEdgeLength; 5166 } 5167 } 5168 return 0; 5169 } 5170 5171 /** 5172 * Returns the width of the vertical scrollbar. 5173 * 5174 * @return The width in pixels of the vertical scrollbar or 0 if there 5175 * is no vertical scrollbar. 5176 */ 5177 public int getVerticalScrollbarWidth() { 5178 ScrollabilityCache cache = mScrollCache; 5179 if (cache != null) { 5180 ScrollBarDrawable scrollBar = cache.scrollBar; 5181 if (scrollBar != null) { 5182 int size = scrollBar.getSize(true); 5183 if (size <= 0) { 5184 size = cache.scrollBarSize; 5185 } 5186 return size; 5187 } 5188 return 0; 5189 } 5190 return 0; 5191 } 5192 5193 /** 5194 * Returns the height of the horizontal scrollbar. 5195 * 5196 * @return The height in pixels of the horizontal scrollbar or 0 if 5197 * there is no horizontal scrollbar. 5198 */ 5199 protected int getHorizontalScrollbarHeight() { 5200 ScrollabilityCache cache = mScrollCache; 5201 if (cache != null) { 5202 ScrollBarDrawable scrollBar = cache.scrollBar; 5203 if (scrollBar != null) { 5204 int size = scrollBar.getSize(false); 5205 if (size <= 0) { 5206 size = cache.scrollBarSize; 5207 } 5208 return size; 5209 } 5210 return 0; 5211 } 5212 return 0; 5213 } 5214 5215 /** 5216 * <p> 5217 * Initializes the scrollbars from a given set of styled attributes. This 5218 * method should be called by subclasses that need scrollbars and when an 5219 * instance of these subclasses is created programmatically rather than 5220 * being inflated from XML. This method is automatically called when the XML 5221 * is inflated. 5222 * </p> 5223 * 5224 * @param a the styled attributes set to initialize the scrollbars from 5225 * 5226 * @removed 5227 */ 5228 protected void initializeScrollbars(TypedArray a) { 5229 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5230 // using the View filter array which is not available to the SDK. As such, internal 5231 // framework usage now uses initializeScrollbarsInternal and we grab a default 5232 // TypedArray with the right filter instead here. 5233 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5234 5235 initializeScrollbarsInternal(arr); 5236 5237 // We ignored the method parameter. Recycle the one we actually did use. 5238 arr.recycle(); 5239 } 5240 5241 /** 5242 * <p> 5243 * Initializes the scrollbars from a given set of styled attributes. This 5244 * method should be called by subclasses that need scrollbars and when an 5245 * instance of these subclasses is created programmatically rather than 5246 * being inflated from XML. This method is automatically called when the XML 5247 * is inflated. 5248 * </p> 5249 * 5250 * @param a the styled attributes set to initialize the scrollbars from 5251 * @hide 5252 */ 5253 protected void initializeScrollbarsInternal(TypedArray a) { 5254 initScrollCache(); 5255 5256 final ScrollabilityCache scrollabilityCache = mScrollCache; 5257 5258 if (scrollabilityCache.scrollBar == null) { 5259 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5260 scrollabilityCache.scrollBar.setState(getDrawableState()); 5261 scrollabilityCache.scrollBar.setCallback(this); 5262 } 5263 5264 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5265 5266 if (!fadeScrollbars) { 5267 scrollabilityCache.state = ScrollabilityCache.ON; 5268 } 5269 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5270 5271 5272 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5273 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5274 .getScrollBarFadeDuration()); 5275 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5276 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5277 ViewConfiguration.getScrollDefaultDelay()); 5278 5279 5280 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5281 com.android.internal.R.styleable.View_scrollbarSize, 5282 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5283 5284 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5285 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5286 5287 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5288 if (thumb != null) { 5289 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5290 } 5291 5292 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5293 false); 5294 if (alwaysDraw) { 5295 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5296 } 5297 5298 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5299 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5300 5301 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5302 if (thumb != null) { 5303 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5304 } 5305 5306 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5307 false); 5308 if (alwaysDraw) { 5309 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5310 } 5311 5312 // Apply layout direction to the new Drawables if needed 5313 final int layoutDirection = getLayoutDirection(); 5314 if (track != null) { 5315 track.setLayoutDirection(layoutDirection); 5316 } 5317 if (thumb != null) { 5318 thumb.setLayoutDirection(layoutDirection); 5319 } 5320 5321 // Re-apply user/background padding so that scrollbar(s) get added 5322 resolvePadding(); 5323 } 5324 5325 private void initializeScrollIndicatorsInternal() { 5326 // Some day maybe we'll break this into top/left/start/etc. and let the 5327 // client control it. Until then, you can have any scroll indicator you 5328 // want as long as it's a 1dp foreground-colored rectangle. 5329 if (mScrollIndicatorDrawable == null) { 5330 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5331 } 5332 } 5333 5334 /** 5335 * <p> 5336 * Initalizes the scrollability cache if necessary. 5337 * </p> 5338 */ 5339 private void initScrollCache() { 5340 if (mScrollCache == null) { 5341 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5342 } 5343 } 5344 5345 private ScrollabilityCache getScrollCache() { 5346 initScrollCache(); 5347 return mScrollCache; 5348 } 5349 5350 /** 5351 * Set the position of the vertical scroll bar. Should be one of 5352 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5353 * {@link #SCROLLBAR_POSITION_RIGHT}. 5354 * 5355 * @param position Where the vertical scroll bar should be positioned. 5356 */ 5357 public void setVerticalScrollbarPosition(int position) { 5358 if (mVerticalScrollbarPosition != position) { 5359 mVerticalScrollbarPosition = position; 5360 computeOpaqueFlags(); 5361 resolvePadding(); 5362 } 5363 } 5364 5365 /** 5366 * @return The position where the vertical scroll bar will show, if applicable. 5367 * @see #setVerticalScrollbarPosition(int) 5368 */ 5369 public int getVerticalScrollbarPosition() { 5370 return mVerticalScrollbarPosition; 5371 } 5372 5373 boolean isOnScrollbar(float x, float y) { 5374 if (mScrollCache == null) { 5375 return false; 5376 } 5377 x += getScrollX(); 5378 y += getScrollY(); 5379 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5380 final Rect bounds = mScrollCache.mScrollBarBounds; 5381 getVerticalScrollBarBounds(bounds); 5382 if (bounds.contains((int)x, (int)y)) { 5383 return true; 5384 } 5385 } 5386 if (isHorizontalScrollBarEnabled()) { 5387 final Rect bounds = mScrollCache.mScrollBarBounds; 5388 getHorizontalScrollBarBounds(bounds); 5389 if (bounds.contains((int)x, (int)y)) { 5390 return true; 5391 } 5392 } 5393 return false; 5394 } 5395 5396 boolean isOnScrollbarThumb(float x, float y) { 5397 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5398 } 5399 5400 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5401 if (mScrollCache == null) { 5402 return false; 5403 } 5404 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5405 x += getScrollX(); 5406 y += getScrollY(); 5407 final Rect bounds = mScrollCache.mScrollBarBounds; 5408 getVerticalScrollBarBounds(bounds); 5409 final int range = computeVerticalScrollRange(); 5410 final int offset = computeVerticalScrollOffset(); 5411 final int extent = computeVerticalScrollExtent(); 5412 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5413 extent, range); 5414 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5415 extent, range, offset); 5416 final int thumbTop = bounds.top + thumbOffset; 5417 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5418 && y <= thumbTop + thumbLength) { 5419 return true; 5420 } 5421 } 5422 return false; 5423 } 5424 5425 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5426 if (mScrollCache == null) { 5427 return false; 5428 } 5429 if (isHorizontalScrollBarEnabled()) { 5430 x += getScrollX(); 5431 y += getScrollY(); 5432 final Rect bounds = mScrollCache.mScrollBarBounds; 5433 getHorizontalScrollBarBounds(bounds); 5434 final int range = computeHorizontalScrollRange(); 5435 final int offset = computeHorizontalScrollOffset(); 5436 final int extent = computeHorizontalScrollExtent(); 5437 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5438 extent, range); 5439 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5440 extent, range, offset); 5441 final int thumbLeft = bounds.left + thumbOffset; 5442 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5443 && y <= bounds.bottom) { 5444 return true; 5445 } 5446 } 5447 return false; 5448 } 5449 5450 boolean isDraggingScrollBar() { 5451 return mScrollCache != null 5452 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5453 } 5454 5455 /** 5456 * Sets the state of all scroll indicators. 5457 * <p> 5458 * See {@link #setScrollIndicators(int, int)} for usage information. 5459 * 5460 * @param indicators a bitmask of indicators that should be enabled, or 5461 * {@code 0} to disable all indicators 5462 * @see #setScrollIndicators(int, int) 5463 * @see #getScrollIndicators() 5464 * @attr ref android.R.styleable#View_scrollIndicators 5465 */ 5466 public void setScrollIndicators(@ScrollIndicators int indicators) { 5467 setScrollIndicators(indicators, 5468 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5469 } 5470 5471 /** 5472 * Sets the state of the scroll indicators specified by the mask. To change 5473 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5474 * <p> 5475 * When a scroll indicator is enabled, it will be displayed if the view 5476 * can scroll in the direction of the indicator. 5477 * <p> 5478 * Multiple indicator types may be enabled or disabled by passing the 5479 * logical OR of the desired types. If multiple types are specified, they 5480 * will all be set to the same enabled state. 5481 * <p> 5482 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5483 * 5484 * @param indicators the indicator direction, or the logical OR of multiple 5485 * indicator directions. One or more of: 5486 * <ul> 5487 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5488 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5489 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5490 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5491 * <li>{@link #SCROLL_INDICATOR_START}</li> 5492 * <li>{@link #SCROLL_INDICATOR_END}</li> 5493 * </ul> 5494 * @see #setScrollIndicators(int) 5495 * @see #getScrollIndicators() 5496 * @attr ref android.R.styleable#View_scrollIndicators 5497 */ 5498 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5499 // Shift and sanitize mask. 5500 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5501 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5502 5503 // Shift and mask indicators. 5504 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5505 indicators &= mask; 5506 5507 // Merge with non-masked flags. 5508 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5509 5510 if (mPrivateFlags3 != updatedFlags) { 5511 mPrivateFlags3 = updatedFlags; 5512 5513 if (indicators != 0) { 5514 initializeScrollIndicatorsInternal(); 5515 } 5516 invalidate(); 5517 } 5518 } 5519 5520 /** 5521 * Returns a bitmask representing the enabled scroll indicators. 5522 * <p> 5523 * For example, if the top and left scroll indicators are enabled and all 5524 * other indicators are disabled, the return value will be 5525 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5526 * <p> 5527 * To check whether the bottom scroll indicator is enabled, use the value 5528 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5529 * 5530 * @return a bitmask representing the enabled scroll indicators 5531 */ 5532 @ScrollIndicators 5533 public int getScrollIndicators() { 5534 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5535 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5536 } 5537 5538 ListenerInfo getListenerInfo() { 5539 if (mListenerInfo != null) { 5540 return mListenerInfo; 5541 } 5542 mListenerInfo = new ListenerInfo(); 5543 return mListenerInfo; 5544 } 5545 5546 /** 5547 * Register a callback to be invoked when the scroll X or Y positions of 5548 * this view change. 5549 * <p> 5550 * <b>Note:</b> Some views handle scrolling independently from View and may 5551 * have their own separate listeners for scroll-type events. For example, 5552 * {@link android.widget.ListView ListView} allows clients to register an 5553 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5554 * to listen for changes in list scroll position. 5555 * 5556 * @param l The listener to notify when the scroll X or Y position changes. 5557 * @see android.view.View#getScrollX() 5558 * @see android.view.View#getScrollY() 5559 */ 5560 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5561 getListenerInfo().mOnScrollChangeListener = l; 5562 } 5563 5564 /** 5565 * Register a callback to be invoked when focus of this view changed. 5566 * 5567 * @param l The callback that will run. 5568 */ 5569 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5570 getListenerInfo().mOnFocusChangeListener = l; 5571 } 5572 5573 /** 5574 * Add a listener that will be called when the bounds of the view change due to 5575 * layout processing. 5576 * 5577 * @param listener The listener that will be called when layout bounds change. 5578 */ 5579 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5580 ListenerInfo li = getListenerInfo(); 5581 if (li.mOnLayoutChangeListeners == null) { 5582 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5583 } 5584 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5585 li.mOnLayoutChangeListeners.add(listener); 5586 } 5587 } 5588 5589 /** 5590 * Remove a listener for layout changes. 5591 * 5592 * @param listener The listener for layout bounds change. 5593 */ 5594 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5595 ListenerInfo li = mListenerInfo; 5596 if (li == null || li.mOnLayoutChangeListeners == null) { 5597 return; 5598 } 5599 li.mOnLayoutChangeListeners.remove(listener); 5600 } 5601 5602 /** 5603 * Add a listener for attach state changes. 5604 * 5605 * This listener will be called whenever this view is attached or detached 5606 * from a window. Remove the listener using 5607 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5608 * 5609 * @param listener Listener to attach 5610 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5611 */ 5612 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5613 ListenerInfo li = getListenerInfo(); 5614 if (li.mOnAttachStateChangeListeners == null) { 5615 li.mOnAttachStateChangeListeners 5616 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5617 } 5618 li.mOnAttachStateChangeListeners.add(listener); 5619 } 5620 5621 /** 5622 * Remove a listener for attach state changes. The listener will receive no further 5623 * notification of window attach/detach events. 5624 * 5625 * @param listener Listener to remove 5626 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5627 */ 5628 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5629 ListenerInfo li = mListenerInfo; 5630 if (li == null || li.mOnAttachStateChangeListeners == null) { 5631 return; 5632 } 5633 li.mOnAttachStateChangeListeners.remove(listener); 5634 } 5635 5636 /** 5637 * Returns the focus-change callback registered for this view. 5638 * 5639 * @return The callback, or null if one is not registered. 5640 */ 5641 public OnFocusChangeListener getOnFocusChangeListener() { 5642 ListenerInfo li = mListenerInfo; 5643 return li != null ? li.mOnFocusChangeListener : null; 5644 } 5645 5646 /** 5647 * Register a callback to be invoked when this view is clicked. If this view is not 5648 * clickable, it becomes clickable. 5649 * 5650 * @param l The callback that will run 5651 * 5652 * @see #setClickable(boolean) 5653 */ 5654 public void setOnClickListener(@Nullable OnClickListener l) { 5655 if (!isClickable()) { 5656 setClickable(true); 5657 } 5658 getListenerInfo().mOnClickListener = l; 5659 } 5660 5661 /** 5662 * Return whether this view has an attached OnClickListener. Returns 5663 * true if there is a listener, false if there is none. 5664 */ 5665 public boolean hasOnClickListeners() { 5666 ListenerInfo li = mListenerInfo; 5667 return (li != null && li.mOnClickListener != null); 5668 } 5669 5670 /** 5671 * Register a callback to be invoked when this view is clicked and held. If this view is not 5672 * long clickable, it becomes long clickable. 5673 * 5674 * @param l The callback that will run 5675 * 5676 * @see #setLongClickable(boolean) 5677 */ 5678 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5679 if (!isLongClickable()) { 5680 setLongClickable(true); 5681 } 5682 getListenerInfo().mOnLongClickListener = l; 5683 } 5684 5685 /** 5686 * Register a callback to be invoked when this view is context clicked. If the view is not 5687 * context clickable, it becomes context clickable. 5688 * 5689 * @param l The callback that will run 5690 * @see #setContextClickable(boolean) 5691 */ 5692 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5693 if (!isContextClickable()) { 5694 setContextClickable(true); 5695 } 5696 getListenerInfo().mOnContextClickListener = l; 5697 } 5698 5699 /** 5700 * Register a callback to be invoked when the context menu for this view is 5701 * being built. If this view is not long clickable, it becomes long clickable. 5702 * 5703 * @param l The callback that will run 5704 * 5705 */ 5706 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5707 if (!isLongClickable()) { 5708 setLongClickable(true); 5709 } 5710 getListenerInfo().mOnCreateContextMenuListener = l; 5711 } 5712 5713 /** 5714 * Set an observer to collect stats for each frame rendered for this view. 5715 * 5716 * @hide 5717 */ 5718 public void addFrameMetricsListener(Window window, 5719 Window.OnFrameMetricsAvailableListener listener, 5720 Handler handler) { 5721 if (mAttachInfo != null) { 5722 if (mAttachInfo.mThreadedRenderer != null) { 5723 if (mFrameMetricsObservers == null) { 5724 mFrameMetricsObservers = new ArrayList<>(); 5725 } 5726 5727 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5728 handler.getLooper(), listener); 5729 mFrameMetricsObservers.add(fmo); 5730 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 5731 } else { 5732 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5733 } 5734 } else { 5735 if (mFrameMetricsObservers == null) { 5736 mFrameMetricsObservers = new ArrayList<>(); 5737 } 5738 5739 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5740 handler.getLooper(), listener); 5741 mFrameMetricsObservers.add(fmo); 5742 } 5743 } 5744 5745 /** 5746 * Remove observer configured to collect frame stats for this view. 5747 * 5748 * @hide 5749 */ 5750 public void removeFrameMetricsListener( 5751 Window.OnFrameMetricsAvailableListener listener) { 5752 ThreadedRenderer renderer = getThreadedRenderer(); 5753 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5754 if (fmo == null) { 5755 throw new IllegalArgumentException( 5756 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 5757 } 5758 5759 if (mFrameMetricsObservers != null) { 5760 mFrameMetricsObservers.remove(fmo); 5761 if (renderer != null) { 5762 renderer.removeFrameMetricsObserver(fmo); 5763 } 5764 } 5765 } 5766 5767 private void registerPendingFrameMetricsObservers() { 5768 if (mFrameMetricsObservers != null) { 5769 ThreadedRenderer renderer = getThreadedRenderer(); 5770 if (renderer != null) { 5771 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5772 renderer.addFrameMetricsObserver(fmo); 5773 } 5774 } else { 5775 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5776 } 5777 } 5778 } 5779 5780 private FrameMetricsObserver findFrameMetricsObserver( 5781 Window.OnFrameMetricsAvailableListener listener) { 5782 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5783 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5784 if (observer.mListener == listener) { 5785 return observer; 5786 } 5787 } 5788 5789 return null; 5790 } 5791 5792 /** 5793 * Call this view's OnClickListener, if it is defined. Performs all normal 5794 * actions associated with clicking: reporting accessibility event, playing 5795 * a sound, etc. 5796 * 5797 * @return True there was an assigned OnClickListener that was called, false 5798 * otherwise is returned. 5799 */ 5800 public boolean performClick() { 5801 final boolean result; 5802 final ListenerInfo li = mListenerInfo; 5803 if (li != null && li.mOnClickListener != null) { 5804 playSoundEffect(SoundEffectConstants.CLICK); 5805 li.mOnClickListener.onClick(this); 5806 result = true; 5807 } else { 5808 result = false; 5809 } 5810 5811 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5812 return result; 5813 } 5814 5815 /** 5816 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5817 * this only calls the listener, and does not do any associated clicking 5818 * actions like reporting an accessibility event. 5819 * 5820 * @return True there was an assigned OnClickListener that was called, false 5821 * otherwise is returned. 5822 */ 5823 public boolean callOnClick() { 5824 ListenerInfo li = mListenerInfo; 5825 if (li != null && li.mOnClickListener != null) { 5826 li.mOnClickListener.onClick(this); 5827 return true; 5828 } 5829 return false; 5830 } 5831 5832 /** 5833 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5834 * context menu if the OnLongClickListener did not consume the event. 5835 * 5836 * @return {@code true} if one of the above receivers consumed the event, 5837 * {@code false} otherwise 5838 */ 5839 public boolean performLongClick() { 5840 return performLongClickInternal(mLongClickX, mLongClickY); 5841 } 5842 5843 /** 5844 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5845 * context menu if the OnLongClickListener did not consume the event, 5846 * anchoring it to an (x,y) coordinate. 5847 * 5848 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5849 * to disable anchoring 5850 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5851 * to disable anchoring 5852 * @return {@code true} if one of the above receivers consumed the event, 5853 * {@code false} otherwise 5854 */ 5855 public boolean performLongClick(float x, float y) { 5856 mLongClickX = x; 5857 mLongClickY = y; 5858 final boolean handled = performLongClick(); 5859 mLongClickX = Float.NaN; 5860 mLongClickY = Float.NaN; 5861 return handled; 5862 } 5863 5864 /** 5865 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5866 * context menu if the OnLongClickListener did not consume the event, 5867 * optionally anchoring it to an (x,y) coordinate. 5868 * 5869 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5870 * to disable anchoring 5871 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5872 * to disable anchoring 5873 * @return {@code true} if one of the above receivers consumed the event, 5874 * {@code false} otherwise 5875 */ 5876 private boolean performLongClickInternal(float x, float y) { 5877 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5878 5879 boolean handled = false; 5880 final ListenerInfo li = mListenerInfo; 5881 if (li != null && li.mOnLongClickListener != null) { 5882 handled = li.mOnLongClickListener.onLongClick(View.this); 5883 } 5884 if (!handled) { 5885 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5886 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5887 } 5888 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 5889 if (!handled) { 5890 handled = showLongClickTooltip((int) x, (int) y); 5891 } 5892 } 5893 if (handled) { 5894 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5895 } 5896 return handled; 5897 } 5898 5899 /** 5900 * Call this view's OnContextClickListener, if it is defined. 5901 * 5902 * @param x the x coordinate of the context click 5903 * @param y the y coordinate of the context click 5904 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5905 * otherwise. 5906 */ 5907 public boolean performContextClick(float x, float y) { 5908 return performContextClick(); 5909 } 5910 5911 /** 5912 * Call this view's OnContextClickListener, if it is defined. 5913 * 5914 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5915 * otherwise. 5916 */ 5917 public boolean performContextClick() { 5918 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5919 5920 boolean handled = false; 5921 ListenerInfo li = mListenerInfo; 5922 if (li != null && li.mOnContextClickListener != null) { 5923 handled = li.mOnContextClickListener.onContextClick(View.this); 5924 } 5925 if (handled) { 5926 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5927 } 5928 return handled; 5929 } 5930 5931 /** 5932 * Performs button-related actions during a touch down event. 5933 * 5934 * @param event The event. 5935 * @return True if the down was consumed. 5936 * 5937 * @hide 5938 */ 5939 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5940 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5941 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5942 showContextMenu(event.getX(), event.getY()); 5943 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5944 return true; 5945 } 5946 return false; 5947 } 5948 5949 /** 5950 * Shows the context menu for this view. 5951 * 5952 * @return {@code true} if the context menu was shown, {@code false} 5953 * otherwise 5954 * @see #showContextMenu(float, float) 5955 */ 5956 public boolean showContextMenu() { 5957 return getParent().showContextMenuForChild(this); 5958 } 5959 5960 /** 5961 * Shows the context menu for this view anchored to the specified 5962 * view-relative coordinate. 5963 * 5964 * @param x the X coordinate in pixels relative to the view to which the 5965 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5966 * @param y the Y coordinate in pixels relative to the view to which the 5967 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5968 * @return {@code true} if the context menu was shown, {@code false} 5969 * otherwise 5970 */ 5971 public boolean showContextMenu(float x, float y) { 5972 return getParent().showContextMenuForChild(this, x, y); 5973 } 5974 5975 /** 5976 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5977 * 5978 * @param callback Callback that will control the lifecycle of the action mode 5979 * @return The new action mode if it is started, null otherwise 5980 * 5981 * @see ActionMode 5982 * @see #startActionMode(android.view.ActionMode.Callback, int) 5983 */ 5984 public ActionMode startActionMode(ActionMode.Callback callback) { 5985 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5986 } 5987 5988 /** 5989 * Start an action mode with the given type. 5990 * 5991 * @param callback Callback that will control the lifecycle of the action mode 5992 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5993 * @return The new action mode if it is started, null otherwise 5994 * 5995 * @see ActionMode 5996 */ 5997 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5998 ViewParent parent = getParent(); 5999 if (parent == null) return null; 6000 try { 6001 return parent.startActionModeForChild(this, callback, type); 6002 } catch (AbstractMethodError ame) { 6003 // Older implementations of custom views might not implement this. 6004 return parent.startActionModeForChild(this, callback); 6005 } 6006 } 6007 6008 /** 6009 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 6010 * Context, creating a unique View identifier to retrieve the result. 6011 * 6012 * @param intent The Intent to be started. 6013 * @param requestCode The request code to use. 6014 * @hide 6015 */ 6016 public void startActivityForResult(Intent intent, int requestCode) { 6017 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 6018 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 6019 } 6020 6021 /** 6022 * If this View corresponds to the calling who, dispatches the activity result. 6023 * @param who The identifier for the targeted View to receive the result. 6024 * @param requestCode The integer request code originally supplied to 6025 * startActivityForResult(), allowing you to identify who this 6026 * result came from. 6027 * @param resultCode The integer result code returned by the child activity 6028 * through its setResult(). 6029 * @param data An Intent, which can return result data to the caller 6030 * (various data can be attached to Intent "extras"). 6031 * @return {@code true} if the activity result was dispatched. 6032 * @hide 6033 */ 6034 public boolean dispatchActivityResult( 6035 String who, int requestCode, int resultCode, Intent data) { 6036 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 6037 onActivityResult(requestCode, resultCode, data); 6038 mStartActivityRequestWho = null; 6039 return true; 6040 } 6041 return false; 6042 } 6043 6044 /** 6045 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 6046 * 6047 * @param requestCode The integer request code originally supplied to 6048 * startActivityForResult(), allowing you to identify who this 6049 * result came from. 6050 * @param resultCode The integer result code returned by the child activity 6051 * through its setResult(). 6052 * @param data An Intent, which can return result data to the caller 6053 * (various data can be attached to Intent "extras"). 6054 * @hide 6055 */ 6056 public void onActivityResult(int requestCode, int resultCode, Intent data) { 6057 // Do nothing. 6058 } 6059 6060 /** 6061 * Register a callback to be invoked when a hardware key is pressed in this view. 6062 * Key presses in software input methods will generally not trigger the methods of 6063 * this listener. 6064 * @param l the key listener to attach to this view 6065 */ 6066 public void setOnKeyListener(OnKeyListener l) { 6067 getListenerInfo().mOnKeyListener = l; 6068 } 6069 6070 /** 6071 * Register a callback to be invoked when a touch event is sent to this view. 6072 * @param l the touch listener to attach to this view 6073 */ 6074 public void setOnTouchListener(OnTouchListener l) { 6075 getListenerInfo().mOnTouchListener = l; 6076 } 6077 6078 /** 6079 * Register a callback to be invoked when a generic motion event is sent to this view. 6080 * @param l the generic motion listener to attach to this view 6081 */ 6082 public void setOnGenericMotionListener(OnGenericMotionListener l) { 6083 getListenerInfo().mOnGenericMotionListener = l; 6084 } 6085 6086 /** 6087 * Register a callback to be invoked when a hover event is sent to this view. 6088 * @param l the hover listener to attach to this view 6089 */ 6090 public void setOnHoverListener(OnHoverListener l) { 6091 getListenerInfo().mOnHoverListener = l; 6092 } 6093 6094 /** 6095 * Register a drag event listener callback object for this View. The parameter is 6096 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 6097 * View, the system calls the 6098 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 6099 * @param l An implementation of {@link android.view.View.OnDragListener}. 6100 */ 6101 public void setOnDragListener(OnDragListener l) { 6102 getListenerInfo().mOnDragListener = l; 6103 } 6104 6105 /** 6106 * Give this view focus. This will cause 6107 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 6108 * 6109 * Note: this does not check whether this {@link View} should get focus, it just 6110 * gives it focus no matter what. It should only be called internally by framework 6111 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 6112 * 6113 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 6114 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 6115 * focus moved when requestFocus() is called. It may not always 6116 * apply, in which case use the default View.FOCUS_DOWN. 6117 * @param previouslyFocusedRect The rectangle of the view that had focus 6118 * prior in this View's coordinate system. 6119 */ 6120 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 6121 if (DBG) { 6122 System.out.println(this + " requestFocus()"); 6123 } 6124 6125 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 6126 mPrivateFlags |= PFLAG_FOCUSED; 6127 6128 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 6129 6130 if (mParent != null) { 6131 mParent.requestChildFocus(this, this); 6132 if (mParent instanceof ViewGroup) { 6133 ((ViewGroup) mParent).setDefaultFocus(this); 6134 } 6135 } 6136 6137 if (mAttachInfo != null) { 6138 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 6139 } 6140 6141 onFocusChanged(true, direction, previouslyFocusedRect); 6142 refreshDrawableState(); 6143 } 6144 } 6145 6146 /** 6147 * Sets this view's preference for reveal behavior when it gains focus. 6148 * 6149 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 6150 * this view would prefer to be brought fully into view when it gains focus. 6151 * For example, a text field that a user is meant to type into. Other views such 6152 * as scrolling containers may prefer to opt-out of this behavior.</p> 6153 * 6154 * <p>The default value for views is true, though subclasses may change this 6155 * based on their preferred behavior.</p> 6156 * 6157 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 6158 * 6159 * @see #getRevealOnFocusHint() 6160 */ 6161 public final void setRevealOnFocusHint(boolean revealOnFocus) { 6162 if (revealOnFocus) { 6163 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 6164 } else { 6165 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 6166 } 6167 } 6168 6169 /** 6170 * Returns this view's preference for reveal behavior when it gains focus. 6171 * 6172 * <p>When this method returns true for a child view requesting focus, ancestor 6173 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 6174 * should make a best effort to make the newly focused child fully visible to the user. 6175 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 6176 * other properties affecting visibility to the user as part of the focus change.</p> 6177 * 6178 * @return true if this view would prefer to become fully visible when it gains focus, 6179 * false if it would prefer not to disrupt scroll positioning 6180 * 6181 * @see #setRevealOnFocusHint(boolean) 6182 */ 6183 public final boolean getRevealOnFocusHint() { 6184 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 6185 } 6186 6187 /** 6188 * Populates <code>outRect</code> with the hotspot bounds. By default, 6189 * the hotspot bounds are identical to the screen bounds. 6190 * 6191 * @param outRect rect to populate with hotspot bounds 6192 * @hide Only for internal use by views and widgets. 6193 */ 6194 public void getHotspotBounds(Rect outRect) { 6195 final Drawable background = getBackground(); 6196 if (background != null) { 6197 background.getHotspotBounds(outRect); 6198 } else { 6199 getBoundsOnScreen(outRect); 6200 } 6201 } 6202 6203 /** 6204 * Request that a rectangle of this view be visible on the screen, 6205 * scrolling if necessary just enough. 6206 * 6207 * <p>A View should call this if it maintains some notion of which part 6208 * of its content is interesting. For example, a text editing view 6209 * should call this when its cursor moves. 6210 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6211 * It should not be affected by which part of the View is currently visible or its scroll 6212 * position. 6213 * 6214 * @param rectangle The rectangle in the View's content coordinate space 6215 * @return Whether any parent scrolled. 6216 */ 6217 public boolean requestRectangleOnScreen(Rect rectangle) { 6218 return requestRectangleOnScreen(rectangle, false); 6219 } 6220 6221 /** 6222 * Request that a rectangle of this view be visible on the screen, 6223 * scrolling if necessary just enough. 6224 * 6225 * <p>A View should call this if it maintains some notion of which part 6226 * of its content is interesting. For example, a text editing view 6227 * should call this when its cursor moves. 6228 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6229 * It should not be affected by which part of the View is currently visible or its scroll 6230 * position. 6231 * <p>When <code>immediate</code> is set to true, scrolling will not be 6232 * animated. 6233 * 6234 * @param rectangle The rectangle in the View's content coordinate space 6235 * @param immediate True to forbid animated scrolling, false otherwise 6236 * @return Whether any parent scrolled. 6237 */ 6238 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 6239 if (mParent == null) { 6240 return false; 6241 } 6242 6243 View child = this; 6244 6245 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6246 position.set(rectangle); 6247 6248 ViewParent parent = mParent; 6249 boolean scrolled = false; 6250 while (parent != null) { 6251 rectangle.set((int) position.left, (int) position.top, 6252 (int) position.right, (int) position.bottom); 6253 6254 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6255 6256 if (!(parent instanceof View)) { 6257 break; 6258 } 6259 6260 // move it from child's content coordinate space to parent's content coordinate space 6261 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6262 6263 child = (View) parent; 6264 parent = child.getParent(); 6265 } 6266 6267 return scrolled; 6268 } 6269 6270 /** 6271 * Called when this view wants to give up focus. If focus is cleared 6272 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6273 * <p> 6274 * <strong>Note:</strong> When a View clears focus the framework is trying 6275 * to give focus to the first focusable View from the top. Hence, if this 6276 * View is the first from the top that can take focus, then all callbacks 6277 * related to clearing focus will be invoked after which the framework will 6278 * give focus to this view. 6279 * </p> 6280 */ 6281 public void clearFocus() { 6282 if (DBG) { 6283 System.out.println(this + " clearFocus()"); 6284 } 6285 6286 clearFocusInternal(null, true, true); 6287 } 6288 6289 /** 6290 * Clears focus from the view, optionally propagating the change up through 6291 * the parent hierarchy and requesting that the root view place new focus. 6292 * 6293 * @param propagate whether to propagate the change up through the parent 6294 * hierarchy 6295 * @param refocus when propagate is true, specifies whether to request the 6296 * root view place new focus 6297 */ 6298 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6299 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6300 mPrivateFlags &= ~PFLAG_FOCUSED; 6301 6302 if (propagate && mParent != null) { 6303 mParent.clearChildFocus(this); 6304 } 6305 6306 onFocusChanged(false, 0, null); 6307 refreshDrawableState(); 6308 6309 if (propagate && (!refocus || !rootViewRequestFocus())) { 6310 notifyGlobalFocusCleared(this); 6311 } 6312 } 6313 } 6314 6315 void notifyGlobalFocusCleared(View oldFocus) { 6316 if (oldFocus != null && mAttachInfo != null) { 6317 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6318 } 6319 } 6320 6321 boolean rootViewRequestFocus() { 6322 final View root = getRootView(); 6323 return root != null && root.requestFocus(); 6324 } 6325 6326 /** 6327 * Called internally by the view system when a new view is getting focus. 6328 * This is what clears the old focus. 6329 * <p> 6330 * <b>NOTE:</b> The parent view's focused child must be updated manually 6331 * after calling this method. Otherwise, the view hierarchy may be left in 6332 * an inconstent state. 6333 */ 6334 void unFocus(View focused) { 6335 if (DBG) { 6336 System.out.println(this + " unFocus()"); 6337 } 6338 6339 clearFocusInternal(focused, false, false); 6340 } 6341 6342 /** 6343 * Returns true if this view has focus itself, or is the ancestor of the 6344 * view that has focus. 6345 * 6346 * @return True if this view has or contains focus, false otherwise. 6347 */ 6348 @ViewDebug.ExportedProperty(category = "focus") 6349 public boolean hasFocus() { 6350 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6351 } 6352 6353 /** 6354 * Returns true if this view is focusable or if it contains a reachable View 6355 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6356 * is a View whose parents do not block descendants focus. 6357 * 6358 * Only {@link #VISIBLE} views are considered focusable. 6359 * 6360 * @return True if the view is focusable or if the view contains a focusable 6361 * View, false otherwise. 6362 * 6363 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6364 * @see ViewGroup#getTouchscreenBlocksFocus() 6365 */ 6366 public boolean hasFocusable() { 6367 if (!isFocusableInTouchMode()) { 6368 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6369 final ViewGroup g = (ViewGroup) p; 6370 if (g.shouldBlockFocusForTouchscreen()) { 6371 return false; 6372 } 6373 } 6374 } 6375 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6376 } 6377 6378 /** 6379 * Called by the view system when the focus state of this view changes. 6380 * When the focus change event is caused by directional navigation, direction 6381 * and previouslyFocusedRect provide insight into where the focus is coming from. 6382 * When overriding, be sure to call up through to the super class so that 6383 * the standard focus handling will occur. 6384 * 6385 * @param gainFocus True if the View has focus; false otherwise. 6386 * @param direction The direction focus has moved when requestFocus() 6387 * is called to give this view focus. Values are 6388 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6389 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6390 * It may not always apply, in which case use the default. 6391 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6392 * system, of the previously focused view. If applicable, this will be 6393 * passed in as finer grained information about where the focus is coming 6394 * from (in addition to direction). Will be <code>null</code> otherwise. 6395 */ 6396 @CallSuper 6397 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6398 @Nullable Rect previouslyFocusedRect) { 6399 if (gainFocus) { 6400 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6401 } else { 6402 notifyViewAccessibilityStateChangedIfNeeded( 6403 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6404 } 6405 6406 InputMethodManager imm = InputMethodManager.peekInstance(); 6407 if (!gainFocus) { 6408 if (isPressed()) { 6409 setPressed(false); 6410 } 6411 if (imm != null && mAttachInfo != null 6412 && mAttachInfo.mHasWindowFocus) { 6413 imm.focusOut(this); 6414 } 6415 onFocusLost(); 6416 } else if (imm != null && mAttachInfo != null 6417 && mAttachInfo.mHasWindowFocus) { 6418 imm.focusIn(this); 6419 } 6420 6421 invalidate(true); 6422 ListenerInfo li = mListenerInfo; 6423 if (li != null && li.mOnFocusChangeListener != null) { 6424 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6425 } 6426 6427 if (mAttachInfo != null) { 6428 mAttachInfo.mKeyDispatchState.reset(this); 6429 } 6430 } 6431 6432 /** 6433 * Sends an accessibility event of the given type. If accessibility is 6434 * not enabled this method has no effect. The default implementation calls 6435 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6436 * to populate information about the event source (this View), then calls 6437 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6438 * populate the text content of the event source including its descendants, 6439 * and last calls 6440 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6441 * on its parent to request sending of the event to interested parties. 6442 * <p> 6443 * If an {@link AccessibilityDelegate} has been specified via calling 6444 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6445 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6446 * responsible for handling this call. 6447 * </p> 6448 * 6449 * @param eventType The type of the event to send, as defined by several types from 6450 * {@link android.view.accessibility.AccessibilityEvent}, such as 6451 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6452 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6453 * 6454 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6455 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6456 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6457 * @see AccessibilityDelegate 6458 */ 6459 public void sendAccessibilityEvent(int eventType) { 6460 if (mAccessibilityDelegate != null) { 6461 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6462 } else { 6463 sendAccessibilityEventInternal(eventType); 6464 } 6465 } 6466 6467 /** 6468 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6469 * {@link AccessibilityEvent} to make an announcement which is related to some 6470 * sort of a context change for which none of the events representing UI transitions 6471 * is a good fit. For example, announcing a new page in a book. If accessibility 6472 * is not enabled this method does nothing. 6473 * 6474 * @param text The announcement text. 6475 */ 6476 public void announceForAccessibility(CharSequence text) { 6477 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6478 AccessibilityEvent event = AccessibilityEvent.obtain( 6479 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6480 onInitializeAccessibilityEvent(event); 6481 event.getText().add(text); 6482 event.setContentDescription(null); 6483 mParent.requestSendAccessibilityEvent(this, event); 6484 } 6485 } 6486 6487 /** 6488 * @see #sendAccessibilityEvent(int) 6489 * 6490 * Note: Called from the default {@link AccessibilityDelegate}. 6491 * 6492 * @hide 6493 */ 6494 public void sendAccessibilityEventInternal(int eventType) { 6495 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6496 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6497 } 6498 } 6499 6500 /** 6501 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6502 * takes as an argument an empty {@link AccessibilityEvent} and does not 6503 * perform a check whether accessibility is enabled. 6504 * <p> 6505 * If an {@link AccessibilityDelegate} has been specified via calling 6506 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6507 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6508 * is responsible for handling this call. 6509 * </p> 6510 * 6511 * @param event The event to send. 6512 * 6513 * @see #sendAccessibilityEvent(int) 6514 */ 6515 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6516 if (mAccessibilityDelegate != null) { 6517 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6518 } else { 6519 sendAccessibilityEventUncheckedInternal(event); 6520 } 6521 } 6522 6523 /** 6524 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6525 * 6526 * Note: Called from the default {@link AccessibilityDelegate}. 6527 * 6528 * @hide 6529 */ 6530 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6531 if (!isShown()) { 6532 return; 6533 } 6534 onInitializeAccessibilityEvent(event); 6535 // Only a subset of accessibility events populates text content. 6536 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6537 dispatchPopulateAccessibilityEvent(event); 6538 } 6539 // In the beginning we called #isShown(), so we know that getParent() is not null. 6540 getParent().requestSendAccessibilityEvent(this, event); 6541 } 6542 6543 /** 6544 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6545 * to its children for adding their text content to the event. Note that the 6546 * event text is populated in a separate dispatch path since we add to the 6547 * event not only the text of the source but also the text of all its descendants. 6548 * A typical implementation will call 6549 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6550 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6551 * on each child. Override this method if custom population of the event text 6552 * content is required. 6553 * <p> 6554 * If an {@link AccessibilityDelegate} has been specified via calling 6555 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6556 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6557 * is responsible for handling this call. 6558 * </p> 6559 * <p> 6560 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6561 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6562 * </p> 6563 * 6564 * @param event The event. 6565 * 6566 * @return True if the event population was completed. 6567 */ 6568 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6569 if (mAccessibilityDelegate != null) { 6570 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6571 } else { 6572 return dispatchPopulateAccessibilityEventInternal(event); 6573 } 6574 } 6575 6576 /** 6577 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6578 * 6579 * Note: Called from the default {@link AccessibilityDelegate}. 6580 * 6581 * @hide 6582 */ 6583 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6584 onPopulateAccessibilityEvent(event); 6585 return false; 6586 } 6587 6588 /** 6589 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6590 * giving a chance to this View to populate the accessibility event with its 6591 * text content. While this method is free to modify event 6592 * attributes other than text content, doing so should normally be performed in 6593 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6594 * <p> 6595 * Example: Adding formatted date string to an accessibility event in addition 6596 * to the text added by the super implementation: 6597 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6598 * super.onPopulateAccessibilityEvent(event); 6599 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6600 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6601 * mCurrentDate.getTimeInMillis(), flags); 6602 * event.getText().add(selectedDateUtterance); 6603 * }</pre> 6604 * <p> 6605 * If an {@link AccessibilityDelegate} has been specified via calling 6606 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6607 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6608 * is responsible for handling this call. 6609 * </p> 6610 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6611 * information to the event, in case the default implementation has basic information to add. 6612 * </p> 6613 * 6614 * @param event The accessibility event which to populate. 6615 * 6616 * @see #sendAccessibilityEvent(int) 6617 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6618 */ 6619 @CallSuper 6620 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6621 if (mAccessibilityDelegate != null) { 6622 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6623 } else { 6624 onPopulateAccessibilityEventInternal(event); 6625 } 6626 } 6627 6628 /** 6629 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6630 * 6631 * Note: Called from the default {@link AccessibilityDelegate}. 6632 * 6633 * @hide 6634 */ 6635 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6636 } 6637 6638 /** 6639 * Initializes an {@link AccessibilityEvent} with information about 6640 * this View which is the event source. In other words, the source of 6641 * an accessibility event is the view whose state change triggered firing 6642 * the event. 6643 * <p> 6644 * Example: Setting the password property of an event in addition 6645 * to properties set by the super implementation: 6646 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6647 * super.onInitializeAccessibilityEvent(event); 6648 * event.setPassword(true); 6649 * }</pre> 6650 * <p> 6651 * If an {@link AccessibilityDelegate} has been specified via calling 6652 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6653 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6654 * is responsible for handling this call. 6655 * </p> 6656 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6657 * information to the event, in case the default implementation has basic information to add. 6658 * </p> 6659 * @param event The event to initialize. 6660 * 6661 * @see #sendAccessibilityEvent(int) 6662 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6663 */ 6664 @CallSuper 6665 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6666 if (mAccessibilityDelegate != null) { 6667 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6668 } else { 6669 onInitializeAccessibilityEventInternal(event); 6670 } 6671 } 6672 6673 /** 6674 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6675 * 6676 * Note: Called from the default {@link AccessibilityDelegate}. 6677 * 6678 * @hide 6679 */ 6680 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6681 event.setSource(this); 6682 event.setClassName(getAccessibilityClassName()); 6683 event.setPackageName(getContext().getPackageName()); 6684 event.setEnabled(isEnabled()); 6685 event.setContentDescription(mContentDescription); 6686 6687 switch (event.getEventType()) { 6688 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6689 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6690 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6691 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6692 event.setItemCount(focusablesTempList.size()); 6693 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6694 if (mAttachInfo != null) { 6695 focusablesTempList.clear(); 6696 } 6697 } break; 6698 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6699 CharSequence text = getIterableTextForAccessibility(); 6700 if (text != null && text.length() > 0) { 6701 event.setFromIndex(getAccessibilitySelectionStart()); 6702 event.setToIndex(getAccessibilitySelectionEnd()); 6703 event.setItemCount(text.length()); 6704 } 6705 } break; 6706 } 6707 } 6708 6709 /** 6710 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6711 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6712 * This method is responsible for obtaining an accessibility node info from a 6713 * pool of reusable instances and calling 6714 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6715 * initialize the former. 6716 * <p> 6717 * Note: The client is responsible for recycling the obtained instance by calling 6718 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6719 * </p> 6720 * 6721 * @return A populated {@link AccessibilityNodeInfo}. 6722 * 6723 * @see AccessibilityNodeInfo 6724 */ 6725 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6726 if (mAccessibilityDelegate != null) { 6727 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6728 } else { 6729 return createAccessibilityNodeInfoInternal(); 6730 } 6731 } 6732 6733 /** 6734 * @see #createAccessibilityNodeInfo() 6735 * 6736 * @hide 6737 */ 6738 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6739 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6740 if (provider != null) { 6741 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6742 } else { 6743 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6744 onInitializeAccessibilityNodeInfo(info); 6745 return info; 6746 } 6747 } 6748 6749 /** 6750 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6751 * The base implementation sets: 6752 * <ul> 6753 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6754 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6755 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6756 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6757 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6758 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6759 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6760 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6761 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6762 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6763 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6764 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6765 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6766 * </ul> 6767 * <p> 6768 * Subclasses should override this method, call the super implementation, 6769 * and set additional attributes. 6770 * </p> 6771 * <p> 6772 * If an {@link AccessibilityDelegate} has been specified via calling 6773 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6774 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6775 * is responsible for handling this call. 6776 * </p> 6777 * 6778 * @param info The instance to initialize. 6779 */ 6780 @CallSuper 6781 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6782 if (mAccessibilityDelegate != null) { 6783 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6784 } else { 6785 onInitializeAccessibilityNodeInfoInternal(info); 6786 } 6787 } 6788 6789 /** 6790 * Gets the location of this view in screen coordinates. 6791 * 6792 * @param outRect The output location 6793 * @hide 6794 */ 6795 public void getBoundsOnScreen(Rect outRect) { 6796 getBoundsOnScreen(outRect, false); 6797 } 6798 6799 /** 6800 * Gets the location of this view in screen coordinates. 6801 * 6802 * @param outRect The output location 6803 * @param clipToParent Whether to clip child bounds to the parent ones. 6804 * @hide 6805 */ 6806 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6807 if (mAttachInfo == null) { 6808 return; 6809 } 6810 6811 RectF position = mAttachInfo.mTmpTransformRect; 6812 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6813 6814 if (!hasIdentityMatrix()) { 6815 getMatrix().mapRect(position); 6816 } 6817 6818 position.offset(mLeft, mTop); 6819 6820 ViewParent parent = mParent; 6821 while (parent instanceof View) { 6822 View parentView = (View) parent; 6823 6824 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6825 6826 if (clipToParent) { 6827 position.left = Math.max(position.left, 0); 6828 position.top = Math.max(position.top, 0); 6829 position.right = Math.min(position.right, parentView.getWidth()); 6830 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6831 } 6832 6833 if (!parentView.hasIdentityMatrix()) { 6834 parentView.getMatrix().mapRect(position); 6835 } 6836 6837 position.offset(parentView.mLeft, parentView.mTop); 6838 6839 parent = parentView.mParent; 6840 } 6841 6842 if (parent instanceof ViewRootImpl) { 6843 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6844 position.offset(0, -viewRootImpl.mCurScrollY); 6845 } 6846 6847 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6848 6849 outRect.set(Math.round(position.left), Math.round(position.top), 6850 Math.round(position.right), Math.round(position.bottom)); 6851 } 6852 6853 /** 6854 * Return the class name of this object to be used for accessibility purposes. 6855 * Subclasses should only override this if they are implementing something that 6856 * should be seen as a completely new class of view when used by accessibility, 6857 * unrelated to the class it is deriving from. This is used to fill in 6858 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6859 */ 6860 public CharSequence getAccessibilityClassName() { 6861 return View.class.getName(); 6862 } 6863 6864 /** 6865 * Called when assist structure is being retrieved from a view as part of 6866 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6867 * @param structure Fill in with structured view data. The default implementation 6868 * fills in all data that can be inferred from the view itself. 6869 */ 6870 public void onProvideStructure(ViewStructure structure) { 6871 onProvideStructureForAssistOrAutoFill(structure, 0); 6872 } 6873 6874 /** 6875 * Called when assist structure is being retrieved from a view as part of an auto-fill request. 6876 * 6877 * <p>The structure must be filled according to the request type, which is set in the 6878 * {@code flags} parameter - see the documentation on each flag for more details. 6879 * 6880 * @param structure Fill in with structured view data. The default implementation 6881 * fills in all data that can be inferred from the view itself. 6882 * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and 6883 * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info). 6884 */ 6885 public void onProvideAutoFillStructure(ViewStructure structure, int flags) { 6886 onProvideStructureForAssistOrAutoFill(structure, flags); 6887 } 6888 6889 private void onProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) { 6890 // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well, 6891 // this method should take a boolean with the type of request. 6892 boolean forAutoFill = (flags 6893 & (View.AUTO_FILL_FLAG_TYPE_FILL 6894 | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0; 6895 final int id = mID; 6896 if (id != NO_ID && !isViewIdGenerated(id)) { 6897 String pkg, type, entry; 6898 try { 6899 final Resources res = getResources(); 6900 entry = res.getResourceEntryName(id); 6901 type = res.getResourceTypeName(id); 6902 pkg = res.getResourcePackageName(id); 6903 } catch (Resources.NotFoundException e) { 6904 entry = type = pkg = null; 6905 } 6906 structure.setId(id, pkg, type, entry); 6907 } else { 6908 structure.setId(id, null, null, null); 6909 } 6910 6911 if (forAutoFill) { 6912 // The auto-fill id needs to be unique, but its value doesn't matter, so it's better to 6913 // reuse the accessibility id to save space. 6914 structure.setAutoFillId(getAccessibilityViewId()); 6915 6916 structure.setAutoFillType(getAutoFillType()); 6917 } 6918 6919 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6920 if (!hasIdentityMatrix()) { 6921 structure.setTransformation(getMatrix()); 6922 } 6923 structure.setElevation(getZ()); 6924 structure.setVisibility(getVisibility()); 6925 structure.setEnabled(isEnabled()); 6926 if (isClickable()) { 6927 structure.setClickable(true); 6928 } 6929 if (isFocusable()) { 6930 structure.setFocusable(true); 6931 } 6932 if (isFocused()) { 6933 structure.setFocused(true); 6934 } 6935 if (isAccessibilityFocused()) { 6936 structure.setAccessibilityFocused(true); 6937 } 6938 if (isSelected()) { 6939 structure.setSelected(true); 6940 } 6941 if (isActivated()) { 6942 structure.setActivated(true); 6943 } 6944 if (isLongClickable()) { 6945 structure.setLongClickable(true); 6946 } 6947 if (this instanceof Checkable) { 6948 structure.setCheckable(true); 6949 if (((Checkable)this).isChecked()) { 6950 structure.setChecked(true); 6951 } 6952 } 6953 if (isContextClickable()) { 6954 structure.setContextClickable(true); 6955 } 6956 structure.setClassName(getAccessibilityClassName().toString()); 6957 structure.setContentDescription(getContentDescription()); 6958 } 6959 6960 /** 6961 * Called when assist structure is being retrieved from a view as part of 6962 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6963 * generate additional virtual structure under this view. The defaullt implementation 6964 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6965 * view's virtual accessibility nodes, if any. You can override this for a more 6966 * optimal implementation providing this data. 6967 */ 6968 public void onProvideVirtualStructure(ViewStructure structure) { 6969 onProvideVirtualStructureForAssistOrAutoFill(structure, 0); 6970 } 6971 6972 /** 6973 * Called when assist structure is being retrieved from a view as part of an auto-fill request 6974 * to generate additional virtual structure under this view. 6975 * 6976 * <p>The defaullt implementation uses {@link #getAccessibilityNodeProvider()} to try to 6977 * generate this from the view's virtual accessibility nodes, if any. You can override this 6978 * for a more optimal implementation providing this data. 6979 * 6980 * <p>The structure must be filled according to the request type, which is set in the 6981 * {@code flags} parameter - see the documentation on each flag for more details. 6982 * 6983 * @param structure Fill in with structured view data. 6984 * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and 6985 * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info). 6986 */ 6987 public void onProvideAutoFillVirtualStructure(ViewStructure structure, int flags) { 6988 onProvideVirtualStructureForAssistOrAutoFill(structure, flags); 6989 } 6990 6991 private void onProvideVirtualStructureForAssistOrAutoFill(ViewStructure structure, int flags) { 6992 // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well, 6993 // this method should take a boolean with the type of request. 6994 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6995 if (provider != null) { 6996 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6997 structure.setChildCount(1); 6998 ViewStructure root = structure.newChild(0); 6999 populateVirtualStructure(root, provider, info, flags); 7000 info.recycle(); 7001 } 7002 } 7003 7004 /** 7005 * Gets the {@link VirtualViewDelegate} responsible for auto-filling the virtual children of 7006 * this view. 7007 * 7008 * <p>By default returns {@code null} but should be overridden when view provides a virtual 7009 * hierachy on {@link OnProvideAssistDataListener} that takes flags used by the AutoFill 7010 * Framework (such as {@link #AUTO_FILL_FLAG_TYPE_FILL} and 7011 * {@link #AUTO_FILL_FLAG_TYPE_SAVE}). 7012 */ 7013 @Nullable 7014 public VirtualViewDelegate getAutoFillVirtualViewDelegate( 7015 @SuppressWarnings("unused") VirtualViewDelegate.Callback callback) { 7016 return null; 7017 } 7018 7019 /** 7020 * Automatically fills the content of this view with the {@code value}. 7021 * 7022 * <p>By default does nothing, but views should override it (and {@link #getAutoFillType()} to 7023 * support the AutoFill Framework. 7024 * 7025 * <p>Typically, it is implemented by: 7026 * 7027 * <ol> 7028 * <li>Call the proper getter method on {@link AutoFillValue} to fetch the actual value. 7029 * <li>Pass the actual value to the equivalent setter in the view. 7030 * <ol> 7031 * 7032 * <p>For example, a text-field view would call: 7033 * 7034 * <pre class="prettyprint"> 7035 * CharSequence text = value.getTextValue(); 7036 * if (text != null) { 7037 * setText(text); 7038 * } 7039 * </pre> 7040 */ 7041 public void autoFill(@SuppressWarnings("unused") AutoFillValue value) { 7042 } 7043 7044 /** 7045 * Describes the auto-fill type that should be used on callas to 7046 * {@link #autoFill(AutoFillValue)} and 7047 * {@link VirtualViewDelegate#autoFill(int, AutoFillValue)}. 7048 * 7049 * <p>By default returns {@code null}, but views should override it (and 7050 * {@link #autoFill(AutoFillValue)} to support the AutoFill Framework. 7051 */ 7052 @Nullable 7053 public AutoFillType getAutoFillType() { 7054 return null; 7055 } 7056 7057 private void populateVirtualStructure(ViewStructure structure, 7058 AccessibilityNodeProvider provider, AccessibilityNodeInfo info, int flags) { 7059 // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well, 7060 // this method should take a boolean with the type of request. 7061 7062 final boolean sanitized = (flags & View.AUTO_FILL_FLAG_TYPE_FILL) != 0; 7063 7064 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 7065 null, null, null); 7066 Rect rect = structure.getTempRect(); 7067 info.getBoundsInParent(rect); 7068 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 7069 structure.setVisibility(VISIBLE); 7070 structure.setEnabled(info.isEnabled()); 7071 if (info.isClickable()) { 7072 structure.setClickable(true); 7073 } 7074 if (info.isFocusable()) { 7075 structure.setFocusable(true); 7076 } 7077 if (info.isFocused()) { 7078 structure.setFocused(true); 7079 } 7080 if (info.isAccessibilityFocused()) { 7081 structure.setAccessibilityFocused(true); 7082 } 7083 if (info.isSelected()) { 7084 structure.setSelected(true); 7085 } 7086 if (info.isLongClickable()) { 7087 structure.setLongClickable(true); 7088 } 7089 if (info.isCheckable()) { 7090 structure.setCheckable(true); 7091 if (info.isChecked()) { 7092 structure.setChecked(true); 7093 } 7094 } 7095 if (info.isContextClickable()) { 7096 structure.setContextClickable(true); 7097 } 7098 CharSequence cname = info.getClassName(); 7099 structure.setClassName(cname != null ? cname.toString() : null); 7100 structure.setContentDescription(info.getContentDescription()); 7101 if (!sanitized && (info.getText() != null || info.getError() != null)) { 7102 // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to 7103 // just set sanitized values (like text coming from resource files), rather than not 7104 // setting it at all. 7105 structure.setText(info.getText(), info.getTextSelectionStart(), 7106 info.getTextSelectionEnd()); 7107 } 7108 final int NCHILDREN = info.getChildCount(); 7109 if (NCHILDREN > 0) { 7110 structure.setChildCount(NCHILDREN); 7111 for (int i=0; i<NCHILDREN; i++) { 7112 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 7113 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 7114 ViewStructure child = structure.newChild(i); 7115 populateVirtualStructure(child, provider, cinfo, flags); 7116 cinfo.recycle(); 7117 } 7118 } 7119 } 7120 7121 /** 7122 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 7123 * implementation calls {@link #onProvideStructure} and 7124 * {@link #onProvideVirtualStructure}. 7125 */ 7126 public void dispatchProvideStructure(ViewStructure structure) { 7127 dispatchProvideStructureForAssistOrAutoFill(structure, 0); 7128 } 7129 7130 /** 7131 * Dispatch creation of {@link ViewStructure} down the hierarchy. 7132 * 7133 * <p>The structure must be filled according to the request type, which is set in the 7134 * {@code flags} parameter - see the documentation on each flag for more details. 7135 * 7136 * <p>The default implementation calls {@link #onProvideAutoFillStructure(ViewStructure, int)} 7137 * and {@link #onProvideAutoFillVirtualStructure(ViewStructure, int)}. 7138 * 7139 * @param structure Fill in with structured view data. 7140 * @param flags optional flags (see {@link #AUTO_FILL_FLAG_TYPE_FILL} and 7141 * {@link #AUTO_FILL_FLAG_TYPE_SAVE} for more info). 7142 */ 7143 public void dispatchProvideAutoFillStructure(ViewStructure structure, int flags) { 7144 dispatchProvideStructureForAssistOrAutoFill(structure, flags); 7145 } 7146 7147 private void dispatchProvideStructureForAssistOrAutoFill(ViewStructure structure, int flags) { 7148 // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well, 7149 // this method should take a boolean with the type of request. 7150 boolean forAutoFill = (flags 7151 & (View.AUTO_FILL_FLAG_TYPE_FILL 7152 | View.AUTO_FILL_FLAG_TYPE_SAVE)) != 0; 7153 7154 boolean blocked = forAutoFill ? isAutoFillBlocked() : isAssistBlocked(); 7155 if (!blocked) { 7156 if (forAutoFill) { 7157 onProvideAutoFillStructure(structure, flags); 7158 onProvideAutoFillVirtualStructure(structure, flags); 7159 } else { 7160 onProvideStructure(structure); 7161 onProvideVirtualStructure(structure); 7162 } 7163 } else { 7164 structure.setClassName(getAccessibilityClassName().toString()); 7165 structure.setAssistBlocked(true); 7166 } 7167 } 7168 7169 /** 7170 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 7171 * 7172 * Note: Called from the default {@link AccessibilityDelegate}. 7173 * 7174 * @hide 7175 */ 7176 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 7177 if (mAttachInfo == null) { 7178 return; 7179 } 7180 7181 Rect bounds = mAttachInfo.mTmpInvalRect; 7182 7183 getDrawingRect(bounds); 7184 info.setBoundsInParent(bounds); 7185 7186 getBoundsOnScreen(bounds, true); 7187 info.setBoundsInScreen(bounds); 7188 7189 ViewParent parent = getParentForAccessibility(); 7190 if (parent instanceof View) { 7191 info.setParent((View) parent); 7192 } 7193 7194 if (mID != View.NO_ID) { 7195 View rootView = getRootView(); 7196 if (rootView == null) { 7197 rootView = this; 7198 } 7199 7200 View label = rootView.findLabelForView(this, mID); 7201 if (label != null) { 7202 info.setLabeledBy(label); 7203 } 7204 7205 if ((mAttachInfo.mAccessibilityFetchFlags 7206 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 7207 && Resources.resourceHasPackage(mID)) { 7208 try { 7209 String viewId = getResources().getResourceName(mID); 7210 info.setViewIdResourceName(viewId); 7211 } catch (Resources.NotFoundException nfe) { 7212 /* ignore */ 7213 } 7214 } 7215 } 7216 7217 if (mLabelForId != View.NO_ID) { 7218 View rootView = getRootView(); 7219 if (rootView == null) { 7220 rootView = this; 7221 } 7222 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 7223 if (labeled != null) { 7224 info.setLabelFor(labeled); 7225 } 7226 } 7227 7228 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 7229 View rootView = getRootView(); 7230 if (rootView == null) { 7231 rootView = this; 7232 } 7233 View next = rootView.findViewInsideOutShouldExist(this, 7234 mAccessibilityTraversalBeforeId); 7235 if (next != null && next.includeForAccessibility()) { 7236 info.setTraversalBefore(next); 7237 } 7238 } 7239 7240 if (mAccessibilityTraversalAfterId != View.NO_ID) { 7241 View rootView = getRootView(); 7242 if (rootView == null) { 7243 rootView = this; 7244 } 7245 View next = rootView.findViewInsideOutShouldExist(this, 7246 mAccessibilityTraversalAfterId); 7247 if (next != null && next.includeForAccessibility()) { 7248 info.setTraversalAfter(next); 7249 } 7250 } 7251 7252 info.setVisibleToUser(isVisibleToUser()); 7253 7254 info.setImportantForAccessibility(isImportantForAccessibility()); 7255 info.setPackageName(mContext.getPackageName()); 7256 info.setClassName(getAccessibilityClassName()); 7257 info.setContentDescription(getContentDescription()); 7258 7259 info.setEnabled(isEnabled()); 7260 info.setClickable(isClickable()); 7261 info.setFocusable(isFocusable()); 7262 info.setFocused(isFocused()); 7263 info.setAccessibilityFocused(isAccessibilityFocused()); 7264 info.setSelected(isSelected()); 7265 info.setLongClickable(isLongClickable()); 7266 info.setContextClickable(isContextClickable()); 7267 info.setLiveRegion(getAccessibilityLiveRegion()); 7268 7269 // TODO: These make sense only if we are in an AdapterView but all 7270 // views can be selected. Maybe from accessibility perspective 7271 // we should report as selectable view in an AdapterView. 7272 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 7273 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 7274 7275 if (isFocusable()) { 7276 if (isFocused()) { 7277 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 7278 } else { 7279 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 7280 } 7281 } 7282 7283 if (!isAccessibilityFocused()) { 7284 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 7285 } else { 7286 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 7287 } 7288 7289 if (isClickable() && isEnabled()) { 7290 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 7291 } 7292 7293 if (isLongClickable() && isEnabled()) { 7294 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 7295 } 7296 7297 if (isContextClickable() && isEnabled()) { 7298 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 7299 } 7300 7301 CharSequence text = getIterableTextForAccessibility(); 7302 if (text != null && text.length() > 0) { 7303 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 7304 7305 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 7306 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 7307 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 7308 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 7309 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 7310 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 7311 } 7312 7313 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 7314 populateAccessibilityNodeInfoDrawingOrderInParent(info); 7315 } 7316 7317 /** 7318 * Determine the order in which this view will be drawn relative to its siblings for a11y 7319 * 7320 * @param info The info whose drawing order should be populated 7321 */ 7322 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 7323 /* 7324 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 7325 * drawing order may not be well-defined, and some Views with custom drawing order may 7326 * not be initialized sufficiently to respond properly getChildDrawingOrder. 7327 */ 7328 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 7329 info.setDrawingOrder(0); 7330 return; 7331 } 7332 int drawingOrderInParent = 1; 7333 // Iterate up the hierarchy if parents are not important for a11y 7334 View viewAtDrawingLevel = this; 7335 final ViewParent parent = getParentForAccessibility(); 7336 while (viewAtDrawingLevel != parent) { 7337 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 7338 if (!(currentParent instanceof ViewGroup)) { 7339 // Should only happen for the Decor 7340 drawingOrderInParent = 0; 7341 break; 7342 } else { 7343 final ViewGroup parentGroup = (ViewGroup) currentParent; 7344 final int childCount = parentGroup.getChildCount(); 7345 if (childCount > 1) { 7346 List<View> preorderedList = parentGroup.buildOrderedChildList(); 7347 if (preorderedList != null) { 7348 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 7349 for (int i = 0; i < childDrawIndex; i++) { 7350 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 7351 } 7352 } else { 7353 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 7354 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 7355 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 7356 .getChildDrawingOrder(childCount, childIndex) : childIndex; 7357 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 7358 if (childDrawIndex != 0) { 7359 for (int i = 0; i < numChildrenToIterate; i++) { 7360 final int otherDrawIndex = (customOrder ? 7361 parentGroup.getChildDrawingOrder(childCount, i) : i); 7362 if (otherDrawIndex < childDrawIndex) { 7363 drawingOrderInParent += 7364 numViewsForAccessibility(parentGroup.getChildAt(i)); 7365 } 7366 } 7367 } 7368 } 7369 } 7370 } 7371 viewAtDrawingLevel = (View) currentParent; 7372 } 7373 info.setDrawingOrder(drawingOrderInParent); 7374 } 7375 7376 private static int numViewsForAccessibility(View view) { 7377 if (view != null) { 7378 if (view.includeForAccessibility()) { 7379 return 1; 7380 } else if (view instanceof ViewGroup) { 7381 return ((ViewGroup) view).getNumChildrenForAccessibility(); 7382 } 7383 } 7384 return 0; 7385 } 7386 7387 private View findLabelForView(View view, int labeledId) { 7388 if (mMatchLabelForPredicate == null) { 7389 mMatchLabelForPredicate = new MatchLabelForPredicate(); 7390 } 7391 mMatchLabelForPredicate.mLabeledId = labeledId; 7392 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 7393 } 7394 7395 /** 7396 * Computes whether this view is visible to the user. Such a view is 7397 * attached, visible, all its predecessors are visible, it is not clipped 7398 * entirely by its predecessors, and has an alpha greater than zero. 7399 * 7400 * @return Whether the view is visible on the screen. 7401 * 7402 * @hide 7403 */ 7404 protected boolean isVisibleToUser() { 7405 return isVisibleToUser(null); 7406 } 7407 7408 /** 7409 * Computes whether the given portion of this view is visible to the user. 7410 * Such a view is attached, visible, all its predecessors are visible, 7411 * has an alpha greater than zero, and the specified portion is not 7412 * clipped entirely by its predecessors. 7413 * 7414 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7415 * <code>null</code>, and the entire view will be tested in this case. 7416 * When <code>true</code> is returned by the function, the actual visible 7417 * region will be stored in this parameter; that is, if boundInView is fully 7418 * contained within the view, no modification will be made, otherwise regions 7419 * outside of the visible area of the view will be clipped. 7420 * 7421 * @return Whether the specified portion of the view is visible on the screen. 7422 * 7423 * @hide 7424 */ 7425 protected boolean isVisibleToUser(Rect boundInView) { 7426 if (mAttachInfo != null) { 7427 // Attached to invisible window means this view is not visible. 7428 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7429 return false; 7430 } 7431 // An invisible predecessor or one with alpha zero means 7432 // that this view is not visible to the user. 7433 Object current = this; 7434 while (current instanceof View) { 7435 View view = (View) current; 7436 // We have attach info so this view is attached and there is no 7437 // need to check whether we reach to ViewRootImpl on the way up. 7438 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7439 view.getVisibility() != VISIBLE) { 7440 return false; 7441 } 7442 current = view.mParent; 7443 } 7444 // Check if the view is entirely covered by its predecessors. 7445 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7446 Point offset = mAttachInfo.mPoint; 7447 if (!getGlobalVisibleRect(visibleRect, offset)) { 7448 return false; 7449 } 7450 // Check if the visible portion intersects the rectangle of interest. 7451 if (boundInView != null) { 7452 visibleRect.offset(-offset.x, -offset.y); 7453 return boundInView.intersect(visibleRect); 7454 } 7455 return true; 7456 } 7457 return false; 7458 } 7459 7460 /** 7461 * Returns the delegate for implementing accessibility support via 7462 * composition. For more details see {@link AccessibilityDelegate}. 7463 * 7464 * @return The delegate, or null if none set. 7465 * 7466 * @hide 7467 */ 7468 public AccessibilityDelegate getAccessibilityDelegate() { 7469 return mAccessibilityDelegate; 7470 } 7471 7472 /** 7473 * Sets a delegate for implementing accessibility support via composition 7474 * (as opposed to inheritance). For more details, see 7475 * {@link AccessibilityDelegate}. 7476 * <p> 7477 * <strong>Note:</strong> On platform versions prior to 7478 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7479 * views in the {@code android.widget.*} package are called <i>before</i> 7480 * host methods. This prevents certain properties such as class name from 7481 * being modified by overriding 7482 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7483 * as any changes will be overwritten by the host class. 7484 * <p> 7485 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7486 * methods are called <i>after</i> host methods, which all properties to be 7487 * modified without being overwritten by the host class. 7488 * 7489 * @param delegate the object to which accessibility method calls should be 7490 * delegated 7491 * @see AccessibilityDelegate 7492 */ 7493 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7494 mAccessibilityDelegate = delegate; 7495 } 7496 7497 /** 7498 * Gets the provider for managing a virtual view hierarchy rooted at this View 7499 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7500 * that explore the window content. 7501 * <p> 7502 * If this method returns an instance, this instance is responsible for managing 7503 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7504 * View including the one representing the View itself. Similarly the returned 7505 * instance is responsible for performing accessibility actions on any virtual 7506 * view or the root view itself. 7507 * </p> 7508 * <p> 7509 * If an {@link AccessibilityDelegate} has been specified via calling 7510 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7511 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7512 * is responsible for handling this call. 7513 * </p> 7514 * 7515 * @return The provider. 7516 * 7517 * @see AccessibilityNodeProvider 7518 */ 7519 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7520 if (mAccessibilityDelegate != null) { 7521 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7522 } else { 7523 return null; 7524 } 7525 } 7526 7527 /** 7528 * Gets the unique identifier of this view on the screen for accessibility purposes. 7529 * 7530 * @return The view accessibility id. 7531 * 7532 * @hide 7533 */ 7534 public int getAccessibilityViewId() { 7535 if (mAccessibilityViewId == NO_ID) { 7536 mAccessibilityViewId = sNextAccessibilityViewId++; 7537 } 7538 return mAccessibilityViewId; 7539 } 7540 7541 /** 7542 * Gets the unique identifier of the window in which this View reseides. 7543 * 7544 * @return The window accessibility id. 7545 * 7546 * @hide 7547 */ 7548 public int getAccessibilityWindowId() { 7549 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7550 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7551 } 7552 7553 /** 7554 * Returns the {@link View}'s content description. 7555 * <p> 7556 * <strong>Note:</strong> Do not override this method, as it will have no 7557 * effect on the content description presented to accessibility services. 7558 * You must call {@link #setContentDescription(CharSequence)} to modify the 7559 * content description. 7560 * 7561 * @return the content description 7562 * @see #setContentDescription(CharSequence) 7563 * @attr ref android.R.styleable#View_contentDescription 7564 */ 7565 @ViewDebug.ExportedProperty(category = "accessibility") 7566 public CharSequence getContentDescription() { 7567 return mContentDescription; 7568 } 7569 7570 /** 7571 * Sets the {@link View}'s content description. 7572 * <p> 7573 * A content description briefly describes the view and is primarily used 7574 * for accessibility support to determine how a view should be presented to 7575 * the user. In the case of a view with no textual representation, such as 7576 * {@link android.widget.ImageButton}, a useful content description 7577 * explains what the view does. For example, an image button with a phone 7578 * icon that is used to place a call may use "Call" as its content 7579 * description. An image of a floppy disk that is used to save a file may 7580 * use "Save". 7581 * 7582 * @param contentDescription The content description. 7583 * @see #getContentDescription() 7584 * @attr ref android.R.styleable#View_contentDescription 7585 */ 7586 @RemotableViewMethod 7587 public void setContentDescription(CharSequence contentDescription) { 7588 if (mContentDescription == null) { 7589 if (contentDescription == null) { 7590 return; 7591 } 7592 } else if (mContentDescription.equals(contentDescription)) { 7593 return; 7594 } 7595 mContentDescription = contentDescription; 7596 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7597 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7598 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7599 notifySubtreeAccessibilityStateChangedIfNeeded(); 7600 } else { 7601 notifyViewAccessibilityStateChangedIfNeeded( 7602 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7603 } 7604 } 7605 7606 /** 7607 * Sets the id of a view before which this one is visited in accessibility traversal. 7608 * A screen-reader must visit the content of this view before the content of the one 7609 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7610 * will traverse the entire content of B before traversing the entire content of A, 7611 * regardles of what traversal strategy it is using. 7612 * <p> 7613 * Views that do not have specified before/after relationships are traversed in order 7614 * determined by the screen-reader. 7615 * </p> 7616 * <p> 7617 * Setting that this view is before a view that is not important for accessibility 7618 * or if this view is not important for accessibility will have no effect as the 7619 * screen-reader is not aware of unimportant views. 7620 * </p> 7621 * 7622 * @param beforeId The id of a view this one precedes in accessibility traversal. 7623 * 7624 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7625 * 7626 * @see #setImportantForAccessibility(int) 7627 */ 7628 @RemotableViewMethod 7629 public void setAccessibilityTraversalBefore(int beforeId) { 7630 if (mAccessibilityTraversalBeforeId == beforeId) { 7631 return; 7632 } 7633 mAccessibilityTraversalBeforeId = beforeId; 7634 notifyViewAccessibilityStateChangedIfNeeded( 7635 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7636 } 7637 7638 /** 7639 * Gets the id of a view before which this one is visited in accessibility traversal. 7640 * 7641 * @return The id of a view this one precedes in accessibility traversal if 7642 * specified, otherwise {@link #NO_ID}. 7643 * 7644 * @see #setAccessibilityTraversalBefore(int) 7645 */ 7646 public int getAccessibilityTraversalBefore() { 7647 return mAccessibilityTraversalBeforeId; 7648 } 7649 7650 /** 7651 * Sets the id of a view after which this one is visited in accessibility traversal. 7652 * A screen-reader must visit the content of the other view before the content of this 7653 * one. For example, if view B is set to be after view A, then a screen-reader 7654 * will traverse the entire content of A before traversing the entire content of B, 7655 * regardles of what traversal strategy it is using. 7656 * <p> 7657 * Views that do not have specified before/after relationships are traversed in order 7658 * determined by the screen-reader. 7659 * </p> 7660 * <p> 7661 * Setting that this view is after a view that is not important for accessibility 7662 * or if this view is not important for accessibility will have no effect as the 7663 * screen-reader is not aware of unimportant views. 7664 * </p> 7665 * 7666 * @param afterId The id of a view this one succedees in accessibility traversal. 7667 * 7668 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7669 * 7670 * @see #setImportantForAccessibility(int) 7671 */ 7672 @RemotableViewMethod 7673 public void setAccessibilityTraversalAfter(int afterId) { 7674 if (mAccessibilityTraversalAfterId == afterId) { 7675 return; 7676 } 7677 mAccessibilityTraversalAfterId = afterId; 7678 notifyViewAccessibilityStateChangedIfNeeded( 7679 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7680 } 7681 7682 /** 7683 * Gets the id of a view after which this one is visited in accessibility traversal. 7684 * 7685 * @return The id of a view this one succeedes in accessibility traversal if 7686 * specified, otherwise {@link #NO_ID}. 7687 * 7688 * @see #setAccessibilityTraversalAfter(int) 7689 */ 7690 public int getAccessibilityTraversalAfter() { 7691 return mAccessibilityTraversalAfterId; 7692 } 7693 7694 /** 7695 * Gets the id of a view for which this view serves as a label for 7696 * accessibility purposes. 7697 * 7698 * @return The labeled view id. 7699 */ 7700 @ViewDebug.ExportedProperty(category = "accessibility") 7701 public int getLabelFor() { 7702 return mLabelForId; 7703 } 7704 7705 /** 7706 * Sets the id of a view for which this view serves as a label for 7707 * accessibility purposes. 7708 * 7709 * @param id The labeled view id. 7710 */ 7711 @RemotableViewMethod 7712 public void setLabelFor(@IdRes int id) { 7713 if (mLabelForId == id) { 7714 return; 7715 } 7716 mLabelForId = id; 7717 if (mLabelForId != View.NO_ID 7718 && mID == View.NO_ID) { 7719 mID = generateViewId(); 7720 } 7721 notifyViewAccessibilityStateChangedIfNeeded( 7722 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7723 } 7724 7725 /** 7726 * Invoked whenever this view loses focus, either by losing window focus or by losing 7727 * focus within its window. This method can be used to clear any state tied to the 7728 * focus. For instance, if a button is held pressed with the trackball and the window 7729 * loses focus, this method can be used to cancel the press. 7730 * 7731 * Subclasses of View overriding this method should always call super.onFocusLost(). 7732 * 7733 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7734 * @see #onWindowFocusChanged(boolean) 7735 * 7736 * @hide pending API council approval 7737 */ 7738 @CallSuper 7739 protected void onFocusLost() { 7740 resetPressedState(); 7741 } 7742 7743 private void resetPressedState() { 7744 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7745 return; 7746 } 7747 7748 if (isPressed()) { 7749 setPressed(false); 7750 7751 if (!mHasPerformedLongPress) { 7752 removeLongPressCallback(); 7753 } 7754 } 7755 } 7756 7757 /** 7758 * Returns true if this view has focus 7759 * 7760 * @return True if this view has focus, false otherwise. 7761 */ 7762 @ViewDebug.ExportedProperty(category = "focus") 7763 public boolean isFocused() { 7764 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7765 } 7766 7767 /** 7768 * Find the view in the hierarchy rooted at this view that currently has 7769 * focus. 7770 * 7771 * @return The view that currently has focus, or null if no focused view can 7772 * be found. 7773 */ 7774 public View findFocus() { 7775 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7776 } 7777 7778 /** 7779 * Indicates whether this view is one of the set of scrollable containers in 7780 * its window. 7781 * 7782 * @return whether this view is one of the set of scrollable containers in 7783 * its window 7784 * 7785 * @attr ref android.R.styleable#View_isScrollContainer 7786 */ 7787 public boolean isScrollContainer() { 7788 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7789 } 7790 7791 /** 7792 * Change whether this view is one of the set of scrollable containers in 7793 * its window. This will be used to determine whether the window can 7794 * resize or must pan when a soft input area is open -- scrollable 7795 * containers allow the window to use resize mode since the container 7796 * will appropriately shrink. 7797 * 7798 * @attr ref android.R.styleable#View_isScrollContainer 7799 */ 7800 public void setScrollContainer(boolean isScrollContainer) { 7801 if (isScrollContainer) { 7802 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7803 mAttachInfo.mScrollContainers.add(this); 7804 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7805 } 7806 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7807 } else { 7808 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7809 mAttachInfo.mScrollContainers.remove(this); 7810 } 7811 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7812 } 7813 } 7814 7815 /** 7816 * Returns the quality of the drawing cache. 7817 * 7818 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7819 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7820 * 7821 * @see #setDrawingCacheQuality(int) 7822 * @see #setDrawingCacheEnabled(boolean) 7823 * @see #isDrawingCacheEnabled() 7824 * 7825 * @attr ref android.R.styleable#View_drawingCacheQuality 7826 */ 7827 @DrawingCacheQuality 7828 public int getDrawingCacheQuality() { 7829 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7830 } 7831 7832 /** 7833 * Set the drawing cache quality of this view. This value is used only when the 7834 * drawing cache is enabled 7835 * 7836 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7837 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7838 * 7839 * @see #getDrawingCacheQuality() 7840 * @see #setDrawingCacheEnabled(boolean) 7841 * @see #isDrawingCacheEnabled() 7842 * 7843 * @attr ref android.R.styleable#View_drawingCacheQuality 7844 */ 7845 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7846 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7847 } 7848 7849 /** 7850 * Returns whether the screen should remain on, corresponding to the current 7851 * value of {@link #KEEP_SCREEN_ON}. 7852 * 7853 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7854 * 7855 * @see #setKeepScreenOn(boolean) 7856 * 7857 * @attr ref android.R.styleable#View_keepScreenOn 7858 */ 7859 public boolean getKeepScreenOn() { 7860 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7861 } 7862 7863 /** 7864 * Controls whether the screen should remain on, modifying the 7865 * value of {@link #KEEP_SCREEN_ON}. 7866 * 7867 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7868 * 7869 * @see #getKeepScreenOn() 7870 * 7871 * @attr ref android.R.styleable#View_keepScreenOn 7872 */ 7873 public void setKeepScreenOn(boolean keepScreenOn) { 7874 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7875 } 7876 7877 /** 7878 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7879 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7880 * 7881 * @attr ref android.R.styleable#View_nextFocusLeft 7882 */ 7883 public int getNextFocusLeftId() { 7884 return mNextFocusLeftId; 7885 } 7886 7887 /** 7888 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7889 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7890 * decide automatically. 7891 * 7892 * @attr ref android.R.styleable#View_nextFocusLeft 7893 */ 7894 public void setNextFocusLeftId(int nextFocusLeftId) { 7895 mNextFocusLeftId = nextFocusLeftId; 7896 } 7897 7898 /** 7899 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7900 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7901 * 7902 * @attr ref android.R.styleable#View_nextFocusRight 7903 */ 7904 public int getNextFocusRightId() { 7905 return mNextFocusRightId; 7906 } 7907 7908 /** 7909 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7910 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7911 * decide automatically. 7912 * 7913 * @attr ref android.R.styleable#View_nextFocusRight 7914 */ 7915 public void setNextFocusRightId(int nextFocusRightId) { 7916 mNextFocusRightId = nextFocusRightId; 7917 } 7918 7919 /** 7920 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7921 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7922 * 7923 * @attr ref android.R.styleable#View_nextFocusUp 7924 */ 7925 public int getNextFocusUpId() { 7926 return mNextFocusUpId; 7927 } 7928 7929 /** 7930 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7931 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7932 * decide automatically. 7933 * 7934 * @attr ref android.R.styleable#View_nextFocusUp 7935 */ 7936 public void setNextFocusUpId(int nextFocusUpId) { 7937 mNextFocusUpId = nextFocusUpId; 7938 } 7939 7940 /** 7941 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7942 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7943 * 7944 * @attr ref android.R.styleable#View_nextFocusDown 7945 */ 7946 public int getNextFocusDownId() { 7947 return mNextFocusDownId; 7948 } 7949 7950 /** 7951 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7952 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7953 * decide automatically. 7954 * 7955 * @attr ref android.R.styleable#View_nextFocusDown 7956 */ 7957 public void setNextFocusDownId(int nextFocusDownId) { 7958 mNextFocusDownId = nextFocusDownId; 7959 } 7960 7961 /** 7962 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7963 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7964 * 7965 * @attr ref android.R.styleable#View_nextFocusForward 7966 */ 7967 public int getNextFocusForwardId() { 7968 return mNextFocusForwardId; 7969 } 7970 7971 /** 7972 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7973 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7974 * decide automatically. 7975 * 7976 * @attr ref android.R.styleable#View_nextFocusForward 7977 */ 7978 public void setNextFocusForwardId(int nextFocusForwardId) { 7979 mNextFocusForwardId = nextFocusForwardId; 7980 } 7981 7982 /** 7983 * Gets the id of the root of the next keyboard navigation cluster. 7984 * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should 7985 * decide automatically. 7986 * 7987 * @attr ref android.R.styleable#View_nextClusterForward 7988 */ 7989 public int getNextClusterForwardId() { 7990 return mNextClusterForwardId; 7991 } 7992 7993 /** 7994 * Sets the id of the view to use as the root of the next keyboard navigation cluster. 7995 * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should 7996 * decide automatically. 7997 * 7998 * @attr ref android.R.styleable#View_nextClusterForward 7999 */ 8000 public void setNextClusterForwardId(int nextClusterForwardId) { 8001 mNextClusterForwardId = nextClusterForwardId; 8002 } 8003 8004 /** 8005 * Returns the visibility of this view and all of its ancestors 8006 * 8007 * @return True if this view and all of its ancestors are {@link #VISIBLE} 8008 */ 8009 public boolean isShown() { 8010 View current = this; 8011 //noinspection ConstantConditions 8012 do { 8013 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8014 return false; 8015 } 8016 ViewParent parent = current.mParent; 8017 if (parent == null) { 8018 return false; // We are not attached to the view root 8019 } 8020 if (!(parent instanceof View)) { 8021 return true; 8022 } 8023 current = (View) parent; 8024 } while (current != null); 8025 8026 return false; 8027 } 8028 8029 /** 8030 * Called by the view hierarchy when the content insets for a window have 8031 * changed, to allow it to adjust its content to fit within those windows. 8032 * The content insets tell you the space that the status bar, input method, 8033 * and other system windows infringe on the application's window. 8034 * 8035 * <p>You do not normally need to deal with this function, since the default 8036 * window decoration given to applications takes care of applying it to the 8037 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 8038 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 8039 * and your content can be placed under those system elements. You can then 8040 * use this method within your view hierarchy if you have parts of your UI 8041 * which you would like to ensure are not being covered. 8042 * 8043 * <p>The default implementation of this method simply applies the content 8044 * insets to the view's padding, consuming that content (modifying the 8045 * insets to be 0), and returning true. This behavior is off by default, but can 8046 * be enabled through {@link #setFitsSystemWindows(boolean)}. 8047 * 8048 * <p>This function's traversal down the hierarchy is depth-first. The same content 8049 * insets object is propagated down the hierarchy, so any changes made to it will 8050 * be seen by all following views (including potentially ones above in 8051 * the hierarchy since this is a depth-first traversal). The first view 8052 * that returns true will abort the entire traversal. 8053 * 8054 * <p>The default implementation works well for a situation where it is 8055 * used with a container that covers the entire window, allowing it to 8056 * apply the appropriate insets to its content on all edges. If you need 8057 * a more complicated layout (such as two different views fitting system 8058 * windows, one on the top of the window, and one on the bottom), 8059 * you can override the method and handle the insets however you would like. 8060 * Note that the insets provided by the framework are always relative to the 8061 * far edges of the window, not accounting for the location of the called view 8062 * within that window. (In fact when this method is called you do not yet know 8063 * where the layout will place the view, as it is done before layout happens.) 8064 * 8065 * <p>Note: unlike many View methods, there is no dispatch phase to this 8066 * call. If you are overriding it in a ViewGroup and want to allow the 8067 * call to continue to your children, you must be sure to call the super 8068 * implementation. 8069 * 8070 * <p>Here is a sample layout that makes use of fitting system windows 8071 * to have controls for a video view placed inside of the window decorations 8072 * that it hides and shows. This can be used with code like the second 8073 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 8074 * 8075 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 8076 * 8077 * @param insets Current content insets of the window. Prior to 8078 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 8079 * the insets or else you and Android will be unhappy. 8080 * 8081 * @return {@code true} if this view applied the insets and it should not 8082 * continue propagating further down the hierarchy, {@code false} otherwise. 8083 * @see #getFitsSystemWindows() 8084 * @see #setFitsSystemWindows(boolean) 8085 * @see #setSystemUiVisibility(int) 8086 * 8087 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 8088 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 8089 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 8090 * to implement handling their own insets. 8091 */ 8092 @Deprecated 8093 protected boolean fitSystemWindows(Rect insets) { 8094 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 8095 if (insets == null) { 8096 // Null insets by definition have already been consumed. 8097 // This call cannot apply insets since there are none to apply, 8098 // so return false. 8099 return false; 8100 } 8101 // If we're not in the process of dispatching the newer apply insets call, 8102 // that means we're not in the compatibility path. Dispatch into the newer 8103 // apply insets path and take things from there. 8104 try { 8105 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 8106 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 8107 } finally { 8108 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 8109 } 8110 } else { 8111 // We're being called from the newer apply insets path. 8112 // Perform the standard fallback behavior. 8113 return fitSystemWindowsInt(insets); 8114 } 8115 } 8116 8117 private boolean fitSystemWindowsInt(Rect insets) { 8118 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 8119 mUserPaddingStart = UNDEFINED_PADDING; 8120 mUserPaddingEnd = UNDEFINED_PADDING; 8121 Rect localInsets = sThreadLocal.get(); 8122 if (localInsets == null) { 8123 localInsets = new Rect(); 8124 sThreadLocal.set(localInsets); 8125 } 8126 boolean res = computeFitSystemWindows(insets, localInsets); 8127 mUserPaddingLeftInitial = localInsets.left; 8128 mUserPaddingRightInitial = localInsets.right; 8129 internalSetPadding(localInsets.left, localInsets.top, 8130 localInsets.right, localInsets.bottom); 8131 return res; 8132 } 8133 return false; 8134 } 8135 8136 /** 8137 * Called when the view should apply {@link WindowInsets} according to its internal policy. 8138 * 8139 * <p>This method should be overridden by views that wish to apply a policy different from or 8140 * in addition to the default behavior. Clients that wish to force a view subtree 8141 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 8142 * 8143 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 8144 * it will be called during dispatch instead of this method. The listener may optionally 8145 * call this method from its own implementation if it wishes to apply the view's default 8146 * insets policy in addition to its own.</p> 8147 * 8148 * <p>Implementations of this method should either return the insets parameter unchanged 8149 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 8150 * that this view applied itself. This allows new inset types added in future platform 8151 * versions to pass through existing implementations unchanged without being erroneously 8152 * consumed.</p> 8153 * 8154 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 8155 * property is set then the view will consume the system window insets and apply them 8156 * as padding for the view.</p> 8157 * 8158 * @param insets Insets to apply 8159 * @return The supplied insets with any applied insets consumed 8160 */ 8161 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 8162 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 8163 // We weren't called from within a direct call to fitSystemWindows, 8164 // call into it as a fallback in case we're in a class that overrides it 8165 // and has logic to perform. 8166 if (fitSystemWindows(insets.getSystemWindowInsets())) { 8167 return insets.consumeSystemWindowInsets(); 8168 } 8169 } else { 8170 // We were called from within a direct call to fitSystemWindows. 8171 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 8172 return insets.consumeSystemWindowInsets(); 8173 } 8174 } 8175 return insets; 8176 } 8177 8178 /** 8179 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 8180 * window insets to this view. The listener's 8181 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 8182 * method will be called instead of the view's 8183 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 8184 * 8185 * @param listener Listener to set 8186 * 8187 * @see #onApplyWindowInsets(WindowInsets) 8188 */ 8189 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 8190 getListenerInfo().mOnApplyWindowInsetsListener = listener; 8191 } 8192 8193 /** 8194 * Request to apply the given window insets to this view or another view in its subtree. 8195 * 8196 * <p>This method should be called by clients wishing to apply insets corresponding to areas 8197 * obscured by window decorations or overlays. This can include the status and navigation bars, 8198 * action bars, input methods and more. New inset categories may be added in the future. 8199 * The method returns the insets provided minus any that were applied by this view or its 8200 * children.</p> 8201 * 8202 * <p>Clients wishing to provide custom behavior should override the 8203 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 8204 * {@link OnApplyWindowInsetsListener} via the 8205 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 8206 * method.</p> 8207 * 8208 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 8209 * </p> 8210 * 8211 * @param insets Insets to apply 8212 * @return The provided insets minus the insets that were consumed 8213 */ 8214 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 8215 try { 8216 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 8217 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 8218 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 8219 } else { 8220 return onApplyWindowInsets(insets); 8221 } 8222 } finally { 8223 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 8224 } 8225 } 8226 8227 /** 8228 * Compute the view's coordinate within the surface. 8229 * 8230 * <p>Computes the coordinates of this view in its surface. The argument 8231 * must be an array of two integers. After the method returns, the array 8232 * contains the x and y location in that order.</p> 8233 * @hide 8234 * @param location an array of two integers in which to hold the coordinates 8235 */ 8236 public void getLocationInSurface(@Size(2) int[] location) { 8237 getLocationInWindow(location); 8238 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 8239 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 8240 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 8241 } 8242 } 8243 8244 /** 8245 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 8246 * only available if the view is attached. 8247 * 8248 * @return WindowInsets from the top of the view hierarchy or null if View is detached 8249 */ 8250 public WindowInsets getRootWindowInsets() { 8251 if (mAttachInfo != null) { 8252 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 8253 } 8254 return null; 8255 } 8256 8257 /** 8258 * @hide Compute the insets that should be consumed by this view and the ones 8259 * that should propagate to those under it. 8260 */ 8261 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 8262 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 8263 || mAttachInfo == null 8264 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 8265 && !mAttachInfo.mOverscanRequested)) { 8266 outLocalInsets.set(inoutInsets); 8267 inoutInsets.set(0, 0, 0, 0); 8268 return true; 8269 } else { 8270 // The application wants to take care of fitting system window for 8271 // the content... however we still need to take care of any overscan here. 8272 final Rect overscan = mAttachInfo.mOverscanInsets; 8273 outLocalInsets.set(overscan); 8274 inoutInsets.left -= overscan.left; 8275 inoutInsets.top -= overscan.top; 8276 inoutInsets.right -= overscan.right; 8277 inoutInsets.bottom -= overscan.bottom; 8278 return false; 8279 } 8280 } 8281 8282 /** 8283 * Compute insets that should be consumed by this view and the ones that should propagate 8284 * to those under it. 8285 * 8286 * @param in Insets currently being processed by this View, likely received as a parameter 8287 * to {@link #onApplyWindowInsets(WindowInsets)}. 8288 * @param outLocalInsets A Rect that will receive the insets that should be consumed 8289 * by this view 8290 * @return Insets that should be passed along to views under this one 8291 */ 8292 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 8293 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 8294 || mAttachInfo == null 8295 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 8296 outLocalInsets.set(in.getSystemWindowInsets()); 8297 return in.consumeSystemWindowInsets(); 8298 } else { 8299 outLocalInsets.set(0, 0, 0, 0); 8300 return in; 8301 } 8302 } 8303 8304 /** 8305 * Sets whether or not this view should account for system screen decorations 8306 * such as the status bar and inset its content; that is, controlling whether 8307 * the default implementation of {@link #fitSystemWindows(Rect)} will be 8308 * executed. See that method for more details. 8309 * 8310 * <p>Note that if you are providing your own implementation of 8311 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 8312 * flag to true -- your implementation will be overriding the default 8313 * implementation that checks this flag. 8314 * 8315 * @param fitSystemWindows If true, then the default implementation of 8316 * {@link #fitSystemWindows(Rect)} will be executed. 8317 * 8318 * @attr ref android.R.styleable#View_fitsSystemWindows 8319 * @see #getFitsSystemWindows() 8320 * @see #fitSystemWindows(Rect) 8321 * @see #setSystemUiVisibility(int) 8322 */ 8323 public void setFitsSystemWindows(boolean fitSystemWindows) { 8324 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 8325 } 8326 8327 /** 8328 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 8329 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 8330 * will be executed. 8331 * 8332 * @return {@code true} if the default implementation of 8333 * {@link #fitSystemWindows(Rect)} will be executed. 8334 * 8335 * @attr ref android.R.styleable#View_fitsSystemWindows 8336 * @see #setFitsSystemWindows(boolean) 8337 * @see #fitSystemWindows(Rect) 8338 * @see #setSystemUiVisibility(int) 8339 */ 8340 @ViewDebug.ExportedProperty 8341 public boolean getFitsSystemWindows() { 8342 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 8343 } 8344 8345 /** @hide */ 8346 public boolean fitsSystemWindows() { 8347 return getFitsSystemWindows(); 8348 } 8349 8350 /** 8351 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 8352 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 8353 */ 8354 @Deprecated 8355 public void requestFitSystemWindows() { 8356 if (mParent != null) { 8357 mParent.requestFitSystemWindows(); 8358 } 8359 } 8360 8361 /** 8362 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 8363 */ 8364 public void requestApplyInsets() { 8365 requestFitSystemWindows(); 8366 } 8367 8368 /** 8369 * For use by PhoneWindow to make its own system window fitting optional. 8370 * @hide 8371 */ 8372 public void makeOptionalFitsSystemWindows() { 8373 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 8374 } 8375 8376 /** 8377 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 8378 * treat them as such. 8379 * @hide 8380 */ 8381 public void getOutsets(Rect outOutsetRect) { 8382 if (mAttachInfo != null) { 8383 outOutsetRect.set(mAttachInfo.mOutsets); 8384 } else { 8385 outOutsetRect.setEmpty(); 8386 } 8387 } 8388 8389 /** 8390 * Returns the visibility status for this view. 8391 * 8392 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8393 * @attr ref android.R.styleable#View_visibility 8394 */ 8395 @ViewDebug.ExportedProperty(mapping = { 8396 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 8397 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 8398 @ViewDebug.IntToString(from = GONE, to = "GONE") 8399 }) 8400 @Visibility 8401 public int getVisibility() { 8402 return mViewFlags & VISIBILITY_MASK; 8403 } 8404 8405 /** 8406 * Set the visibility state of this view. 8407 * 8408 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8409 * @attr ref android.R.styleable#View_visibility 8410 */ 8411 @RemotableViewMethod 8412 public void setVisibility(@Visibility int visibility) { 8413 setFlags(visibility, VISIBILITY_MASK); 8414 } 8415 8416 /** 8417 * Returns the enabled status for this view. The interpretation of the 8418 * enabled state varies by subclass. 8419 * 8420 * @return True if this view is enabled, false otherwise. 8421 */ 8422 @ViewDebug.ExportedProperty 8423 public boolean isEnabled() { 8424 return (mViewFlags & ENABLED_MASK) == ENABLED; 8425 } 8426 8427 /** 8428 * Set the enabled state of this view. The interpretation of the enabled 8429 * state varies by subclass. 8430 * 8431 * @param enabled True if this view is enabled, false otherwise. 8432 */ 8433 @RemotableViewMethod 8434 public void setEnabled(boolean enabled) { 8435 if (enabled == isEnabled()) return; 8436 8437 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8438 8439 /* 8440 * The View most likely has to change its appearance, so refresh 8441 * the drawable state. 8442 */ 8443 refreshDrawableState(); 8444 8445 // Invalidate too, since the default behavior for views is to be 8446 // be drawn at 50% alpha rather than to change the drawable. 8447 invalidate(true); 8448 8449 if (!enabled) { 8450 cancelPendingInputEvents(); 8451 } 8452 } 8453 8454 /** 8455 * Set whether this view can receive the focus. 8456 * 8457 * Setting this to false will also ensure that this view is not focusable 8458 * in touch mode. 8459 * 8460 * @param focusable If true, this view can receive the focus. 8461 * 8462 * @see #setFocusableInTouchMode(boolean) 8463 * @attr ref android.R.styleable#View_focusable 8464 */ 8465 public void setFocusable(boolean focusable) { 8466 if (!focusable) { 8467 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8468 } 8469 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8470 } 8471 8472 /** 8473 * Set whether this view can receive focus while in touch mode. 8474 * 8475 * Setting this to true will also ensure that this view is focusable. 8476 * 8477 * @param focusableInTouchMode If true, this view can receive the focus while 8478 * in touch mode. 8479 * 8480 * @see #setFocusable(boolean) 8481 * @attr ref android.R.styleable#View_focusableInTouchMode 8482 */ 8483 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8484 // Focusable in touch mode should always be set before the focusable flag 8485 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8486 // which, in touch mode, will not successfully request focus on this view 8487 // because the focusable in touch mode flag is not set 8488 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8489 if (focusableInTouchMode) { 8490 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8491 } 8492 } 8493 8494 /** 8495 * Set whether this view should have sound effects enabled for events such as 8496 * clicking and touching. 8497 * 8498 * <p>You may wish to disable sound effects for a view if you already play sounds, 8499 * for instance, a dial key that plays dtmf tones. 8500 * 8501 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8502 * @see #isSoundEffectsEnabled() 8503 * @see #playSoundEffect(int) 8504 * @attr ref android.R.styleable#View_soundEffectsEnabled 8505 */ 8506 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8507 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8508 } 8509 8510 /** 8511 * @return whether this view should have sound effects enabled for events such as 8512 * clicking and touching. 8513 * 8514 * @see #setSoundEffectsEnabled(boolean) 8515 * @see #playSoundEffect(int) 8516 * @attr ref android.R.styleable#View_soundEffectsEnabled 8517 */ 8518 @ViewDebug.ExportedProperty 8519 public boolean isSoundEffectsEnabled() { 8520 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8521 } 8522 8523 /** 8524 * Set whether this view should have haptic feedback for events such as 8525 * long presses. 8526 * 8527 * <p>You may wish to disable haptic feedback if your view already controls 8528 * its own haptic feedback. 8529 * 8530 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8531 * @see #isHapticFeedbackEnabled() 8532 * @see #performHapticFeedback(int) 8533 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8534 */ 8535 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8536 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8537 } 8538 8539 /** 8540 * @return whether this view should have haptic feedback enabled for events 8541 * long presses. 8542 * 8543 * @see #setHapticFeedbackEnabled(boolean) 8544 * @see #performHapticFeedback(int) 8545 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8546 */ 8547 @ViewDebug.ExportedProperty 8548 public boolean isHapticFeedbackEnabled() { 8549 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8550 } 8551 8552 /** 8553 * Returns the layout direction for this view. 8554 * 8555 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8556 * {@link #LAYOUT_DIRECTION_RTL}, 8557 * {@link #LAYOUT_DIRECTION_INHERIT} or 8558 * {@link #LAYOUT_DIRECTION_LOCALE}. 8559 * 8560 * @attr ref android.R.styleable#View_layoutDirection 8561 * 8562 * @hide 8563 */ 8564 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8565 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8566 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8567 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8568 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8569 }) 8570 @LayoutDir 8571 public int getRawLayoutDirection() { 8572 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8573 } 8574 8575 /** 8576 * Set the layout direction for this view. This will propagate a reset of layout direction 8577 * resolution to the view's children and resolve layout direction for this view. 8578 * 8579 * @param layoutDirection the layout direction to set. Should be one of: 8580 * 8581 * {@link #LAYOUT_DIRECTION_LTR}, 8582 * {@link #LAYOUT_DIRECTION_RTL}, 8583 * {@link #LAYOUT_DIRECTION_INHERIT}, 8584 * {@link #LAYOUT_DIRECTION_LOCALE}. 8585 * 8586 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8587 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8588 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8589 * 8590 * @attr ref android.R.styleable#View_layoutDirection 8591 */ 8592 @RemotableViewMethod 8593 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8594 if (getRawLayoutDirection() != layoutDirection) { 8595 // Reset the current layout direction and the resolved one 8596 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8597 resetRtlProperties(); 8598 // Set the new layout direction (filtered) 8599 mPrivateFlags2 |= 8600 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8601 // We need to resolve all RTL properties as they all depend on layout direction 8602 resolveRtlPropertiesIfNeeded(); 8603 requestLayout(); 8604 invalidate(true); 8605 } 8606 } 8607 8608 /** 8609 * Returns the resolved layout direction for this view. 8610 * 8611 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8612 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8613 * 8614 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8615 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8616 * 8617 * @attr ref android.R.styleable#View_layoutDirection 8618 */ 8619 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8620 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8621 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8622 }) 8623 @ResolvedLayoutDir 8624 public int getLayoutDirection() { 8625 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8626 if (targetSdkVersion < JELLY_BEAN_MR1) { 8627 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8628 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8629 } 8630 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8631 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8632 } 8633 8634 /** 8635 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8636 * layout attribute and/or the inherited value from the parent 8637 * 8638 * @return true if the layout is right-to-left. 8639 * 8640 * @hide 8641 */ 8642 @ViewDebug.ExportedProperty(category = "layout") 8643 public boolean isLayoutRtl() { 8644 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8645 } 8646 8647 /** 8648 * Indicates whether the view is currently tracking transient state that the 8649 * app should not need to concern itself with saving and restoring, but that 8650 * the framework should take special note to preserve when possible. 8651 * 8652 * <p>A view with transient state cannot be trivially rebound from an external 8653 * data source, such as an adapter binding item views in a list. This may be 8654 * because the view is performing an animation, tracking user selection 8655 * of content, or similar.</p> 8656 * 8657 * @return true if the view has transient state 8658 */ 8659 @ViewDebug.ExportedProperty(category = "layout") 8660 public boolean hasTransientState() { 8661 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8662 } 8663 8664 /** 8665 * Set whether this view is currently tracking transient state that the 8666 * framework should attempt to preserve when possible. This flag is reference counted, 8667 * so every call to setHasTransientState(true) should be paired with a later call 8668 * to setHasTransientState(false). 8669 * 8670 * <p>A view with transient state cannot be trivially rebound from an external 8671 * data source, such as an adapter binding item views in a list. This may be 8672 * because the view is performing an animation, tracking user selection 8673 * of content, or similar.</p> 8674 * 8675 * @param hasTransientState true if this view has transient state 8676 */ 8677 public void setHasTransientState(boolean hasTransientState) { 8678 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8679 mTransientStateCount - 1; 8680 if (mTransientStateCount < 0) { 8681 mTransientStateCount = 0; 8682 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8683 "unmatched pair of setHasTransientState calls"); 8684 } else if ((hasTransientState && mTransientStateCount == 1) || 8685 (!hasTransientState && mTransientStateCount == 0)) { 8686 // update flag if we've just incremented up from 0 or decremented down to 0 8687 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8688 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8689 if (mParent != null) { 8690 try { 8691 mParent.childHasTransientStateChanged(this, hasTransientState); 8692 } catch (AbstractMethodError e) { 8693 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8694 " does not fully implement ViewParent", e); 8695 } 8696 } 8697 } 8698 } 8699 8700 /** 8701 * Returns true if this view is currently attached to a window. 8702 */ 8703 public boolean isAttachedToWindow() { 8704 return mAttachInfo != null; 8705 } 8706 8707 /** 8708 * Returns true if this view has been through at least one layout since it 8709 * was last attached to or detached from a window. 8710 */ 8711 public boolean isLaidOut() { 8712 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8713 } 8714 8715 /** 8716 * If this view doesn't do any drawing on its own, set this flag to 8717 * allow further optimizations. By default, this flag is not set on 8718 * View, but could be set on some View subclasses such as ViewGroup. 8719 * 8720 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8721 * you should clear this flag. 8722 * 8723 * @param willNotDraw whether or not this View draw on its own 8724 */ 8725 public void setWillNotDraw(boolean willNotDraw) { 8726 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8727 } 8728 8729 /** 8730 * Returns whether or not this View draws on its own. 8731 * 8732 * @return true if this view has nothing to draw, false otherwise 8733 */ 8734 @ViewDebug.ExportedProperty(category = "drawing") 8735 public boolean willNotDraw() { 8736 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8737 } 8738 8739 /** 8740 * When a View's drawing cache is enabled, drawing is redirected to an 8741 * offscreen bitmap. Some views, like an ImageView, must be able to 8742 * bypass this mechanism if they already draw a single bitmap, to avoid 8743 * unnecessary usage of the memory. 8744 * 8745 * @param willNotCacheDrawing true if this view does not cache its 8746 * drawing, false otherwise 8747 */ 8748 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8749 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8750 } 8751 8752 /** 8753 * Returns whether or not this View can cache its drawing or not. 8754 * 8755 * @return true if this view does not cache its drawing, false otherwise 8756 */ 8757 @ViewDebug.ExportedProperty(category = "drawing") 8758 public boolean willNotCacheDrawing() { 8759 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8760 } 8761 8762 /** 8763 * Indicates whether this view reacts to click events or not. 8764 * 8765 * @return true if the view is clickable, false otherwise 8766 * 8767 * @see #setClickable(boolean) 8768 * @attr ref android.R.styleable#View_clickable 8769 */ 8770 @ViewDebug.ExportedProperty 8771 public boolean isClickable() { 8772 return (mViewFlags & CLICKABLE) == CLICKABLE; 8773 } 8774 8775 /** 8776 * Enables or disables click events for this view. When a view 8777 * is clickable it will change its state to "pressed" on every click. 8778 * Subclasses should set the view clickable to visually react to 8779 * user's clicks. 8780 * 8781 * @param clickable true to make the view clickable, false otherwise 8782 * 8783 * @see #isClickable() 8784 * @attr ref android.R.styleable#View_clickable 8785 */ 8786 public void setClickable(boolean clickable) { 8787 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8788 } 8789 8790 /** 8791 * Indicates whether this view reacts to long click events or not. 8792 * 8793 * @return true if the view is long clickable, false otherwise 8794 * 8795 * @see #setLongClickable(boolean) 8796 * @attr ref android.R.styleable#View_longClickable 8797 */ 8798 public boolean isLongClickable() { 8799 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8800 } 8801 8802 /** 8803 * Enables or disables long click events for this view. When a view is long 8804 * clickable it reacts to the user holding down the button for a longer 8805 * duration than a tap. This event can either launch the listener or a 8806 * context menu. 8807 * 8808 * @param longClickable true to make the view long clickable, false otherwise 8809 * @see #isLongClickable() 8810 * @attr ref android.R.styleable#View_longClickable 8811 */ 8812 public void setLongClickable(boolean longClickable) { 8813 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8814 } 8815 8816 /** 8817 * Indicates whether this view reacts to context clicks or not. 8818 * 8819 * @return true if the view is context clickable, false otherwise 8820 * @see #setContextClickable(boolean) 8821 * @attr ref android.R.styleable#View_contextClickable 8822 */ 8823 public boolean isContextClickable() { 8824 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8825 } 8826 8827 /** 8828 * Enables or disables context clicking for this view. This event can launch the listener. 8829 * 8830 * @param contextClickable true to make the view react to a context click, false otherwise 8831 * @see #isContextClickable() 8832 * @attr ref android.R.styleable#View_contextClickable 8833 */ 8834 public void setContextClickable(boolean contextClickable) { 8835 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8836 } 8837 8838 /** 8839 * Sets the pressed state for this view and provides a touch coordinate for 8840 * animation hinting. 8841 * 8842 * @param pressed Pass true to set the View's internal state to "pressed", 8843 * or false to reverts the View's internal state from a 8844 * previously set "pressed" state. 8845 * @param x The x coordinate of the touch that caused the press 8846 * @param y The y coordinate of the touch that caused the press 8847 */ 8848 private void setPressed(boolean pressed, float x, float y) { 8849 if (pressed) { 8850 drawableHotspotChanged(x, y); 8851 } 8852 8853 setPressed(pressed); 8854 } 8855 8856 /** 8857 * Sets the pressed state for this view. 8858 * 8859 * @see #isClickable() 8860 * @see #setClickable(boolean) 8861 * 8862 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8863 * the View's internal state from a previously set "pressed" state. 8864 */ 8865 public void setPressed(boolean pressed) { 8866 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8867 8868 if (pressed) { 8869 mPrivateFlags |= PFLAG_PRESSED; 8870 } else { 8871 mPrivateFlags &= ~PFLAG_PRESSED; 8872 } 8873 8874 if (needsRefresh) { 8875 refreshDrawableState(); 8876 } 8877 dispatchSetPressed(pressed); 8878 } 8879 8880 /** 8881 * Dispatch setPressed to all of this View's children. 8882 * 8883 * @see #setPressed(boolean) 8884 * 8885 * @param pressed The new pressed state 8886 */ 8887 protected void dispatchSetPressed(boolean pressed) { 8888 } 8889 8890 /** 8891 * Indicates whether the view is currently in pressed state. Unless 8892 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8893 * the pressed state. 8894 * 8895 * @see #setPressed(boolean) 8896 * @see #isClickable() 8897 * @see #setClickable(boolean) 8898 * 8899 * @return true if the view is currently pressed, false otherwise 8900 */ 8901 @ViewDebug.ExportedProperty 8902 public boolean isPressed() { 8903 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8904 } 8905 8906 /** 8907 * @hide 8908 * Indicates whether this view will participate in data collection through 8909 * {@link ViewStructure}. If true, it will not provide any data 8910 * for itself or its children. If false, the normal data collection will be allowed. 8911 * 8912 * @return Returns false if assist data collection is not blocked, else true. 8913 * 8914 * @see #setAssistBlocked(boolean) 8915 * @attr ref android.R.styleable#View_assistBlocked 8916 */ 8917 public boolean isAssistBlocked() { 8918 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8919 } 8920 8921 /** 8922 * @hide 8923 * Indicates whether this view will participate in data collection through 8924 * {@link ViewStructure} for auto-fill purposes. 8925 * 8926 * <p>If {@code true}, it will not provide any data for itself or its children. 8927 * <p>If {@code false}, the normal data collection will be allowed. 8928 * 8929 * @return Returns {@code false} if assist data collection for auto-fill is not blocked, 8930 * else {@code true}. 8931 * 8932 * TODO(b/33197203): update / remove javadoc tags below 8933 * @see #setAssistBlocked(boolean) 8934 * @attr ref android.R.styleable#View_assistBlocked 8935 */ 8936 public boolean isAutoFillBlocked() { 8937 return false; // TODO(b/33197203): properly implement it 8938 } 8939 8940 /** 8941 * @hide 8942 * Controls whether assist data collection from this view and its children is enabled 8943 * (that is, whether {@link #onProvideStructure} and 8944 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8945 * allowing normal assist collection. Setting this to false will disable assist collection. 8946 * 8947 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8948 * (the default) to allow it. 8949 * 8950 * @see #isAssistBlocked() 8951 * @see #onProvideStructure 8952 * @see #onProvideVirtualStructure 8953 * @attr ref android.R.styleable#View_assistBlocked 8954 */ 8955 public void setAssistBlocked(boolean enabled) { 8956 if (enabled) { 8957 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8958 } else { 8959 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8960 } 8961 } 8962 8963 /** 8964 * Indicates whether this view will save its state (that is, 8965 * whether its {@link #onSaveInstanceState} method will be called). 8966 * 8967 * @return Returns true if the view state saving is enabled, else false. 8968 * 8969 * @see #setSaveEnabled(boolean) 8970 * @attr ref android.R.styleable#View_saveEnabled 8971 */ 8972 public boolean isSaveEnabled() { 8973 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8974 } 8975 8976 /** 8977 * Controls whether the saving of this view's state is 8978 * enabled (that is, whether its {@link #onSaveInstanceState} method 8979 * will be called). Note that even if freezing is enabled, the 8980 * view still must have an id assigned to it (via {@link #setId(int)}) 8981 * for its state to be saved. This flag can only disable the 8982 * saving of this view; any child views may still have their state saved. 8983 * 8984 * @param enabled Set to false to <em>disable</em> state saving, or true 8985 * (the default) to allow it. 8986 * 8987 * @see #isSaveEnabled() 8988 * @see #setId(int) 8989 * @see #onSaveInstanceState() 8990 * @attr ref android.R.styleable#View_saveEnabled 8991 */ 8992 public void setSaveEnabled(boolean enabled) { 8993 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8994 } 8995 8996 /** 8997 * Gets whether the framework should discard touches when the view's 8998 * window is obscured by another visible window. 8999 * Refer to the {@link View} security documentation for more details. 9000 * 9001 * @return True if touch filtering is enabled. 9002 * 9003 * @see #setFilterTouchesWhenObscured(boolean) 9004 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9005 */ 9006 @ViewDebug.ExportedProperty 9007 public boolean getFilterTouchesWhenObscured() { 9008 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 9009 } 9010 9011 /** 9012 * Sets whether the framework should discard touches when the view's 9013 * window is obscured by another visible window. 9014 * Refer to the {@link View} security documentation for more details. 9015 * 9016 * @param enabled True if touch filtering should be enabled. 9017 * 9018 * @see #getFilterTouchesWhenObscured 9019 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9020 */ 9021 public void setFilterTouchesWhenObscured(boolean enabled) { 9022 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 9023 FILTER_TOUCHES_WHEN_OBSCURED); 9024 } 9025 9026 /** 9027 * Indicates whether the entire hierarchy under this view will save its 9028 * state when a state saving traversal occurs from its parent. The default 9029 * is true; if false, these views will not be saved unless 9030 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9031 * 9032 * @return Returns true if the view state saving from parent is enabled, else false. 9033 * 9034 * @see #setSaveFromParentEnabled(boolean) 9035 */ 9036 public boolean isSaveFromParentEnabled() { 9037 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 9038 } 9039 9040 /** 9041 * Controls whether the entire hierarchy under this view will save its 9042 * state when a state saving traversal occurs from its parent. The default 9043 * is true; if false, these views will not be saved unless 9044 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9045 * 9046 * @param enabled Set to false to <em>disable</em> state saving, or true 9047 * (the default) to allow it. 9048 * 9049 * @see #isSaveFromParentEnabled() 9050 * @see #setId(int) 9051 * @see #onSaveInstanceState() 9052 */ 9053 public void setSaveFromParentEnabled(boolean enabled) { 9054 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 9055 } 9056 9057 9058 /** 9059 * Returns whether this View is able to take focus. 9060 * 9061 * @return True if this view can take focus, or false otherwise. 9062 * @attr ref android.R.styleable#View_focusable 9063 */ 9064 @ViewDebug.ExportedProperty(category = "focus") 9065 public final boolean isFocusable() { 9066 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 9067 } 9068 9069 /** 9070 * When a view is focusable, it may not want to take focus when in touch mode. 9071 * For example, a button would like focus when the user is navigating via a D-pad 9072 * so that the user can click on it, but once the user starts touching the screen, 9073 * the button shouldn't take focus 9074 * @return Whether the view is focusable in touch mode. 9075 * @attr ref android.R.styleable#View_focusableInTouchMode 9076 */ 9077 @ViewDebug.ExportedProperty 9078 public final boolean isFocusableInTouchMode() { 9079 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 9080 } 9081 9082 /** 9083 * Find the nearest view in the specified direction that can take focus. 9084 * This does not actually give focus to that view. 9085 * 9086 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9087 * 9088 * @return The nearest focusable in the specified direction, or null if none 9089 * can be found. 9090 */ 9091 public View focusSearch(@FocusRealDirection int direction) { 9092 if (mParent != null) { 9093 return mParent.focusSearch(this, direction); 9094 } else { 9095 return null; 9096 } 9097 } 9098 9099 /** 9100 * Returns whether this View is a root of a keyboard navigation cluster. 9101 * 9102 * @return True if this view is a root of a cluster, or false otherwise. 9103 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9104 */ 9105 @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster") 9106 public final boolean isKeyboardNavigationCluster() { 9107 return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0; 9108 } 9109 9110 /** 9111 * Set whether this view is a root of a keyboard navigation cluster. 9112 * 9113 * @param isCluster If true, this view is a root of a cluster. 9114 * 9115 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9116 */ 9117 public void setKeyboardNavigationCluster(boolean isCluster) { 9118 if (isCluster) { 9119 mPrivateFlags3 |= PFLAG3_CLUSTER; 9120 } else { 9121 mPrivateFlags3 &= ~PFLAG3_CLUSTER; 9122 } 9123 } 9124 9125 /** 9126 * Returns whether this View should receive focus when the focus is restored for the view 9127 * hierarchy containing this view. 9128 * <p> 9129 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9130 * window or serves as a target of cluster navigation. 9131 * 9132 * @see #restoreDefaultFocus(int) 9133 * 9134 * @return {@code true} if this view is the default-focus view, {@code false} otherwise 9135 * @attr ref android.R.styleable#View_focusedByDefault 9136 */ 9137 @ViewDebug.ExportedProperty(category = "focusedByDefault") 9138 public final boolean isFocusedByDefault() { 9139 return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0; 9140 } 9141 9142 /** 9143 * Sets whether this View should receive focus when the focus is restored for the view 9144 * hierarchy containing this view. 9145 * <p> 9146 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9147 * window or serves as a target of cluster navigation. 9148 * 9149 * @param isFocusedByDefault {@code true} to set this view as the default-focus view, 9150 * {@code false} otherwise. 9151 * 9152 * @see #restoreDefaultFocus(int) 9153 * 9154 * @attr ref android.R.styleable#View_focusedByDefault 9155 */ 9156 public void setFocusedByDefault(boolean isFocusedByDefault) { 9157 if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) { 9158 return; 9159 } 9160 9161 if (isFocusedByDefault) { 9162 mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT; 9163 } else { 9164 mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT; 9165 } 9166 9167 if (mParent instanceof ViewGroup) { 9168 if (isFocusedByDefault) { 9169 ((ViewGroup) mParent).setDefaultFocus(this); 9170 } else { 9171 ((ViewGroup) mParent).cleanDefaultFocus(this); 9172 } 9173 } 9174 } 9175 9176 /** 9177 * Returns whether the view hierarchy with this view as a root contain a default-focus view. 9178 * 9179 * @return {@code true} if this view has default focus, {@code false} otherwise 9180 */ 9181 boolean hasDefaultFocus() { 9182 return isFocusedByDefault(); 9183 } 9184 9185 /** 9186 * Find the nearest keyboard navigation cluster in the specified direction. 9187 * This does not actually give focus to that cluster. 9188 * 9189 * @param currentCluster The starting point of the search. Null means the current cluster is not 9190 * found yet 9191 * @param direction Direction to look 9192 * 9193 * @return The nearest keyboard navigation cluster in the specified direction, or null if none 9194 * can be found 9195 */ 9196 public View keyboardNavigationClusterSearch(View currentCluster, int direction) { 9197 if (isKeyboardNavigationCluster()) { 9198 currentCluster = this; 9199 } 9200 if (isRootNamespace()) { 9201 // Root namespace means we should consider ourselves the top of the 9202 // tree for group searching; otherwise we could be group searching 9203 // into other tabs. see LocalActivityManager and TabHost for more info. 9204 return FocusFinder.getInstance().findNextKeyboardNavigationCluster( 9205 this, currentCluster, direction); 9206 } else if (mParent != null) { 9207 return mParent.keyboardNavigationClusterSearch(currentCluster, direction); 9208 } 9209 return null; 9210 } 9211 9212 /** 9213 * This method is the last chance for the focused view and its ancestors to 9214 * respond to an arrow key. This is called when the focused view did not 9215 * consume the key internally, nor could the view system find a new view in 9216 * the requested direction to give focus to. 9217 * 9218 * @param focused The currently focused view. 9219 * @param direction The direction focus wants to move. One of FOCUS_UP, 9220 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 9221 * @return True if the this view consumed this unhandled move. 9222 */ 9223 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 9224 return false; 9225 } 9226 9227 /** 9228 * If a user manually specified the next view id for a particular direction, 9229 * use the root to look up the view. 9230 * @param root The root view of the hierarchy containing this view. 9231 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 9232 * or FOCUS_BACKWARD. 9233 * @return The user specified next view, or null if there is none. 9234 */ 9235 View findUserSetNextFocus(View root, @FocusDirection int direction) { 9236 switch (direction) { 9237 case FOCUS_LEFT: 9238 if (mNextFocusLeftId == View.NO_ID) return null; 9239 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 9240 case FOCUS_RIGHT: 9241 if (mNextFocusRightId == View.NO_ID) return null; 9242 return findViewInsideOutShouldExist(root, mNextFocusRightId); 9243 case FOCUS_UP: 9244 if (mNextFocusUpId == View.NO_ID) return null; 9245 return findViewInsideOutShouldExist(root, mNextFocusUpId); 9246 case FOCUS_DOWN: 9247 if (mNextFocusDownId == View.NO_ID) return null; 9248 return findViewInsideOutShouldExist(root, mNextFocusDownId); 9249 case FOCUS_FORWARD: 9250 if (mNextFocusForwardId == View.NO_ID) return null; 9251 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 9252 case FOCUS_BACKWARD: { 9253 if (mID == View.NO_ID) return null; 9254 final int id = mID; 9255 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 9256 @Override 9257 public boolean apply(View t) { 9258 return t.mNextFocusForwardId == id; 9259 } 9260 }); 9261 } 9262 } 9263 return null; 9264 } 9265 9266 private View findViewInsideOutShouldExist(View root, int id) { 9267 if (mMatchIdPredicate == null) { 9268 mMatchIdPredicate = new MatchIdPredicate(); 9269 } 9270 mMatchIdPredicate.mId = id; 9271 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 9272 if (result == null) { 9273 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 9274 } 9275 return result; 9276 } 9277 9278 /** 9279 * Find and return all focusable views that are descendants of this view, 9280 * possibly including this view if it is focusable itself. 9281 * 9282 * @param direction The direction of the focus 9283 * @return A list of focusable views 9284 */ 9285 public ArrayList<View> getFocusables(@FocusDirection int direction) { 9286 ArrayList<View> result = new ArrayList<View>(24); 9287 addFocusables(result, direction); 9288 return result; 9289 } 9290 9291 /** 9292 * Add any focusable views that are descendants of this view (possibly 9293 * including this view if it is focusable itself) to views. If we are in touch mode, 9294 * only add views that are also focusable in touch mode. 9295 * 9296 * @param views Focusable views found so far 9297 * @param direction The direction of the focus 9298 */ 9299 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 9300 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 9301 } 9302 9303 /** 9304 * Adds any focusable views that are descendants of this view (possibly 9305 * including this view if it is focusable itself) to views. This method 9306 * adds all focusable views regardless if we are in touch mode or 9307 * only views focusable in touch mode if we are in touch mode or 9308 * only views that can take accessibility focus if accessibility is enabled 9309 * depending on the focusable mode parameter. 9310 * 9311 * @param views Focusable views found so far or null if all we are interested is 9312 * the number of focusables. 9313 * @param direction The direction of the focus. 9314 * @param focusableMode The type of focusables to be added. 9315 * 9316 * @see #FOCUSABLES_ALL 9317 * @see #FOCUSABLES_TOUCH_MODE 9318 */ 9319 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 9320 @FocusableMode int focusableMode) { 9321 if (views == null) { 9322 return; 9323 } 9324 if (!isFocusable()) { 9325 return; 9326 } 9327 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 9328 && !isFocusableInTouchMode()) { 9329 return; 9330 } 9331 views.add(this); 9332 } 9333 9334 /** 9335 * Adds any keyboard navigation cluster roots that are descendants of this view (possibly 9336 * including this view if it is a cluster root itself) to views. 9337 * 9338 * @param views Keyboard navigation cluster roots found so far 9339 * @param direction Direction to look 9340 */ 9341 public void addKeyboardNavigationClusters( 9342 @NonNull Collection<View> views, 9343 int direction) { 9344 if (!(isKeyboardNavigationCluster())) { 9345 return; 9346 } 9347 views.add(this); 9348 } 9349 9350 /** 9351 * Finds the Views that contain given text. The containment is case insensitive. 9352 * The search is performed by either the text that the View renders or the content 9353 * description that describes the view for accessibility purposes and the view does 9354 * not render or both. Clients can specify how the search is to be performed via 9355 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 9356 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 9357 * 9358 * @param outViews The output list of matching Views. 9359 * @param searched The text to match against. 9360 * 9361 * @see #FIND_VIEWS_WITH_TEXT 9362 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 9363 * @see #setContentDescription(CharSequence) 9364 */ 9365 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 9366 @FindViewFlags int flags) { 9367 if (getAccessibilityNodeProvider() != null) { 9368 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 9369 outViews.add(this); 9370 } 9371 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 9372 && (searched != null && searched.length() > 0) 9373 && (mContentDescription != null && mContentDescription.length() > 0)) { 9374 String searchedLowerCase = searched.toString().toLowerCase(); 9375 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 9376 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 9377 outViews.add(this); 9378 } 9379 } 9380 } 9381 9382 /** 9383 * Find and return all touchable views that are descendants of this view, 9384 * possibly including this view if it is touchable itself. 9385 * 9386 * @return A list of touchable views 9387 */ 9388 public ArrayList<View> getTouchables() { 9389 ArrayList<View> result = new ArrayList<View>(); 9390 addTouchables(result); 9391 return result; 9392 } 9393 9394 /** 9395 * Add any touchable views that are descendants of this view (possibly 9396 * including this view if it is touchable itself) to views. 9397 * 9398 * @param views Touchable views found so far 9399 */ 9400 public void addTouchables(ArrayList<View> views) { 9401 final int viewFlags = mViewFlags; 9402 9403 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 9404 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 9405 && (viewFlags & ENABLED_MASK) == ENABLED) { 9406 views.add(this); 9407 } 9408 } 9409 9410 /** 9411 * Returns whether this View is accessibility focused. 9412 * 9413 * @return True if this View is accessibility focused. 9414 */ 9415 public boolean isAccessibilityFocused() { 9416 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 9417 } 9418 9419 /** 9420 * Call this to try to give accessibility focus to this view. 9421 * 9422 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 9423 * returns false or the view is no visible or the view already has accessibility 9424 * focus. 9425 * 9426 * See also {@link #focusSearch(int)}, which is what you call to say that you 9427 * have focus, and you want your parent to look for the next one. 9428 * 9429 * @return Whether this view actually took accessibility focus. 9430 * 9431 * @hide 9432 */ 9433 public boolean requestAccessibilityFocus() { 9434 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 9435 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 9436 return false; 9437 } 9438 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9439 return false; 9440 } 9441 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 9442 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 9443 ViewRootImpl viewRootImpl = getViewRootImpl(); 9444 if (viewRootImpl != null) { 9445 viewRootImpl.setAccessibilityFocus(this, null); 9446 } 9447 invalidate(); 9448 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 9449 return true; 9450 } 9451 return false; 9452 } 9453 9454 /** 9455 * Call this to try to clear accessibility focus of this view. 9456 * 9457 * See also {@link #focusSearch(int)}, which is what you call to say that you 9458 * have focus, and you want your parent to look for the next one. 9459 * 9460 * @hide 9461 */ 9462 public void clearAccessibilityFocus() { 9463 clearAccessibilityFocusNoCallbacks(0); 9464 9465 // Clear the global reference of accessibility focus if this view or 9466 // any of its descendants had accessibility focus. This will NOT send 9467 // an event or update internal state if focus is cleared from a 9468 // descendant view, which may leave views in inconsistent states. 9469 final ViewRootImpl viewRootImpl = getViewRootImpl(); 9470 if (viewRootImpl != null) { 9471 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 9472 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9473 viewRootImpl.setAccessibilityFocus(null, null); 9474 } 9475 } 9476 } 9477 9478 private void sendAccessibilityHoverEvent(int eventType) { 9479 // Since we are not delivering to a client accessibility events from not 9480 // important views (unless the clinet request that) we need to fire the 9481 // event from the deepest view exposed to the client. As a consequence if 9482 // the user crosses a not exposed view the client will see enter and exit 9483 // of the exposed predecessor followed by and enter and exit of that same 9484 // predecessor when entering and exiting the not exposed descendant. This 9485 // is fine since the client has a clear idea which view is hovered at the 9486 // price of a couple more events being sent. This is a simple and 9487 // working solution. 9488 View source = this; 9489 while (true) { 9490 if (source.includeForAccessibility()) { 9491 source.sendAccessibilityEvent(eventType); 9492 return; 9493 } 9494 ViewParent parent = source.getParent(); 9495 if (parent instanceof View) { 9496 source = (View) parent; 9497 } else { 9498 return; 9499 } 9500 } 9501 } 9502 9503 /** 9504 * Clears accessibility focus without calling any callback methods 9505 * normally invoked in {@link #clearAccessibilityFocus()}. This method 9506 * is used separately from that one for clearing accessibility focus when 9507 * giving this focus to another view. 9508 * 9509 * @param action The action, if any, that led to focus being cleared. Set to 9510 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 9511 * the window. 9512 */ 9513 void clearAccessibilityFocusNoCallbacks(int action) { 9514 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 9515 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 9516 invalidate(); 9517 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9518 AccessibilityEvent event = AccessibilityEvent.obtain( 9519 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 9520 event.setAction(action); 9521 if (mAccessibilityDelegate != null) { 9522 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 9523 } else { 9524 sendAccessibilityEventUnchecked(event); 9525 } 9526 } 9527 } 9528 } 9529 9530 /** 9531 * Call this to try to give focus to a specific view or to one of its 9532 * descendants. 9533 * 9534 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9535 * false), or if it is focusable and it is not focusable in touch mode 9536 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9537 * 9538 * See also {@link #focusSearch(int)}, which is what you call to say that you 9539 * have focus, and you want your parent to look for the next one. 9540 * 9541 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 9542 * {@link #FOCUS_DOWN} and <code>null</code>. 9543 * 9544 * @return Whether this view or one of its descendants actually took focus. 9545 */ 9546 public final boolean requestFocus() { 9547 return requestFocus(View.FOCUS_DOWN); 9548 } 9549 9550 /** 9551 * Gives focus to the default-focus view in the view hierarchy that has this view as a root. 9552 * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}. 9553 * Nested keyboard navigation clusters are excluded from the hierarchy. 9554 * 9555 * @param direction The direction of the focus 9556 * @return Whether this view or one of its descendants actually took focus 9557 */ 9558 public boolean restoreDefaultFocus(@FocusDirection int direction) { 9559 return requestFocus(direction); 9560 } 9561 9562 /** 9563 * Call this to try to give focus to a specific view or to one of its 9564 * descendants and give it a hint about what direction focus is heading. 9565 * 9566 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9567 * false), or if it is focusable and it is not focusable in touch mode 9568 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9569 * 9570 * See also {@link #focusSearch(int)}, which is what you call to say that you 9571 * have focus, and you want your parent to look for the next one. 9572 * 9573 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 9574 * <code>null</code> set for the previously focused rectangle. 9575 * 9576 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9577 * @return Whether this view or one of its descendants actually took focus. 9578 */ 9579 public final boolean requestFocus(int direction) { 9580 return requestFocus(direction, null); 9581 } 9582 9583 /** 9584 * Call this to try to give focus to a specific view or to one of its descendants 9585 * and give it hints about the direction and a specific rectangle that the focus 9586 * is coming from. The rectangle can help give larger views a finer grained hint 9587 * about where focus is coming from, and therefore, where to show selection, or 9588 * forward focus change internally. 9589 * 9590 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9591 * false), or if it is focusable and it is not focusable in touch mode 9592 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9593 * 9594 * A View will not take focus if it is not visible. 9595 * 9596 * A View will not take focus if one of its parents has 9597 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9598 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9599 * 9600 * See also {@link #focusSearch(int)}, which is what you call to say that you 9601 * have focus, and you want your parent to look for the next one. 9602 * 9603 * You may wish to override this method if your custom {@link View} has an internal 9604 * {@link View} that it wishes to forward the request to. 9605 * 9606 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9607 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9608 * to give a finer grained hint about where focus is coming from. May be null 9609 * if there is no hint. 9610 * @return Whether this view or one of its descendants actually took focus. 9611 */ 9612 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9613 return requestFocusNoSearch(direction, previouslyFocusedRect); 9614 } 9615 9616 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9617 // need to be focusable 9618 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9619 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9620 return false; 9621 } 9622 9623 // need to be focusable in touch mode if in touch mode 9624 if (isInTouchMode() && 9625 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9626 return false; 9627 } 9628 9629 // need to not have any parents blocking us 9630 if (hasAncestorThatBlocksDescendantFocus()) { 9631 return false; 9632 } 9633 9634 handleFocusGainInternal(direction, previouslyFocusedRect); 9635 return true; 9636 } 9637 9638 /** 9639 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9640 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9641 * touch mode to request focus when they are touched. 9642 * 9643 * @return Whether this view or one of its descendants actually took focus. 9644 * 9645 * @see #isInTouchMode() 9646 * 9647 */ 9648 public final boolean requestFocusFromTouch() { 9649 // Leave touch mode if we need to 9650 if (isInTouchMode()) { 9651 ViewRootImpl viewRoot = getViewRootImpl(); 9652 if (viewRoot != null) { 9653 viewRoot.ensureTouchMode(false); 9654 } 9655 } 9656 return requestFocus(View.FOCUS_DOWN); 9657 } 9658 9659 /** 9660 * @return Whether any ancestor of this view blocks descendant focus. 9661 */ 9662 private boolean hasAncestorThatBlocksDescendantFocus() { 9663 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9664 ViewParent ancestor = mParent; 9665 while (ancestor instanceof ViewGroup) { 9666 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9667 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9668 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9669 return true; 9670 } else { 9671 ancestor = vgAncestor.getParent(); 9672 } 9673 } 9674 return false; 9675 } 9676 9677 /** 9678 * Gets the mode for determining whether this View is important for accessibility. 9679 * A view is important for accessibility if it fires accessibility events and if it 9680 * is reported to accessibility services that query the screen. 9681 * 9682 * @return The mode for determining whether a view is important for accessibility, one 9683 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 9684 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 9685 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 9686 * 9687 * @attr ref android.R.styleable#View_importantForAccessibility 9688 * 9689 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9690 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9691 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9692 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9693 */ 9694 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9695 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9696 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9697 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9698 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9699 to = "noHideDescendants") 9700 }) 9701 public int getImportantForAccessibility() { 9702 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9703 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9704 } 9705 9706 /** 9707 * Sets the live region mode for this view. This indicates to accessibility 9708 * services whether they should automatically notify the user about changes 9709 * to the view's content description or text, or to the content descriptions 9710 * or text of the view's children (where applicable). 9711 * <p> 9712 * For example, in a login screen with a TextView that displays an "incorrect 9713 * password" notification, that view should be marked as a live region with 9714 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9715 * <p> 9716 * To disable change notifications for this view, use 9717 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9718 * mode for most views. 9719 * <p> 9720 * To indicate that the user should be notified of changes, use 9721 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9722 * <p> 9723 * If the view's changes should interrupt ongoing speech and notify the user 9724 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9725 * 9726 * @param mode The live region mode for this view, one of: 9727 * <ul> 9728 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9729 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9730 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9731 * </ul> 9732 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9733 */ 9734 public void setAccessibilityLiveRegion(int mode) { 9735 if (mode != getAccessibilityLiveRegion()) { 9736 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9737 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9738 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9739 notifyViewAccessibilityStateChangedIfNeeded( 9740 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9741 } 9742 } 9743 9744 /** 9745 * Gets the live region mode for this View. 9746 * 9747 * @return The live region mode for the view. 9748 * 9749 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9750 * 9751 * @see #setAccessibilityLiveRegion(int) 9752 */ 9753 public int getAccessibilityLiveRegion() { 9754 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9755 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9756 } 9757 9758 /** 9759 * Sets how to determine whether this view is important for accessibility 9760 * which is if it fires accessibility events and if it is reported to 9761 * accessibility services that query the screen. 9762 * 9763 * @param mode How to determine whether this view is important for accessibility. 9764 * 9765 * @attr ref android.R.styleable#View_importantForAccessibility 9766 * 9767 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9768 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9769 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9770 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9771 */ 9772 public void setImportantForAccessibility(int mode) { 9773 final int oldMode = getImportantForAccessibility(); 9774 if (mode != oldMode) { 9775 final boolean hideDescendants = 9776 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9777 9778 // If this node or its descendants are no longer important, try to 9779 // clear accessibility focus. 9780 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9781 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9782 if (focusHost != null) { 9783 focusHost.clearAccessibilityFocus(); 9784 } 9785 } 9786 9787 // If we're moving between AUTO and another state, we might not need 9788 // to send a subtree changed notification. We'll store the computed 9789 // importance, since we'll need to check it later to make sure. 9790 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9791 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9792 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9793 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9794 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9795 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9796 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9797 notifySubtreeAccessibilityStateChangedIfNeeded(); 9798 } else { 9799 notifyViewAccessibilityStateChangedIfNeeded( 9800 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9801 } 9802 } 9803 } 9804 9805 /** 9806 * Returns the view within this view's hierarchy that is hosting 9807 * accessibility focus. 9808 * 9809 * @param searchDescendants whether to search for focus in descendant views 9810 * @return the view hosting accessibility focus, or {@code null} 9811 */ 9812 private View findAccessibilityFocusHost(boolean searchDescendants) { 9813 if (isAccessibilityFocusedViewOrHost()) { 9814 return this; 9815 } 9816 9817 if (searchDescendants) { 9818 final ViewRootImpl viewRoot = getViewRootImpl(); 9819 if (viewRoot != null) { 9820 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9821 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9822 return focusHost; 9823 } 9824 } 9825 } 9826 9827 return null; 9828 } 9829 9830 /** 9831 * Computes whether this view should be exposed for accessibility. In 9832 * general, views that are interactive or provide information are exposed 9833 * while views that serve only as containers are hidden. 9834 * <p> 9835 * If an ancestor of this view has importance 9836 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9837 * returns <code>false</code>. 9838 * <p> 9839 * Otherwise, the value is computed according to the view's 9840 * {@link #getImportantForAccessibility()} value: 9841 * <ol> 9842 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9843 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9844 * </code> 9845 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9846 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9847 * view satisfies any of the following: 9848 * <ul> 9849 * <li>Is actionable, e.g. {@link #isClickable()}, 9850 * {@link #isLongClickable()}, or {@link #isFocusable()} 9851 * <li>Has an {@link AccessibilityDelegate} 9852 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9853 * {@link OnKeyListener}, etc. 9854 * <li>Is an accessibility live region, e.g. 9855 * {@link #getAccessibilityLiveRegion()} is not 9856 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9857 * </ul> 9858 * </ol> 9859 * 9860 * @return Whether the view is exposed for accessibility. 9861 * @see #setImportantForAccessibility(int) 9862 * @see #getImportantForAccessibility() 9863 */ 9864 public boolean isImportantForAccessibility() { 9865 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9866 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9867 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9868 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9869 return false; 9870 } 9871 9872 // Check parent mode to ensure we're not hidden. 9873 ViewParent parent = mParent; 9874 while (parent instanceof View) { 9875 if (((View) parent).getImportantForAccessibility() 9876 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9877 return false; 9878 } 9879 parent = parent.getParent(); 9880 } 9881 9882 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9883 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9884 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9885 } 9886 9887 /** 9888 * Gets the parent for accessibility purposes. Note that the parent for 9889 * accessibility is not necessary the immediate parent. It is the first 9890 * predecessor that is important for accessibility. 9891 * 9892 * @return The parent for accessibility purposes. 9893 */ 9894 public ViewParent getParentForAccessibility() { 9895 if (mParent instanceof View) { 9896 View parentView = (View) mParent; 9897 if (parentView.includeForAccessibility()) { 9898 return mParent; 9899 } else { 9900 return mParent.getParentForAccessibility(); 9901 } 9902 } 9903 return null; 9904 } 9905 9906 /** 9907 * Adds the children of this View relevant for accessibility to the given list 9908 * as output. Since some Views are not important for accessibility the added 9909 * child views are not necessarily direct children of this view, rather they are 9910 * the first level of descendants important for accessibility. 9911 * 9912 * @param outChildren The output list that will receive children for accessibility. 9913 */ 9914 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9915 9916 } 9917 9918 /** 9919 * Whether to regard this view for accessibility. A view is regarded for 9920 * accessibility if it is important for accessibility or the querying 9921 * accessibility service has explicitly requested that view not 9922 * important for accessibility are regarded. 9923 * 9924 * @return Whether to regard the view for accessibility. 9925 * 9926 * @hide 9927 */ 9928 public boolean includeForAccessibility() { 9929 if (mAttachInfo != null) { 9930 return (mAttachInfo.mAccessibilityFetchFlags 9931 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9932 || isImportantForAccessibility(); 9933 } 9934 return false; 9935 } 9936 9937 /** 9938 * Returns whether the View is considered actionable from 9939 * accessibility perspective. Such view are important for 9940 * accessibility. 9941 * 9942 * @return True if the view is actionable for accessibility. 9943 * 9944 * @hide 9945 */ 9946 public boolean isActionableForAccessibility() { 9947 return (isClickable() || isLongClickable() || isFocusable()); 9948 } 9949 9950 /** 9951 * Returns whether the View has registered callbacks which makes it 9952 * important for accessibility. 9953 * 9954 * @return True if the view is actionable for accessibility. 9955 */ 9956 private boolean hasListenersForAccessibility() { 9957 ListenerInfo info = getListenerInfo(); 9958 return mTouchDelegate != null || info.mOnKeyListener != null 9959 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9960 || info.mOnHoverListener != null || info.mOnDragListener != null; 9961 } 9962 9963 /** 9964 * Notifies that the accessibility state of this view changed. The change 9965 * is local to this view and does not represent structural changes such 9966 * as children and parent. For example, the view became focusable. The 9967 * notification is at at most once every 9968 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9969 * to avoid unnecessary load to the system. Also once a view has a pending 9970 * notification this method is a NOP until the notification has been sent. 9971 * 9972 * @hide 9973 */ 9974 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9975 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9976 return; 9977 } 9978 if (mSendViewStateChangedAccessibilityEvent == null) { 9979 mSendViewStateChangedAccessibilityEvent = 9980 new SendViewStateChangedAccessibilityEvent(); 9981 } 9982 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9983 } 9984 9985 /** 9986 * Notifies that the accessibility state of this view changed. The change 9987 * is *not* local to this view and does represent structural changes such 9988 * as children and parent. For example, the view size changed. The 9989 * notification is at at most once every 9990 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9991 * to avoid unnecessary load to the system. Also once a view has a pending 9992 * notification this method is a NOP until the notification has been sent. 9993 * 9994 * @hide 9995 */ 9996 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9997 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9998 return; 9999 } 10000 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 10001 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10002 if (mParent != null) { 10003 try { 10004 mParent.notifySubtreeAccessibilityStateChanged( 10005 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 10006 } catch (AbstractMethodError e) { 10007 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 10008 " does not fully implement ViewParent", e); 10009 } 10010 } 10011 } 10012 } 10013 10014 /** 10015 * Change the visibility of the View without triggering any other changes. This is 10016 * important for transitions, where visibility changes should not adjust focus or 10017 * trigger a new layout. This is only used when the visibility has already been changed 10018 * and we need a transient value during an animation. When the animation completes, 10019 * the original visibility value is always restored. 10020 * 10021 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 10022 * @hide 10023 */ 10024 public void setTransitionVisibility(@Visibility int visibility) { 10025 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 10026 } 10027 10028 /** 10029 * Reset the flag indicating the accessibility state of the subtree rooted 10030 * at this view changed. 10031 */ 10032 void resetSubtreeAccessibilityStateChanged() { 10033 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10034 } 10035 10036 /** 10037 * Report an accessibility action to this view's parents for delegated processing. 10038 * 10039 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 10040 * call this method to delegate an accessibility action to a supporting parent. If the parent 10041 * returns true from its 10042 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 10043 * method this method will return true to signify that the action was consumed.</p> 10044 * 10045 * <p>This method is useful for implementing nested scrolling child views. If 10046 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 10047 * a custom view implementation may invoke this method to allow a parent to consume the 10048 * scroll first. If this method returns true the custom view should skip its own scrolling 10049 * behavior.</p> 10050 * 10051 * @param action Accessibility action to delegate 10052 * @param arguments Optional action arguments 10053 * @return true if the action was consumed by a parent 10054 */ 10055 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 10056 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 10057 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 10058 return true; 10059 } 10060 } 10061 return false; 10062 } 10063 10064 /** 10065 * Performs the specified accessibility action on the view. For 10066 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 10067 * <p> 10068 * If an {@link AccessibilityDelegate} has been specified via calling 10069 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 10070 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 10071 * is responsible for handling this call. 10072 * </p> 10073 * 10074 * <p>The default implementation will delegate 10075 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 10076 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 10077 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 10078 * 10079 * @param action The action to perform. 10080 * @param arguments Optional action arguments. 10081 * @return Whether the action was performed. 10082 */ 10083 public boolean performAccessibilityAction(int action, Bundle arguments) { 10084 if (mAccessibilityDelegate != null) { 10085 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 10086 } else { 10087 return performAccessibilityActionInternal(action, arguments); 10088 } 10089 } 10090 10091 /** 10092 * @see #performAccessibilityAction(int, Bundle) 10093 * 10094 * Note: Called from the default {@link AccessibilityDelegate}. 10095 * 10096 * @hide 10097 */ 10098 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 10099 if (isNestedScrollingEnabled() 10100 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 10101 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 10102 || action == R.id.accessibilityActionScrollUp 10103 || action == R.id.accessibilityActionScrollLeft 10104 || action == R.id.accessibilityActionScrollDown 10105 || action == R.id.accessibilityActionScrollRight)) { 10106 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 10107 return true; 10108 } 10109 } 10110 10111 switch (action) { 10112 case AccessibilityNodeInfo.ACTION_CLICK: { 10113 if (isClickable()) { 10114 performClick(); 10115 return true; 10116 } 10117 } break; 10118 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 10119 if (isLongClickable()) { 10120 performLongClick(); 10121 return true; 10122 } 10123 } break; 10124 case AccessibilityNodeInfo.ACTION_FOCUS: { 10125 if (!hasFocus()) { 10126 // Get out of touch mode since accessibility 10127 // wants to move focus around. 10128 getViewRootImpl().ensureTouchMode(false); 10129 return requestFocus(); 10130 } 10131 } break; 10132 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 10133 if (hasFocus()) { 10134 clearFocus(); 10135 return !isFocused(); 10136 } 10137 } break; 10138 case AccessibilityNodeInfo.ACTION_SELECT: { 10139 if (!isSelected()) { 10140 setSelected(true); 10141 return isSelected(); 10142 } 10143 } break; 10144 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 10145 if (isSelected()) { 10146 setSelected(false); 10147 return !isSelected(); 10148 } 10149 } break; 10150 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 10151 if (!isAccessibilityFocused()) { 10152 return requestAccessibilityFocus(); 10153 } 10154 } break; 10155 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 10156 if (isAccessibilityFocused()) { 10157 clearAccessibilityFocus(); 10158 return true; 10159 } 10160 } break; 10161 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 10162 if (arguments != null) { 10163 final int granularity = arguments.getInt( 10164 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 10165 final boolean extendSelection = arguments.getBoolean( 10166 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 10167 return traverseAtGranularity(granularity, true, extendSelection); 10168 } 10169 } break; 10170 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 10171 if (arguments != null) { 10172 final int granularity = arguments.getInt( 10173 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 10174 final boolean extendSelection = arguments.getBoolean( 10175 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 10176 return traverseAtGranularity(granularity, false, extendSelection); 10177 } 10178 } break; 10179 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 10180 CharSequence text = getIterableTextForAccessibility(); 10181 if (text == null) { 10182 return false; 10183 } 10184 final int start = (arguments != null) ? arguments.getInt( 10185 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 10186 final int end = (arguments != null) ? arguments.getInt( 10187 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 10188 // Only cursor position can be specified (selection length == 0) 10189 if ((getAccessibilitySelectionStart() != start 10190 || getAccessibilitySelectionEnd() != end) 10191 && (start == end)) { 10192 setAccessibilitySelection(start, end); 10193 notifyViewAccessibilityStateChangedIfNeeded( 10194 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10195 return true; 10196 } 10197 } break; 10198 case R.id.accessibilityActionShowOnScreen: { 10199 if (mAttachInfo != null) { 10200 final Rect r = mAttachInfo.mTmpInvalRect; 10201 getDrawingRect(r); 10202 return requestRectangleOnScreen(r, true); 10203 } 10204 } break; 10205 case R.id.accessibilityActionContextClick: { 10206 if (isContextClickable()) { 10207 performContextClick(); 10208 return true; 10209 } 10210 } break; 10211 } 10212 return false; 10213 } 10214 10215 private boolean traverseAtGranularity(int granularity, boolean forward, 10216 boolean extendSelection) { 10217 CharSequence text = getIterableTextForAccessibility(); 10218 if (text == null || text.length() == 0) { 10219 return false; 10220 } 10221 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 10222 if (iterator == null) { 10223 return false; 10224 } 10225 int current = getAccessibilitySelectionEnd(); 10226 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 10227 current = forward ? 0 : text.length(); 10228 } 10229 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 10230 if (range == null) { 10231 return false; 10232 } 10233 final int segmentStart = range[0]; 10234 final int segmentEnd = range[1]; 10235 int selectionStart; 10236 int selectionEnd; 10237 if (extendSelection && isAccessibilitySelectionExtendable()) { 10238 selectionStart = getAccessibilitySelectionStart(); 10239 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 10240 selectionStart = forward ? segmentStart : segmentEnd; 10241 } 10242 selectionEnd = forward ? segmentEnd : segmentStart; 10243 } else { 10244 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 10245 } 10246 setAccessibilitySelection(selectionStart, selectionEnd); 10247 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 10248 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 10249 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 10250 return true; 10251 } 10252 10253 /** 10254 * Gets the text reported for accessibility purposes. 10255 * 10256 * @return The accessibility text. 10257 * 10258 * @hide 10259 */ 10260 public CharSequence getIterableTextForAccessibility() { 10261 return getContentDescription(); 10262 } 10263 10264 /** 10265 * Gets whether accessibility selection can be extended. 10266 * 10267 * @return If selection is extensible. 10268 * 10269 * @hide 10270 */ 10271 public boolean isAccessibilitySelectionExtendable() { 10272 return false; 10273 } 10274 10275 /** 10276 * @hide 10277 */ 10278 public int getAccessibilitySelectionStart() { 10279 return mAccessibilityCursorPosition; 10280 } 10281 10282 /** 10283 * @hide 10284 */ 10285 public int getAccessibilitySelectionEnd() { 10286 return getAccessibilitySelectionStart(); 10287 } 10288 10289 /** 10290 * @hide 10291 */ 10292 public void setAccessibilitySelection(int start, int end) { 10293 if (start == end && end == mAccessibilityCursorPosition) { 10294 return; 10295 } 10296 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 10297 mAccessibilityCursorPosition = start; 10298 } else { 10299 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 10300 } 10301 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 10302 } 10303 10304 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 10305 int fromIndex, int toIndex) { 10306 if (mParent == null) { 10307 return; 10308 } 10309 AccessibilityEvent event = AccessibilityEvent.obtain( 10310 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 10311 onInitializeAccessibilityEvent(event); 10312 onPopulateAccessibilityEvent(event); 10313 event.setFromIndex(fromIndex); 10314 event.setToIndex(toIndex); 10315 event.setAction(action); 10316 event.setMovementGranularity(granularity); 10317 mParent.requestSendAccessibilityEvent(this, event); 10318 } 10319 10320 /** 10321 * @hide 10322 */ 10323 public TextSegmentIterator getIteratorForGranularity(int granularity) { 10324 switch (granularity) { 10325 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 10326 CharSequence text = getIterableTextForAccessibility(); 10327 if (text != null && text.length() > 0) { 10328 CharacterTextSegmentIterator iterator = 10329 CharacterTextSegmentIterator.getInstance( 10330 mContext.getResources().getConfiguration().locale); 10331 iterator.initialize(text.toString()); 10332 return iterator; 10333 } 10334 } break; 10335 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 10336 CharSequence text = getIterableTextForAccessibility(); 10337 if (text != null && text.length() > 0) { 10338 WordTextSegmentIterator iterator = 10339 WordTextSegmentIterator.getInstance( 10340 mContext.getResources().getConfiguration().locale); 10341 iterator.initialize(text.toString()); 10342 return iterator; 10343 } 10344 } break; 10345 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 10346 CharSequence text = getIterableTextForAccessibility(); 10347 if (text != null && text.length() > 0) { 10348 ParagraphTextSegmentIterator iterator = 10349 ParagraphTextSegmentIterator.getInstance(); 10350 iterator.initialize(text.toString()); 10351 return iterator; 10352 } 10353 } break; 10354 } 10355 return null; 10356 } 10357 10358 /** 10359 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 10360 * and {@link #onFinishTemporaryDetach()}. 10361 * 10362 * <p>This method always returns {@code true} when called directly or indirectly from 10363 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 10364 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 10365 * <ul> 10366 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 10367 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 10368 * </ul> 10369 * </p> 10370 * 10371 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 10372 * and {@link #onFinishTemporaryDetach()}. 10373 */ 10374 public final boolean isTemporarilyDetached() { 10375 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 10376 } 10377 10378 /** 10379 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 10380 * a container View. 10381 */ 10382 @CallSuper 10383 public void dispatchStartTemporaryDetach() { 10384 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 10385 onStartTemporaryDetach(); 10386 } 10387 10388 /** 10389 * This is called when a container is going to temporarily detach a child, with 10390 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 10391 * It will either be followed by {@link #onFinishTemporaryDetach()} or 10392 * {@link #onDetachedFromWindow()} when the container is done. 10393 */ 10394 public void onStartTemporaryDetach() { 10395 removeUnsetPressCallback(); 10396 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 10397 } 10398 10399 /** 10400 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 10401 * a container View. 10402 */ 10403 @CallSuper 10404 public void dispatchFinishTemporaryDetach() { 10405 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 10406 onFinishTemporaryDetach(); 10407 if (hasWindowFocus() && hasFocus()) { 10408 InputMethodManager.getInstance().focusIn(this); 10409 } 10410 } 10411 10412 /** 10413 * Called after {@link #onStartTemporaryDetach} when the container is done 10414 * changing the view. 10415 */ 10416 public void onFinishTemporaryDetach() { 10417 } 10418 10419 /** 10420 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 10421 * for this view's window. Returns null if the view is not currently attached 10422 * to the window. Normally you will not need to use this directly, but 10423 * just use the standard high-level event callbacks like 10424 * {@link #onKeyDown(int, KeyEvent)}. 10425 */ 10426 public KeyEvent.DispatcherState getKeyDispatcherState() { 10427 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 10428 } 10429 10430 /** 10431 * Dispatch a key event before it is processed by any input method 10432 * associated with the view hierarchy. This can be used to intercept 10433 * key events in special situations before the IME consumes them; a 10434 * typical example would be handling the BACK key to update the application's 10435 * UI instead of allowing the IME to see it and close itself. 10436 * 10437 * @param event The key event to be dispatched. 10438 * @return True if the event was handled, false otherwise. 10439 */ 10440 public boolean dispatchKeyEventPreIme(KeyEvent event) { 10441 return onKeyPreIme(event.getKeyCode(), event); 10442 } 10443 10444 /** 10445 * Dispatch a key event to the next view on the focus path. This path runs 10446 * from the top of the view tree down to the currently focused view. If this 10447 * view has focus, it will dispatch to itself. Otherwise it will dispatch 10448 * the next node down the focus path. This method also fires any key 10449 * listeners. 10450 * 10451 * @param event The key event to be dispatched. 10452 * @return True if the event was handled, false otherwise. 10453 */ 10454 public boolean dispatchKeyEvent(KeyEvent event) { 10455 if (mInputEventConsistencyVerifier != null) { 10456 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 10457 } 10458 10459 // Give any attached key listener a first crack at the event. 10460 //noinspection SimplifiableIfStatement 10461 ListenerInfo li = mListenerInfo; 10462 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 10463 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 10464 return true; 10465 } 10466 10467 if (event.dispatch(this, mAttachInfo != null 10468 ? mAttachInfo.mKeyDispatchState : null, this)) { 10469 return true; 10470 } 10471 10472 if (mInputEventConsistencyVerifier != null) { 10473 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10474 } 10475 return false; 10476 } 10477 10478 /** 10479 * Dispatches a key shortcut event. 10480 * 10481 * @param event The key event to be dispatched. 10482 * @return True if the event was handled by the view, false otherwise. 10483 */ 10484 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 10485 return onKeyShortcut(event.getKeyCode(), event); 10486 } 10487 10488 /** 10489 * Pass the touch screen motion event down to the target view, or this 10490 * view if it is the target. 10491 * 10492 * @param event The motion event to be dispatched. 10493 * @return True if the event was handled by the view, false otherwise. 10494 */ 10495 public boolean dispatchTouchEvent(MotionEvent event) { 10496 // If the event should be handled by accessibility focus first. 10497 if (event.isTargetAccessibilityFocus()) { 10498 // We don't have focus or no virtual descendant has it, do not handle the event. 10499 if (!isAccessibilityFocusedViewOrHost()) { 10500 return false; 10501 } 10502 // We have focus and got the event, then use normal event dispatch. 10503 event.setTargetAccessibilityFocus(false); 10504 } 10505 10506 boolean result = false; 10507 10508 if (mInputEventConsistencyVerifier != null) { 10509 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 10510 } 10511 10512 final int actionMasked = event.getActionMasked(); 10513 if (actionMasked == MotionEvent.ACTION_DOWN) { 10514 // Defensive cleanup for new gesture 10515 stopNestedScroll(); 10516 } 10517 10518 if (onFilterTouchEventForSecurity(event)) { 10519 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 10520 result = true; 10521 } 10522 //noinspection SimplifiableIfStatement 10523 ListenerInfo li = mListenerInfo; 10524 if (li != null && li.mOnTouchListener != null 10525 && (mViewFlags & ENABLED_MASK) == ENABLED 10526 && li.mOnTouchListener.onTouch(this, event)) { 10527 result = true; 10528 } 10529 10530 if (!result && onTouchEvent(event)) { 10531 result = true; 10532 } 10533 } 10534 10535 if (!result && mInputEventConsistencyVerifier != null) { 10536 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10537 } 10538 10539 // Clean up after nested scrolls if this is the end of a gesture; 10540 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 10541 // of the gesture. 10542 if (actionMasked == MotionEvent.ACTION_UP || 10543 actionMasked == MotionEvent.ACTION_CANCEL || 10544 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 10545 stopNestedScroll(); 10546 } 10547 10548 return result; 10549 } 10550 10551 boolean isAccessibilityFocusedViewOrHost() { 10552 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 10553 .getAccessibilityFocusedHost() == this); 10554 } 10555 10556 /** 10557 * Filter the touch event to apply security policies. 10558 * 10559 * @param event The motion event to be filtered. 10560 * @return True if the event should be dispatched, false if the event should be dropped. 10561 * 10562 * @see #getFilterTouchesWhenObscured 10563 */ 10564 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 10565 //noinspection RedundantIfStatement 10566 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 10567 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 10568 // Window is obscured, drop this touch. 10569 return false; 10570 } 10571 return true; 10572 } 10573 10574 /** 10575 * Pass a trackball motion event down to the focused view. 10576 * 10577 * @param event The motion event to be dispatched. 10578 * @return True if the event was handled by the view, false otherwise. 10579 */ 10580 public boolean dispatchTrackballEvent(MotionEvent event) { 10581 if (mInputEventConsistencyVerifier != null) { 10582 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 10583 } 10584 10585 return onTrackballEvent(event); 10586 } 10587 10588 /** 10589 * Dispatch a generic motion event. 10590 * <p> 10591 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10592 * are delivered to the view under the pointer. All other generic motion events are 10593 * delivered to the focused view. Hover events are handled specially and are delivered 10594 * to {@link #onHoverEvent(MotionEvent)}. 10595 * </p> 10596 * 10597 * @param event The motion event to be dispatched. 10598 * @return True if the event was handled by the view, false otherwise. 10599 */ 10600 public boolean dispatchGenericMotionEvent(MotionEvent event) { 10601 if (mInputEventConsistencyVerifier != null) { 10602 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10603 } 10604 10605 final int source = event.getSource(); 10606 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10607 final int action = event.getAction(); 10608 if (action == MotionEvent.ACTION_HOVER_ENTER 10609 || action == MotionEvent.ACTION_HOVER_MOVE 10610 || action == MotionEvent.ACTION_HOVER_EXIT) { 10611 if (dispatchHoverEvent(event)) { 10612 return true; 10613 } 10614 } else if (dispatchGenericPointerEvent(event)) { 10615 return true; 10616 } 10617 } else if (dispatchGenericFocusedEvent(event)) { 10618 return true; 10619 } 10620 10621 if (dispatchGenericMotionEventInternal(event)) { 10622 return true; 10623 } 10624 10625 if (mInputEventConsistencyVerifier != null) { 10626 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10627 } 10628 return false; 10629 } 10630 10631 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10632 //noinspection SimplifiableIfStatement 10633 ListenerInfo li = mListenerInfo; 10634 if (li != null && li.mOnGenericMotionListener != null 10635 && (mViewFlags & ENABLED_MASK) == ENABLED 10636 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10637 return true; 10638 } 10639 10640 if (onGenericMotionEvent(event)) { 10641 return true; 10642 } 10643 10644 final int actionButton = event.getActionButton(); 10645 switch (event.getActionMasked()) { 10646 case MotionEvent.ACTION_BUTTON_PRESS: 10647 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10648 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10649 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10650 if (performContextClick(event.getX(), event.getY())) { 10651 mInContextButtonPress = true; 10652 setPressed(true, event.getX(), event.getY()); 10653 removeTapCallback(); 10654 removeLongPressCallback(); 10655 return true; 10656 } 10657 } 10658 break; 10659 10660 case MotionEvent.ACTION_BUTTON_RELEASE: 10661 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10662 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10663 mInContextButtonPress = false; 10664 mIgnoreNextUpEvent = true; 10665 } 10666 break; 10667 } 10668 10669 if (mInputEventConsistencyVerifier != null) { 10670 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10671 } 10672 return false; 10673 } 10674 10675 /** 10676 * Dispatch a hover event. 10677 * <p> 10678 * Do not call this method directly. 10679 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10680 * </p> 10681 * 10682 * @param event The motion event to be dispatched. 10683 * @return True if the event was handled by the view, false otherwise. 10684 */ 10685 protected boolean dispatchHoverEvent(MotionEvent event) { 10686 ListenerInfo li = mListenerInfo; 10687 //noinspection SimplifiableIfStatement 10688 if (li != null && li.mOnHoverListener != null 10689 && (mViewFlags & ENABLED_MASK) == ENABLED 10690 && li.mOnHoverListener.onHover(this, event)) { 10691 return true; 10692 } 10693 10694 return onHoverEvent(event); 10695 } 10696 10697 /** 10698 * Returns true if the view has a child to which it has recently sent 10699 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10700 * it does not have a hovered child, then it must be the innermost hovered view. 10701 * @hide 10702 */ 10703 protected boolean hasHoveredChild() { 10704 return false; 10705 } 10706 10707 /** 10708 * Dispatch a generic motion event to the view under the first pointer. 10709 * <p> 10710 * Do not call this method directly. 10711 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10712 * </p> 10713 * 10714 * @param event The motion event to be dispatched. 10715 * @return True if the event was handled by the view, false otherwise. 10716 */ 10717 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10718 return false; 10719 } 10720 10721 /** 10722 * Dispatch a generic motion event to the currently focused view. 10723 * <p> 10724 * Do not call this method directly. 10725 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10726 * </p> 10727 * 10728 * @param event The motion event to be dispatched. 10729 * @return True if the event was handled by the view, false otherwise. 10730 */ 10731 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10732 return false; 10733 } 10734 10735 /** 10736 * Dispatch a pointer event. 10737 * <p> 10738 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10739 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10740 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10741 * and should not be expected to handle other pointing device features. 10742 * </p> 10743 * 10744 * @param event The motion event to be dispatched. 10745 * @return True if the event was handled by the view, false otherwise. 10746 * @hide 10747 */ 10748 public final boolean dispatchPointerEvent(MotionEvent event) { 10749 if (event.isTouchEvent()) { 10750 return dispatchTouchEvent(event); 10751 } else { 10752 return dispatchGenericMotionEvent(event); 10753 } 10754 } 10755 10756 /** 10757 * Called when the window containing this view gains or loses window focus. 10758 * ViewGroups should override to route to their children. 10759 * 10760 * @param hasFocus True if the window containing this view now has focus, 10761 * false otherwise. 10762 */ 10763 public void dispatchWindowFocusChanged(boolean hasFocus) { 10764 onWindowFocusChanged(hasFocus); 10765 } 10766 10767 /** 10768 * Called when the window containing this view gains or loses focus. Note 10769 * that this is separate from view focus: to receive key events, both 10770 * your view and its window must have focus. If a window is displayed 10771 * on top of yours that takes input focus, then your own window will lose 10772 * focus but the view focus will remain unchanged. 10773 * 10774 * @param hasWindowFocus True if the window containing this view now has 10775 * focus, false otherwise. 10776 */ 10777 public void onWindowFocusChanged(boolean hasWindowFocus) { 10778 InputMethodManager imm = InputMethodManager.peekInstance(); 10779 if (!hasWindowFocus) { 10780 if (isPressed()) { 10781 setPressed(false); 10782 } 10783 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 10784 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10785 imm.focusOut(this); 10786 } 10787 removeLongPressCallback(); 10788 removeTapCallback(); 10789 onFocusLost(); 10790 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10791 imm.focusIn(this); 10792 } 10793 refreshDrawableState(); 10794 } 10795 10796 /** 10797 * Returns true if this view is in a window that currently has window focus. 10798 * Note that this is not the same as the view itself having focus. 10799 * 10800 * @return True if this view is in a window that currently has window focus. 10801 */ 10802 public boolean hasWindowFocus() { 10803 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10804 } 10805 10806 /** 10807 * Dispatch a view visibility change down the view hierarchy. 10808 * ViewGroups should override to route to their children. 10809 * @param changedView The view whose visibility changed. Could be 'this' or 10810 * an ancestor view. 10811 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10812 * {@link #INVISIBLE} or {@link #GONE}. 10813 */ 10814 protected void dispatchVisibilityChanged(@NonNull View changedView, 10815 @Visibility int visibility) { 10816 onVisibilityChanged(changedView, visibility); 10817 } 10818 10819 /** 10820 * Called when the visibility of the view or an ancestor of the view has 10821 * changed. 10822 * 10823 * @param changedView The view whose visibility changed. May be 10824 * {@code this} or an ancestor view. 10825 * @param visibility The new visibility, one of {@link #VISIBLE}, 10826 * {@link #INVISIBLE} or {@link #GONE}. 10827 */ 10828 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10829 } 10830 10831 /** 10832 * Dispatch a hint about whether this view is displayed. For instance, when 10833 * a View moves out of the screen, it might receives a display hint indicating 10834 * the view is not displayed. Applications should not <em>rely</em> on this hint 10835 * as there is no guarantee that they will receive one. 10836 * 10837 * @param hint A hint about whether or not this view is displayed: 10838 * {@link #VISIBLE} or {@link #INVISIBLE}. 10839 */ 10840 public void dispatchDisplayHint(@Visibility int hint) { 10841 onDisplayHint(hint); 10842 } 10843 10844 /** 10845 * Gives this view a hint about whether is displayed or not. For instance, when 10846 * a View moves out of the screen, it might receives a display hint indicating 10847 * the view is not displayed. Applications should not <em>rely</em> on this hint 10848 * as there is no guarantee that they will receive one. 10849 * 10850 * @param hint A hint about whether or not this view is displayed: 10851 * {@link #VISIBLE} or {@link #INVISIBLE}. 10852 */ 10853 protected void onDisplayHint(@Visibility int hint) { 10854 } 10855 10856 /** 10857 * Dispatch a window visibility change down the view hierarchy. 10858 * ViewGroups should override to route to their children. 10859 * 10860 * @param visibility The new visibility of the window. 10861 * 10862 * @see #onWindowVisibilityChanged(int) 10863 */ 10864 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10865 onWindowVisibilityChanged(visibility); 10866 } 10867 10868 /** 10869 * Called when the window containing has change its visibility 10870 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10871 * that this tells you whether or not your window is being made visible 10872 * to the window manager; this does <em>not</em> tell you whether or not 10873 * your window is obscured by other windows on the screen, even if it 10874 * is itself visible. 10875 * 10876 * @param visibility The new visibility of the window. 10877 */ 10878 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10879 if (visibility == VISIBLE) { 10880 initialAwakenScrollBars(); 10881 } 10882 } 10883 10884 /** 10885 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10886 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10887 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10888 * 10889 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10890 * ancestors or by window visibility 10891 * @return true if this view is visible to the user, not counting clipping or overlapping 10892 */ 10893 boolean dispatchVisibilityAggregated(boolean isVisible) { 10894 final boolean thisVisible = getVisibility() == VISIBLE; 10895 // If we're not visible but something is telling us we are, ignore it. 10896 if (thisVisible || !isVisible) { 10897 onVisibilityAggregated(isVisible); 10898 } 10899 return thisVisible && isVisible; 10900 } 10901 10902 /** 10903 * Called when the user-visibility of this View is potentially affected by a change 10904 * to this view itself, an ancestor view or the window this view is attached to. 10905 * 10906 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10907 * and this view's window is also visible 10908 */ 10909 @CallSuper 10910 public void onVisibilityAggregated(boolean isVisible) { 10911 if (isVisible && mAttachInfo != null) { 10912 initialAwakenScrollBars(); 10913 } 10914 10915 final Drawable dr = mBackground; 10916 if (dr != null && isVisible != dr.isVisible()) { 10917 dr.setVisible(isVisible, false); 10918 } 10919 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10920 if (fg != null && isVisible != fg.isVisible()) { 10921 fg.setVisible(isVisible, false); 10922 } 10923 } 10924 10925 /** 10926 * Returns the current visibility of the window this view is attached to 10927 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10928 * 10929 * @return Returns the current visibility of the view's window. 10930 */ 10931 @Visibility 10932 public int getWindowVisibility() { 10933 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10934 } 10935 10936 /** 10937 * Retrieve the overall visible display size in which the window this view is 10938 * attached to has been positioned in. This takes into account screen 10939 * decorations above the window, for both cases where the window itself 10940 * is being position inside of them or the window is being placed under 10941 * then and covered insets are used for the window to position its content 10942 * inside. In effect, this tells you the available area where content can 10943 * be placed and remain visible to users. 10944 * 10945 * <p>This function requires an IPC back to the window manager to retrieve 10946 * the requested information, so should not be used in performance critical 10947 * code like drawing. 10948 * 10949 * @param outRect Filled in with the visible display frame. If the view 10950 * is not attached to a window, this is simply the raw display size. 10951 */ 10952 public void getWindowVisibleDisplayFrame(Rect outRect) { 10953 if (mAttachInfo != null) { 10954 try { 10955 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10956 } catch (RemoteException e) { 10957 return; 10958 } 10959 // XXX This is really broken, and probably all needs to be done 10960 // in the window manager, and we need to know more about whether 10961 // we want the area behind or in front of the IME. 10962 final Rect insets = mAttachInfo.mVisibleInsets; 10963 outRect.left += insets.left; 10964 outRect.top += insets.top; 10965 outRect.right -= insets.right; 10966 outRect.bottom -= insets.bottom; 10967 return; 10968 } 10969 // The view is not attached to a display so we don't have a context. 10970 // Make a best guess about the display size. 10971 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10972 d.getRectSize(outRect); 10973 } 10974 10975 /** 10976 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10977 * is currently in without any insets. 10978 * 10979 * @hide 10980 */ 10981 public void getWindowDisplayFrame(Rect outRect) { 10982 if (mAttachInfo != null) { 10983 try { 10984 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10985 } catch (RemoteException e) { 10986 return; 10987 } 10988 return; 10989 } 10990 // The view is not attached to a display so we don't have a context. 10991 // Make a best guess about the display size. 10992 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10993 d.getRectSize(outRect); 10994 } 10995 10996 /** 10997 * Dispatch a notification about a resource configuration change down 10998 * the view hierarchy. 10999 * ViewGroups should override to route to their children. 11000 * 11001 * @param newConfig The new resource configuration. 11002 * 11003 * @see #onConfigurationChanged(android.content.res.Configuration) 11004 */ 11005 public void dispatchConfigurationChanged(Configuration newConfig) { 11006 onConfigurationChanged(newConfig); 11007 } 11008 11009 /** 11010 * Called when the current configuration of the resources being used 11011 * by the application have changed. You can use this to decide when 11012 * to reload resources that can changed based on orientation and other 11013 * configuration characteristics. You only need to use this if you are 11014 * not relying on the normal {@link android.app.Activity} mechanism of 11015 * recreating the activity instance upon a configuration change. 11016 * 11017 * @param newConfig The new resource configuration. 11018 */ 11019 protected void onConfigurationChanged(Configuration newConfig) { 11020 } 11021 11022 /** 11023 * Private function to aggregate all per-view attributes in to the view 11024 * root. 11025 */ 11026 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 11027 performCollectViewAttributes(attachInfo, visibility); 11028 } 11029 11030 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 11031 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 11032 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 11033 attachInfo.mKeepScreenOn = true; 11034 } 11035 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 11036 ListenerInfo li = mListenerInfo; 11037 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 11038 attachInfo.mHasSystemUiListeners = true; 11039 } 11040 } 11041 } 11042 11043 void needGlobalAttributesUpdate(boolean force) { 11044 final AttachInfo ai = mAttachInfo; 11045 if (ai != null && !ai.mRecomputeGlobalAttributes) { 11046 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 11047 || ai.mHasSystemUiListeners) { 11048 ai.mRecomputeGlobalAttributes = true; 11049 } 11050 } 11051 } 11052 11053 /** 11054 * Returns whether the device is currently in touch mode. Touch mode is entered 11055 * once the user begins interacting with the device by touch, and affects various 11056 * things like whether focus is always visible to the user. 11057 * 11058 * @return Whether the device is in touch mode. 11059 */ 11060 @ViewDebug.ExportedProperty 11061 public boolean isInTouchMode() { 11062 if (mAttachInfo != null) { 11063 return mAttachInfo.mInTouchMode; 11064 } else { 11065 return ViewRootImpl.isInTouchMode(); 11066 } 11067 } 11068 11069 /** 11070 * Returns the context the view is running in, through which it can 11071 * access the current theme, resources, etc. 11072 * 11073 * @return The view's Context. 11074 */ 11075 @ViewDebug.CapturedViewProperty 11076 public final Context getContext() { 11077 return mContext; 11078 } 11079 11080 /** 11081 * Handle a key event before it is processed by any input method 11082 * associated with the view hierarchy. This can be used to intercept 11083 * key events in special situations before the IME consumes them; a 11084 * typical example would be handling the BACK key to update the application's 11085 * UI instead of allowing the IME to see it and close itself. 11086 * 11087 * @param keyCode The value in event.getKeyCode(). 11088 * @param event Description of the key event. 11089 * @return If you handled the event, return true. If you want to allow the 11090 * event to be handled by the next receiver, return false. 11091 */ 11092 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 11093 return false; 11094 } 11095 11096 /** 11097 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 11098 * KeyEvent.Callback.onKeyDown()}: perform press of the view 11099 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 11100 * is released, if the view is enabled and clickable. 11101 * <p> 11102 * Key presses in software keyboards will generally NOT trigger this 11103 * listener, although some may elect to do so in some situations. Do not 11104 * rely on this to catch software key presses. 11105 * 11106 * @param keyCode a key code that represents the button pressed, from 11107 * {@link android.view.KeyEvent} 11108 * @param event the KeyEvent object that defines the button action 11109 */ 11110 public boolean onKeyDown(int keyCode, KeyEvent event) { 11111 if (KeyEvent.isConfirmKey(keyCode)) { 11112 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 11113 return true; 11114 } 11115 11116 if (event.getRepeatCount() == 0) { 11117 // Long clickable items don't necessarily have to be clickable. 11118 final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE 11119 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 11120 if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) { 11121 // For the purposes of menu anchoring and drawable hotspots, 11122 // key events are considered to be at the center of the view. 11123 final float x = getWidth() / 2f; 11124 final float y = getHeight() / 2f; 11125 if (clickable) { 11126 setPressed(true, x, y); 11127 } 11128 checkForLongClick(0, x, y); 11129 return true; 11130 } 11131 } 11132 } 11133 11134 return false; 11135 } 11136 11137 /** 11138 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 11139 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 11140 * the event). 11141 * <p>Key presses in software keyboards will generally NOT trigger this listener, 11142 * although some may elect to do so in some situations. Do not rely on this to 11143 * catch software key presses. 11144 */ 11145 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 11146 return false; 11147 } 11148 11149 /** 11150 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 11151 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 11152 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 11153 * or {@link KeyEvent#KEYCODE_SPACE} is released. 11154 * <p>Key presses in software keyboards will generally NOT trigger this listener, 11155 * although some may elect to do so in some situations. Do not rely on this to 11156 * catch software key presses. 11157 * 11158 * @param keyCode A key code that represents the button pressed, from 11159 * {@link android.view.KeyEvent}. 11160 * @param event The KeyEvent object that defines the button action. 11161 */ 11162 public boolean onKeyUp(int keyCode, KeyEvent event) { 11163 if (KeyEvent.isConfirmKey(keyCode)) { 11164 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 11165 return true; 11166 } 11167 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 11168 setPressed(false); 11169 11170 if (!mHasPerformedLongPress) { 11171 // This is a tap, so remove the longpress check 11172 removeLongPressCallback(); 11173 return performClick(); 11174 } 11175 } 11176 } 11177 return false; 11178 } 11179 11180 /** 11181 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 11182 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 11183 * the event). 11184 * <p>Key presses in software keyboards will generally NOT trigger this listener, 11185 * although some may elect to do so in some situations. Do not rely on this to 11186 * catch software key presses. 11187 * 11188 * @param keyCode A key code that represents the button pressed, from 11189 * {@link android.view.KeyEvent}. 11190 * @param repeatCount The number of times the action was made. 11191 * @param event The KeyEvent object that defines the button action. 11192 */ 11193 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 11194 return false; 11195 } 11196 11197 /** 11198 * Called on the focused view when a key shortcut event is not handled. 11199 * Override this method to implement local key shortcuts for the View. 11200 * Key shortcuts can also be implemented by setting the 11201 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 11202 * 11203 * @param keyCode The value in event.getKeyCode(). 11204 * @param event Description of the key event. 11205 * @return If you handled the event, return true. If you want to allow the 11206 * event to be handled by the next receiver, return false. 11207 */ 11208 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 11209 return false; 11210 } 11211 11212 /** 11213 * Check whether the called view is a text editor, in which case it 11214 * would make sense to automatically display a soft input window for 11215 * it. Subclasses should override this if they implement 11216 * {@link #onCreateInputConnection(EditorInfo)} to return true if 11217 * a call on that method would return a non-null InputConnection, and 11218 * they are really a first-class editor that the user would normally 11219 * start typing on when the go into a window containing your view. 11220 * 11221 * <p>The default implementation always returns false. This does 11222 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 11223 * will not be called or the user can not otherwise perform edits on your 11224 * view; it is just a hint to the system that this is not the primary 11225 * purpose of this view. 11226 * 11227 * @return Returns true if this view is a text editor, else false. 11228 */ 11229 public boolean onCheckIsTextEditor() { 11230 return false; 11231 } 11232 11233 /** 11234 * Create a new InputConnection for an InputMethod to interact 11235 * with the view. The default implementation returns null, since it doesn't 11236 * support input methods. You can override this to implement such support. 11237 * This is only needed for views that take focus and text input. 11238 * 11239 * <p>When implementing this, you probably also want to implement 11240 * {@link #onCheckIsTextEditor()} to indicate you will return a 11241 * non-null InputConnection.</p> 11242 * 11243 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 11244 * object correctly and in its entirety, so that the connected IME can rely 11245 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 11246 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 11247 * must be filled in with the correct cursor position for IMEs to work correctly 11248 * with your application.</p> 11249 * 11250 * @param outAttrs Fill in with attribute information about the connection. 11251 */ 11252 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 11253 return null; 11254 } 11255 11256 /** 11257 * Called by the {@link android.view.inputmethod.InputMethodManager} 11258 * when a view who is not the current 11259 * input connection target is trying to make a call on the manager. The 11260 * default implementation returns false; you can override this to return 11261 * true for certain views if you are performing InputConnection proxying 11262 * to them. 11263 * @param view The View that is making the InputMethodManager call. 11264 * @return Return true to allow the call, false to reject. 11265 */ 11266 public boolean checkInputConnectionProxy(View view) { 11267 return false; 11268 } 11269 11270 /** 11271 * Show the context menu for this view. It is not safe to hold on to the 11272 * menu after returning from this method. 11273 * 11274 * You should normally not overload this method. Overload 11275 * {@link #onCreateContextMenu(ContextMenu)} or define an 11276 * {@link OnCreateContextMenuListener} to add items to the context menu. 11277 * 11278 * @param menu The context menu to populate 11279 */ 11280 public void createContextMenu(ContextMenu menu) { 11281 ContextMenuInfo menuInfo = getContextMenuInfo(); 11282 11283 // Sets the current menu info so all items added to menu will have 11284 // my extra info set. 11285 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 11286 11287 onCreateContextMenu(menu); 11288 ListenerInfo li = mListenerInfo; 11289 if (li != null && li.mOnCreateContextMenuListener != null) { 11290 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 11291 } 11292 11293 // Clear the extra information so subsequent items that aren't mine don't 11294 // have my extra info. 11295 ((MenuBuilder)menu).setCurrentMenuInfo(null); 11296 11297 if (mParent != null) { 11298 mParent.createContextMenu(menu); 11299 } 11300 } 11301 11302 /** 11303 * Views should implement this if they have extra information to associate 11304 * with the context menu. The return result is supplied as a parameter to 11305 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 11306 * callback. 11307 * 11308 * @return Extra information about the item for which the context menu 11309 * should be shown. This information will vary across different 11310 * subclasses of View. 11311 */ 11312 protected ContextMenuInfo getContextMenuInfo() { 11313 return null; 11314 } 11315 11316 /** 11317 * Views should implement this if the view itself is going to add items to 11318 * the context menu. 11319 * 11320 * @param menu the context menu to populate 11321 */ 11322 protected void onCreateContextMenu(ContextMenu menu) { 11323 } 11324 11325 /** 11326 * Implement this method to handle trackball motion events. The 11327 * <em>relative</em> movement of the trackball since the last event 11328 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 11329 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 11330 * that a movement of 1 corresponds to the user pressing one DPAD key (so 11331 * they will often be fractional values, representing the more fine-grained 11332 * movement information available from a trackball). 11333 * 11334 * @param event The motion event. 11335 * @return True if the event was handled, false otherwise. 11336 */ 11337 public boolean onTrackballEvent(MotionEvent event) { 11338 return false; 11339 } 11340 11341 /** 11342 * Implement this method to handle generic motion events. 11343 * <p> 11344 * Generic motion events describe joystick movements, mouse hovers, track pad 11345 * touches, scroll wheel movements and other input events. The 11346 * {@link MotionEvent#getSource() source} of the motion event specifies 11347 * the class of input that was received. Implementations of this method 11348 * must examine the bits in the source before processing the event. 11349 * The following code example shows how this is done. 11350 * </p><p> 11351 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 11352 * are delivered to the view under the pointer. All other generic motion events are 11353 * delivered to the focused view. 11354 * </p> 11355 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 11356 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 11357 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 11358 * // process the joystick movement... 11359 * return true; 11360 * } 11361 * } 11362 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 11363 * switch (event.getAction()) { 11364 * case MotionEvent.ACTION_HOVER_MOVE: 11365 * // process the mouse hover movement... 11366 * return true; 11367 * case MotionEvent.ACTION_SCROLL: 11368 * // process the scroll wheel movement... 11369 * return true; 11370 * } 11371 * } 11372 * return super.onGenericMotionEvent(event); 11373 * }</pre> 11374 * 11375 * @param event The generic motion event being processed. 11376 * @return True if the event was handled, false otherwise. 11377 */ 11378 public boolean onGenericMotionEvent(MotionEvent event) { 11379 return false; 11380 } 11381 11382 /** 11383 * Implement this method to handle hover events. 11384 * <p> 11385 * This method is called whenever a pointer is hovering into, over, or out of the 11386 * bounds of a view and the view is not currently being touched. 11387 * Hover events are represented as pointer events with action 11388 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 11389 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 11390 * </p> 11391 * <ul> 11392 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 11393 * when the pointer enters the bounds of the view.</li> 11394 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 11395 * when the pointer has already entered the bounds of the view and has moved.</li> 11396 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 11397 * when the pointer has exited the bounds of the view or when the pointer is 11398 * about to go down due to a button click, tap, or similar user action that 11399 * causes the view to be touched.</li> 11400 * </ul> 11401 * <p> 11402 * The view should implement this method to return true to indicate that it is 11403 * handling the hover event, such as by changing its drawable state. 11404 * </p><p> 11405 * The default implementation calls {@link #setHovered} to update the hovered state 11406 * of the view when a hover enter or hover exit event is received, if the view 11407 * is enabled and is clickable. The default implementation also sends hover 11408 * accessibility events. 11409 * </p> 11410 * 11411 * @param event The motion event that describes the hover. 11412 * @return True if the view handled the hover event. 11413 * 11414 * @see #isHovered 11415 * @see #setHovered 11416 * @see #onHoverChanged 11417 */ 11418 public boolean onHoverEvent(MotionEvent event) { 11419 // The root view may receive hover (or touch) events that are outside the bounds of 11420 // the window. This code ensures that we only send accessibility events for 11421 // hovers that are actually within the bounds of the root view. 11422 final int action = event.getActionMasked(); 11423 if (!mSendingHoverAccessibilityEvents) { 11424 if ((action == MotionEvent.ACTION_HOVER_ENTER 11425 || action == MotionEvent.ACTION_HOVER_MOVE) 11426 && !hasHoveredChild() 11427 && pointInView(event.getX(), event.getY())) { 11428 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 11429 mSendingHoverAccessibilityEvents = true; 11430 } 11431 } else { 11432 if (action == MotionEvent.ACTION_HOVER_EXIT 11433 || (action == MotionEvent.ACTION_MOVE 11434 && !pointInView(event.getX(), event.getY()))) { 11435 mSendingHoverAccessibilityEvents = false; 11436 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 11437 } 11438 } 11439 11440 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 11441 && event.isFromSource(InputDevice.SOURCE_MOUSE) 11442 && isOnScrollbar(event.getX(), event.getY())) { 11443 awakenScrollBars(); 11444 } 11445 if (isHoverable()) { 11446 switch (action) { 11447 case MotionEvent.ACTION_HOVER_ENTER: 11448 setHovered(true); 11449 break; 11450 case MotionEvent.ACTION_HOVER_EXIT: 11451 setHovered(false); 11452 break; 11453 } 11454 11455 // Dispatch the event to onGenericMotionEvent before returning true. 11456 // This is to provide compatibility with existing applications that 11457 // handled HOVER_MOVE events in onGenericMotionEvent and that would 11458 // break because of the new default handling for hoverable views 11459 // in onHoverEvent. 11460 // Note that onGenericMotionEvent will be called by default when 11461 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 11462 dispatchGenericMotionEventInternal(event); 11463 // The event was already handled by calling setHovered(), so always 11464 // return true. 11465 return true; 11466 } 11467 11468 return false; 11469 } 11470 11471 /** 11472 * Returns true if the view should handle {@link #onHoverEvent} 11473 * by calling {@link #setHovered} to change its hovered state. 11474 * 11475 * @return True if the view is hoverable. 11476 */ 11477 private boolean isHoverable() { 11478 final int viewFlags = mViewFlags; 11479 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11480 return false; 11481 } 11482 11483 return (viewFlags & CLICKABLE) == CLICKABLE 11484 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 11485 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 11486 } 11487 11488 /** 11489 * Returns true if the view is currently hovered. 11490 * 11491 * @return True if the view is currently hovered. 11492 * 11493 * @see #setHovered 11494 * @see #onHoverChanged 11495 */ 11496 @ViewDebug.ExportedProperty 11497 public boolean isHovered() { 11498 return (mPrivateFlags & PFLAG_HOVERED) != 0; 11499 } 11500 11501 /** 11502 * Sets whether the view is currently hovered. 11503 * <p> 11504 * Calling this method also changes the drawable state of the view. This 11505 * enables the view to react to hover by using different drawable resources 11506 * to change its appearance. 11507 * </p><p> 11508 * The {@link #onHoverChanged} method is called when the hovered state changes. 11509 * </p> 11510 * 11511 * @param hovered True if the view is hovered. 11512 * 11513 * @see #isHovered 11514 * @see #onHoverChanged 11515 */ 11516 public void setHovered(boolean hovered) { 11517 if (hovered) { 11518 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 11519 mPrivateFlags |= PFLAG_HOVERED; 11520 refreshDrawableState(); 11521 onHoverChanged(true); 11522 } 11523 } else { 11524 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 11525 mPrivateFlags &= ~PFLAG_HOVERED; 11526 refreshDrawableState(); 11527 onHoverChanged(false); 11528 } 11529 } 11530 } 11531 11532 /** 11533 * Implement this method to handle hover state changes. 11534 * <p> 11535 * This method is called whenever the hover state changes as a result of a 11536 * call to {@link #setHovered}. 11537 * </p> 11538 * 11539 * @param hovered The current hover state, as returned by {@link #isHovered}. 11540 * 11541 * @see #isHovered 11542 * @see #setHovered 11543 */ 11544 public void onHoverChanged(boolean hovered) { 11545 } 11546 11547 /** 11548 * Handles scroll bar dragging by mouse input. 11549 * 11550 * @hide 11551 * @param event The motion event. 11552 * 11553 * @return true if the event was handled as a scroll bar dragging, false otherwise. 11554 */ 11555 protected boolean handleScrollBarDragging(MotionEvent event) { 11556 if (mScrollCache == null) { 11557 return false; 11558 } 11559 final float x = event.getX(); 11560 final float y = event.getY(); 11561 final int action = event.getAction(); 11562 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 11563 && action != MotionEvent.ACTION_DOWN) 11564 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 11565 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 11566 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11567 return false; 11568 } 11569 11570 switch (action) { 11571 case MotionEvent.ACTION_MOVE: 11572 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 11573 return false; 11574 } 11575 if (mScrollCache.mScrollBarDraggingState 11576 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 11577 final Rect bounds = mScrollCache.mScrollBarBounds; 11578 getVerticalScrollBarBounds(bounds); 11579 final int range = computeVerticalScrollRange(); 11580 final int offset = computeVerticalScrollOffset(); 11581 final int extent = computeVerticalScrollExtent(); 11582 11583 final int thumbLength = ScrollBarUtils.getThumbLength( 11584 bounds.height(), bounds.width(), extent, range); 11585 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11586 bounds.height(), thumbLength, extent, range, offset); 11587 11588 final float diff = y - mScrollCache.mScrollBarDraggingPos; 11589 final float maxThumbOffset = bounds.height() - thumbLength; 11590 final float newThumbOffset = 11591 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11592 final int height = getHeight(); 11593 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11594 && height > 0 && extent > 0) { 11595 final int newY = Math.round((range - extent) 11596 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 11597 if (newY != getScrollY()) { 11598 mScrollCache.mScrollBarDraggingPos = y; 11599 setScrollY(newY); 11600 } 11601 } 11602 return true; 11603 } 11604 if (mScrollCache.mScrollBarDraggingState 11605 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 11606 final Rect bounds = mScrollCache.mScrollBarBounds; 11607 getHorizontalScrollBarBounds(bounds); 11608 final int range = computeHorizontalScrollRange(); 11609 final int offset = computeHorizontalScrollOffset(); 11610 final int extent = computeHorizontalScrollExtent(); 11611 11612 final int thumbLength = ScrollBarUtils.getThumbLength( 11613 bounds.width(), bounds.height(), extent, range); 11614 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11615 bounds.width(), thumbLength, extent, range, offset); 11616 11617 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11618 final float maxThumbOffset = bounds.width() - thumbLength; 11619 final float newThumbOffset = 11620 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11621 final int width = getWidth(); 11622 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11623 && width > 0 && extent > 0) { 11624 final int newX = Math.round((range - extent) 11625 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11626 if (newX != getScrollX()) { 11627 mScrollCache.mScrollBarDraggingPos = x; 11628 setScrollX(newX); 11629 } 11630 } 11631 return true; 11632 } 11633 case MotionEvent.ACTION_DOWN: 11634 if (mScrollCache.state == ScrollabilityCache.OFF) { 11635 return false; 11636 } 11637 if (isOnVerticalScrollbarThumb(x, y)) { 11638 mScrollCache.mScrollBarDraggingState = 11639 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11640 mScrollCache.mScrollBarDraggingPos = y; 11641 return true; 11642 } 11643 if (isOnHorizontalScrollbarThumb(x, y)) { 11644 mScrollCache.mScrollBarDraggingState = 11645 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11646 mScrollCache.mScrollBarDraggingPos = x; 11647 return true; 11648 } 11649 } 11650 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11651 return false; 11652 } 11653 11654 /** 11655 * Implement this method to handle touch screen motion events. 11656 * <p> 11657 * If this method is used to detect click actions, it is recommended that 11658 * the actions be performed by implementing and calling 11659 * {@link #performClick()}. This will ensure consistent system behavior, 11660 * including: 11661 * <ul> 11662 * <li>obeying click sound preferences 11663 * <li>dispatching OnClickListener calls 11664 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11665 * accessibility features are enabled 11666 * </ul> 11667 * 11668 * @param event The motion event. 11669 * @return True if the event was handled, false otherwise. 11670 */ 11671 public boolean onTouchEvent(MotionEvent event) { 11672 final float x = event.getX(); 11673 final float y = event.getY(); 11674 final int viewFlags = mViewFlags; 11675 final int action = event.getAction(); 11676 11677 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE 11678 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11679 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 11680 11681 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11682 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11683 setPressed(false); 11684 } 11685 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11686 // A disabled view that is clickable still consumes the touch 11687 // events, it just doesn't respond to them. 11688 return clickable; 11689 } 11690 if (mTouchDelegate != null) { 11691 if (mTouchDelegate.onTouchEvent(event)) { 11692 return true; 11693 } 11694 } 11695 11696 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { 11697 switch (action) { 11698 case MotionEvent.ACTION_UP: 11699 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11700 if ((viewFlags & TOOLTIP) == TOOLTIP) { 11701 handleTooltipUp(); 11702 } 11703 if (!clickable) { 11704 removeTapCallback(); 11705 removeLongPressCallback(); 11706 mInContextButtonPress = false; 11707 mHasPerformedLongPress = false; 11708 mIgnoreNextUpEvent = false; 11709 break; 11710 } 11711 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11712 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11713 // take focus if we don't have it already and we should in 11714 // touch mode. 11715 boolean focusTaken = false; 11716 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11717 focusTaken = requestFocus(); 11718 } 11719 11720 if (prepressed) { 11721 // The button is being released before we actually 11722 // showed it as pressed. Make it show the pressed 11723 // state now (before scheduling the click) to ensure 11724 // the user sees it. 11725 setPressed(true, x, y); 11726 } 11727 11728 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11729 // This is a tap, so remove the longpress check 11730 removeLongPressCallback(); 11731 11732 // Only perform take click actions if we were in the pressed state 11733 if (!focusTaken) { 11734 // Use a Runnable and post this rather than calling 11735 // performClick directly. This lets other visual state 11736 // of the view update before click actions start. 11737 if (mPerformClick == null) { 11738 mPerformClick = new PerformClick(); 11739 } 11740 if (!post(mPerformClick)) { 11741 performClick(); 11742 } 11743 } 11744 } 11745 11746 if (mUnsetPressedState == null) { 11747 mUnsetPressedState = new UnsetPressedState(); 11748 } 11749 11750 if (prepressed) { 11751 postDelayed(mUnsetPressedState, 11752 ViewConfiguration.getPressedStateDuration()); 11753 } else if (!post(mUnsetPressedState)) { 11754 // If the post failed, unpress right now 11755 mUnsetPressedState.run(); 11756 } 11757 11758 removeTapCallback(); 11759 } 11760 mIgnoreNextUpEvent = false; 11761 break; 11762 11763 case MotionEvent.ACTION_DOWN: 11764 if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { 11765 mPrivateFlags3 |= PFLAG3_FINGER_DOWN; 11766 } 11767 mHasPerformedLongPress = false; 11768 11769 if (!clickable) { 11770 checkForLongClick(0, x, y); 11771 break; 11772 } 11773 11774 if (performButtonActionOnTouchDown(event)) { 11775 break; 11776 } 11777 11778 // Walk up the hierarchy to determine if we're inside a scrolling container. 11779 boolean isInScrollingContainer = isInScrollingContainer(); 11780 11781 // For views inside a scrolling container, delay the pressed feedback for 11782 // a short period in case this is a scroll. 11783 if (isInScrollingContainer) { 11784 mPrivateFlags |= PFLAG_PREPRESSED; 11785 if (mPendingCheckForTap == null) { 11786 mPendingCheckForTap = new CheckForTap(); 11787 } 11788 mPendingCheckForTap.x = event.getX(); 11789 mPendingCheckForTap.y = event.getY(); 11790 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11791 } else { 11792 // Not inside a scrolling container, so show the feedback right away 11793 setPressed(true, x, y); 11794 checkForLongClick(0, x, y); 11795 } 11796 break; 11797 11798 case MotionEvent.ACTION_CANCEL: 11799 if (clickable) { 11800 setPressed(false); 11801 } 11802 removeTapCallback(); 11803 removeLongPressCallback(); 11804 mInContextButtonPress = false; 11805 mHasPerformedLongPress = false; 11806 mIgnoreNextUpEvent = false; 11807 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11808 break; 11809 11810 case MotionEvent.ACTION_MOVE: 11811 if (clickable) { 11812 drawableHotspotChanged(x, y); 11813 } 11814 11815 // Be lenient about moving outside of buttons 11816 if (!pointInView(x, y, mTouchSlop)) { 11817 // Outside button 11818 // Remove any future long press/tap checks 11819 removeTapCallback(); 11820 removeLongPressCallback(); 11821 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11822 setPressed(false); 11823 } 11824 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11825 } 11826 break; 11827 } 11828 11829 return true; 11830 } 11831 11832 return false; 11833 } 11834 11835 /** 11836 * @hide 11837 */ 11838 public boolean isInScrollingContainer() { 11839 ViewParent p = getParent(); 11840 while (p != null && p instanceof ViewGroup) { 11841 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11842 return true; 11843 } 11844 p = p.getParent(); 11845 } 11846 return false; 11847 } 11848 11849 /** 11850 * Remove the longpress detection timer. 11851 */ 11852 private void removeLongPressCallback() { 11853 if (mPendingCheckForLongPress != null) { 11854 removeCallbacks(mPendingCheckForLongPress); 11855 } 11856 } 11857 11858 /** 11859 * Remove the pending click action 11860 */ 11861 private void removePerformClickCallback() { 11862 if (mPerformClick != null) { 11863 removeCallbacks(mPerformClick); 11864 } 11865 } 11866 11867 /** 11868 * Remove the prepress detection timer. 11869 */ 11870 private void removeUnsetPressCallback() { 11871 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11872 setPressed(false); 11873 removeCallbacks(mUnsetPressedState); 11874 } 11875 } 11876 11877 /** 11878 * Remove the tap detection timer. 11879 */ 11880 private void removeTapCallback() { 11881 if (mPendingCheckForTap != null) { 11882 mPrivateFlags &= ~PFLAG_PREPRESSED; 11883 removeCallbacks(mPendingCheckForTap); 11884 } 11885 } 11886 11887 /** 11888 * Cancels a pending long press. Your subclass can use this if you 11889 * want the context menu to come up if the user presses and holds 11890 * at the same place, but you don't want it to come up if they press 11891 * and then move around enough to cause scrolling. 11892 */ 11893 public void cancelLongPress() { 11894 removeLongPressCallback(); 11895 11896 /* 11897 * The prepressed state handled by the tap callback is a display 11898 * construct, but the tap callback will post a long press callback 11899 * less its own timeout. Remove it here. 11900 */ 11901 removeTapCallback(); 11902 } 11903 11904 /** 11905 * Remove the pending callback for sending a 11906 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11907 */ 11908 private void removeSendViewScrolledAccessibilityEventCallback() { 11909 if (mSendViewScrolledAccessibilityEvent != null) { 11910 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11911 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11912 } 11913 } 11914 11915 /** 11916 * Sets the TouchDelegate for this View. 11917 */ 11918 public void setTouchDelegate(TouchDelegate delegate) { 11919 mTouchDelegate = delegate; 11920 } 11921 11922 /** 11923 * Gets the TouchDelegate for this View. 11924 */ 11925 public TouchDelegate getTouchDelegate() { 11926 return mTouchDelegate; 11927 } 11928 11929 /** 11930 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11931 * 11932 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11933 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11934 * available. This method should only be called for touch events. 11935 * 11936 * <p class="note">This api is not intended for most applications. Buffered dispatch 11937 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11938 * streams will not improve your input latency. Side effects include: increased latency, 11939 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11940 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11941 * you.</p> 11942 */ 11943 public final void requestUnbufferedDispatch(MotionEvent event) { 11944 final int action = event.getAction(); 11945 if (mAttachInfo == null 11946 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11947 || !event.isTouchEvent()) { 11948 return; 11949 } 11950 mAttachInfo.mUnbufferedDispatchRequested = true; 11951 } 11952 11953 /** 11954 * Set flags controlling behavior of this view. 11955 * 11956 * @param flags Constant indicating the value which should be set 11957 * @param mask Constant indicating the bit range that should be changed 11958 */ 11959 void setFlags(int flags, int mask) { 11960 final boolean accessibilityEnabled = 11961 AccessibilityManager.getInstance(mContext).isEnabled(); 11962 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11963 11964 int old = mViewFlags; 11965 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11966 11967 int changed = mViewFlags ^ old; 11968 if (changed == 0) { 11969 return; 11970 } 11971 int privateFlags = mPrivateFlags; 11972 11973 /* Check if the FOCUSABLE bit has changed */ 11974 if (((changed & FOCUSABLE_MASK) != 0) && 11975 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11976 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11977 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11978 /* Give up focus if we are no longer focusable */ 11979 clearFocus(); 11980 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11981 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11982 /* 11983 * Tell the view system that we are now available to take focus 11984 * if no one else already has it. 11985 */ 11986 if (mParent != null) mParent.focusableViewAvailable(this); 11987 } 11988 } 11989 11990 final int newVisibility = flags & VISIBILITY_MASK; 11991 if (newVisibility == VISIBLE) { 11992 if ((changed & VISIBILITY_MASK) != 0) { 11993 /* 11994 * If this view is becoming visible, invalidate it in case it changed while 11995 * it was not visible. Marking it drawn ensures that the invalidation will 11996 * go through. 11997 */ 11998 mPrivateFlags |= PFLAG_DRAWN; 11999 invalidate(true); 12000 12001 needGlobalAttributesUpdate(true); 12002 12003 // a view becoming visible is worth notifying the parent 12004 // about in case nothing has focus. even if this specific view 12005 // isn't focusable, it may contain something that is, so let 12006 // the root view try to give this focus if nothing else does. 12007 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 12008 mParent.focusableViewAvailable(this); 12009 } 12010 } 12011 } 12012 12013 /* Check if the GONE bit has changed */ 12014 if ((changed & GONE) != 0) { 12015 needGlobalAttributesUpdate(false); 12016 requestLayout(); 12017 12018 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 12019 if (hasFocus()) clearFocus(); 12020 clearAccessibilityFocus(); 12021 destroyDrawingCache(); 12022 if (mParent instanceof View) { 12023 // GONE views noop invalidation, so invalidate the parent 12024 ((View) mParent).invalidate(true); 12025 } 12026 // Mark the view drawn to ensure that it gets invalidated properly the next 12027 // time it is visible and gets invalidated 12028 mPrivateFlags |= PFLAG_DRAWN; 12029 } 12030 if (mAttachInfo != null) { 12031 mAttachInfo.mViewVisibilityChanged = true; 12032 } 12033 } 12034 12035 /* Check if the VISIBLE bit has changed */ 12036 if ((changed & INVISIBLE) != 0) { 12037 needGlobalAttributesUpdate(false); 12038 /* 12039 * If this view is becoming invisible, set the DRAWN flag so that 12040 * the next invalidate() will not be skipped. 12041 */ 12042 mPrivateFlags |= PFLAG_DRAWN; 12043 12044 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 12045 // root view becoming invisible shouldn't clear focus and accessibility focus 12046 if (getRootView() != this) { 12047 if (hasFocus()) clearFocus(); 12048 clearAccessibilityFocus(); 12049 } 12050 } 12051 if (mAttachInfo != null) { 12052 mAttachInfo.mViewVisibilityChanged = true; 12053 } 12054 } 12055 12056 if ((changed & VISIBILITY_MASK) != 0) { 12057 // If the view is invisible, cleanup its display list to free up resources 12058 if (newVisibility != VISIBLE && mAttachInfo != null) { 12059 cleanupDraw(); 12060 } 12061 12062 if (mParent instanceof ViewGroup) { 12063 ((ViewGroup) mParent).onChildVisibilityChanged(this, 12064 (changed & VISIBILITY_MASK), newVisibility); 12065 ((View) mParent).invalidate(true); 12066 } else if (mParent != null) { 12067 mParent.invalidateChild(this, null); 12068 } 12069 12070 if (mAttachInfo != null) { 12071 dispatchVisibilityChanged(this, newVisibility); 12072 12073 // Aggregated visibility changes are dispatched to attached views 12074 // in visible windows where the parent is currently shown/drawn 12075 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 12076 // discounting clipping or overlapping. This makes it a good place 12077 // to change animation states. 12078 if (mParent != null && getWindowVisibility() == VISIBLE && 12079 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 12080 dispatchVisibilityAggregated(newVisibility == VISIBLE); 12081 } 12082 notifySubtreeAccessibilityStateChangedIfNeeded(); 12083 } 12084 } 12085 12086 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 12087 destroyDrawingCache(); 12088 } 12089 12090 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 12091 destroyDrawingCache(); 12092 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12093 invalidateParentCaches(); 12094 } 12095 12096 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 12097 destroyDrawingCache(); 12098 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12099 } 12100 12101 if ((changed & DRAW_MASK) != 0) { 12102 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 12103 if (mBackground != null 12104 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 12105 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 12106 } else { 12107 mPrivateFlags |= PFLAG_SKIP_DRAW; 12108 } 12109 } else { 12110 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 12111 } 12112 requestLayout(); 12113 invalidate(true); 12114 } 12115 12116 if ((changed & KEEP_SCREEN_ON) != 0) { 12117 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12118 mParent.recomputeViewAttributes(this); 12119 } 12120 } 12121 12122 if (accessibilityEnabled) { 12123 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 12124 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 12125 || (changed & CONTEXT_CLICKABLE) != 0) { 12126 if (oldIncludeForAccessibility != includeForAccessibility()) { 12127 notifySubtreeAccessibilityStateChangedIfNeeded(); 12128 } else { 12129 notifyViewAccessibilityStateChangedIfNeeded( 12130 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12131 } 12132 } else if ((changed & ENABLED_MASK) != 0) { 12133 notifyViewAccessibilityStateChangedIfNeeded( 12134 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12135 } 12136 } 12137 } 12138 12139 /** 12140 * Change the view's z order in the tree, so it's on top of other sibling 12141 * views. This ordering change may affect layout, if the parent container 12142 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 12143 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 12144 * method should be followed by calls to {@link #requestLayout()} and 12145 * {@link View#invalidate()} on the view's parent to force the parent to redraw 12146 * with the new child ordering. 12147 * 12148 * @see ViewGroup#bringChildToFront(View) 12149 */ 12150 public void bringToFront() { 12151 if (mParent != null) { 12152 mParent.bringChildToFront(this); 12153 } 12154 } 12155 12156 /** 12157 * This is called in response to an internal scroll in this view (i.e., the 12158 * view scrolled its own contents). This is typically as a result of 12159 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 12160 * called. 12161 * 12162 * @param l Current horizontal scroll origin. 12163 * @param t Current vertical scroll origin. 12164 * @param oldl Previous horizontal scroll origin. 12165 * @param oldt Previous vertical scroll origin. 12166 */ 12167 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 12168 notifySubtreeAccessibilityStateChangedIfNeeded(); 12169 12170 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 12171 postSendViewScrolledAccessibilityEventCallback(); 12172 } 12173 12174 mBackgroundSizeChanged = true; 12175 if (mForegroundInfo != null) { 12176 mForegroundInfo.mBoundsChanged = true; 12177 } 12178 12179 final AttachInfo ai = mAttachInfo; 12180 if (ai != null) { 12181 ai.mViewScrollChanged = true; 12182 } 12183 12184 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 12185 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 12186 } 12187 } 12188 12189 /** 12190 * Interface definition for a callback to be invoked when the scroll 12191 * X or Y positions of a view change. 12192 * <p> 12193 * <b>Note:</b> Some views handle scrolling independently from View and may 12194 * have their own separate listeners for scroll-type events. For example, 12195 * {@link android.widget.ListView ListView} allows clients to register an 12196 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 12197 * to listen for changes in list scroll position. 12198 * 12199 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 12200 */ 12201 public interface OnScrollChangeListener { 12202 /** 12203 * Called when the scroll position of a view changes. 12204 * 12205 * @param v The view whose scroll position has changed. 12206 * @param scrollX Current horizontal scroll origin. 12207 * @param scrollY Current vertical scroll origin. 12208 * @param oldScrollX Previous horizontal scroll origin. 12209 * @param oldScrollY Previous vertical scroll origin. 12210 */ 12211 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 12212 } 12213 12214 /** 12215 * Interface definition for a callback to be invoked when the layout bounds of a view 12216 * changes due to layout processing. 12217 */ 12218 public interface OnLayoutChangeListener { 12219 /** 12220 * Called when the layout bounds of a view changes due to layout processing. 12221 * 12222 * @param v The view whose bounds have changed. 12223 * @param left The new value of the view's left property. 12224 * @param top The new value of the view's top property. 12225 * @param right The new value of the view's right property. 12226 * @param bottom The new value of the view's bottom property. 12227 * @param oldLeft The previous value of the view's left property. 12228 * @param oldTop The previous value of the view's top property. 12229 * @param oldRight The previous value of the view's right property. 12230 * @param oldBottom The previous value of the view's bottom property. 12231 */ 12232 void onLayoutChange(View v, int left, int top, int right, int bottom, 12233 int oldLeft, int oldTop, int oldRight, int oldBottom); 12234 } 12235 12236 /** 12237 * This is called during layout when the size of this view has changed. If 12238 * you were just added to the view hierarchy, you're called with the old 12239 * values of 0. 12240 * 12241 * @param w Current width of this view. 12242 * @param h Current height of this view. 12243 * @param oldw Old width of this view. 12244 * @param oldh Old height of this view. 12245 */ 12246 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 12247 } 12248 12249 /** 12250 * Called by draw to draw the child views. This may be overridden 12251 * by derived classes to gain control just before its children are drawn 12252 * (but after its own view has been drawn). 12253 * @param canvas the canvas on which to draw the view 12254 */ 12255 protected void dispatchDraw(Canvas canvas) { 12256 12257 } 12258 12259 /** 12260 * Gets the parent of this view. Note that the parent is a 12261 * ViewParent and not necessarily a View. 12262 * 12263 * @return Parent of this view. 12264 */ 12265 public final ViewParent getParent() { 12266 return mParent; 12267 } 12268 12269 /** 12270 * Set the horizontal scrolled position of your view. This will cause a call to 12271 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12272 * invalidated. 12273 * @param value the x position to scroll to 12274 */ 12275 public void setScrollX(int value) { 12276 scrollTo(value, mScrollY); 12277 } 12278 12279 /** 12280 * Set the vertical scrolled position of your view. This will cause a call to 12281 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12282 * invalidated. 12283 * @param value the y position to scroll to 12284 */ 12285 public void setScrollY(int value) { 12286 scrollTo(mScrollX, value); 12287 } 12288 12289 /** 12290 * Return the scrolled left position of this view. This is the left edge of 12291 * the displayed part of your view. You do not need to draw any pixels 12292 * farther left, since those are outside of the frame of your view on 12293 * screen. 12294 * 12295 * @return The left edge of the displayed part of your view, in pixels. 12296 */ 12297 public final int getScrollX() { 12298 return mScrollX; 12299 } 12300 12301 /** 12302 * Return the scrolled top position of this view. This is the top edge of 12303 * the displayed part of your view. You do not need to draw any pixels above 12304 * it, since those are outside of the frame of your view on screen. 12305 * 12306 * @return The top edge of the displayed part of your view, in pixels. 12307 */ 12308 public final int getScrollY() { 12309 return mScrollY; 12310 } 12311 12312 /** 12313 * Return the width of the your view. 12314 * 12315 * @return The width of your view, in pixels. 12316 */ 12317 @ViewDebug.ExportedProperty(category = "layout") 12318 public final int getWidth() { 12319 return mRight - mLeft; 12320 } 12321 12322 /** 12323 * Return the height of your view. 12324 * 12325 * @return The height of your view, in pixels. 12326 */ 12327 @ViewDebug.ExportedProperty(category = "layout") 12328 public final int getHeight() { 12329 return mBottom - mTop; 12330 } 12331 12332 /** 12333 * Return the visible drawing bounds of your view. Fills in the output 12334 * rectangle with the values from getScrollX(), getScrollY(), 12335 * getWidth(), and getHeight(). These bounds do not account for any 12336 * transformation properties currently set on the view, such as 12337 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 12338 * 12339 * @param outRect The (scrolled) drawing bounds of the view. 12340 */ 12341 public void getDrawingRect(Rect outRect) { 12342 outRect.left = mScrollX; 12343 outRect.top = mScrollY; 12344 outRect.right = mScrollX + (mRight - mLeft); 12345 outRect.bottom = mScrollY + (mBottom - mTop); 12346 } 12347 12348 /** 12349 * Like {@link #getMeasuredWidthAndState()}, but only returns the 12350 * raw width component (that is the result is masked by 12351 * {@link #MEASURED_SIZE_MASK}). 12352 * 12353 * @return The raw measured width of this view. 12354 */ 12355 public final int getMeasuredWidth() { 12356 return mMeasuredWidth & MEASURED_SIZE_MASK; 12357 } 12358 12359 /** 12360 * Return the full width measurement information for this view as computed 12361 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 12362 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12363 * This should be used during measurement and layout calculations only. Use 12364 * {@link #getWidth()} to see how wide a view is after layout. 12365 * 12366 * @return The measured width of this view as a bit mask. 12367 */ 12368 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 12369 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 12370 name = "MEASURED_STATE_TOO_SMALL"), 12371 }) 12372 public final int getMeasuredWidthAndState() { 12373 return mMeasuredWidth; 12374 } 12375 12376 /** 12377 * Like {@link #getMeasuredHeightAndState()}, but only returns the 12378 * raw height component (that is the result is masked by 12379 * {@link #MEASURED_SIZE_MASK}). 12380 * 12381 * @return The raw measured height of this view. 12382 */ 12383 public final int getMeasuredHeight() { 12384 return mMeasuredHeight & MEASURED_SIZE_MASK; 12385 } 12386 12387 /** 12388 * Return the full height measurement information for this view as computed 12389 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 12390 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 12391 * This should be used during measurement and layout calculations only. Use 12392 * {@link #getHeight()} to see how wide a view is after layout. 12393 * 12394 * @return The measured height of this view as a bit mask. 12395 */ 12396 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 12397 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 12398 name = "MEASURED_STATE_TOO_SMALL"), 12399 }) 12400 public final int getMeasuredHeightAndState() { 12401 return mMeasuredHeight; 12402 } 12403 12404 /** 12405 * Return only the state bits of {@link #getMeasuredWidthAndState()} 12406 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 12407 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 12408 * and the height component is at the shifted bits 12409 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 12410 */ 12411 public final int getMeasuredState() { 12412 return (mMeasuredWidth&MEASURED_STATE_MASK) 12413 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 12414 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 12415 } 12416 12417 /** 12418 * The transform matrix of this view, which is calculated based on the current 12419 * rotation, scale, and pivot properties. 12420 * 12421 * @see #getRotation() 12422 * @see #getScaleX() 12423 * @see #getScaleY() 12424 * @see #getPivotX() 12425 * @see #getPivotY() 12426 * @return The current transform matrix for the view 12427 */ 12428 public Matrix getMatrix() { 12429 ensureTransformationInfo(); 12430 final Matrix matrix = mTransformationInfo.mMatrix; 12431 mRenderNode.getMatrix(matrix); 12432 return matrix; 12433 } 12434 12435 /** 12436 * Returns true if the transform matrix is the identity matrix. 12437 * Recomputes the matrix if necessary. 12438 * 12439 * @return True if the transform matrix is the identity matrix, false otherwise. 12440 */ 12441 final boolean hasIdentityMatrix() { 12442 return mRenderNode.hasIdentityMatrix(); 12443 } 12444 12445 void ensureTransformationInfo() { 12446 if (mTransformationInfo == null) { 12447 mTransformationInfo = new TransformationInfo(); 12448 } 12449 } 12450 12451 /** 12452 * Utility method to retrieve the inverse of the current mMatrix property. 12453 * We cache the matrix to avoid recalculating it when transform properties 12454 * have not changed. 12455 * 12456 * @return The inverse of the current matrix of this view. 12457 * @hide 12458 */ 12459 public final Matrix getInverseMatrix() { 12460 ensureTransformationInfo(); 12461 if (mTransformationInfo.mInverseMatrix == null) { 12462 mTransformationInfo.mInverseMatrix = new Matrix(); 12463 } 12464 final Matrix matrix = mTransformationInfo.mInverseMatrix; 12465 mRenderNode.getInverseMatrix(matrix); 12466 return matrix; 12467 } 12468 12469 /** 12470 * Gets the distance along the Z axis from the camera to this view. 12471 * 12472 * @see #setCameraDistance(float) 12473 * 12474 * @return The distance along the Z axis. 12475 */ 12476 public float getCameraDistance() { 12477 final float dpi = mResources.getDisplayMetrics().densityDpi; 12478 return -(mRenderNode.getCameraDistance() * dpi); 12479 } 12480 12481 /** 12482 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 12483 * views are drawn) from the camera to this view. The camera's distance 12484 * affects 3D transformations, for instance rotations around the X and Y 12485 * axis. If the rotationX or rotationY properties are changed and this view is 12486 * large (more than half the size of the screen), it is recommended to always 12487 * use a camera distance that's greater than the height (X axis rotation) or 12488 * the width (Y axis rotation) of this view.</p> 12489 * 12490 * <p>The distance of the camera from the view plane can have an affect on the 12491 * perspective distortion of the view when it is rotated around the x or y axis. 12492 * For example, a large distance will result in a large viewing angle, and there 12493 * will not be much perspective distortion of the view as it rotates. A short 12494 * distance may cause much more perspective distortion upon rotation, and can 12495 * also result in some drawing artifacts if the rotated view ends up partially 12496 * behind the camera (which is why the recommendation is to use a distance at 12497 * least as far as the size of the view, if the view is to be rotated.)</p> 12498 * 12499 * <p>The distance is expressed in "depth pixels." The default distance depends 12500 * on the screen density. For instance, on a medium density display, the 12501 * default distance is 1280. On a high density display, the default distance 12502 * is 1920.</p> 12503 * 12504 * <p>If you want to specify a distance that leads to visually consistent 12505 * results across various densities, use the following formula:</p> 12506 * <pre> 12507 * float scale = context.getResources().getDisplayMetrics().density; 12508 * view.setCameraDistance(distance * scale); 12509 * </pre> 12510 * 12511 * <p>The density scale factor of a high density display is 1.5, 12512 * and 1920 = 1280 * 1.5.</p> 12513 * 12514 * @param distance The distance in "depth pixels", if negative the opposite 12515 * value is used 12516 * 12517 * @see #setRotationX(float) 12518 * @see #setRotationY(float) 12519 */ 12520 public void setCameraDistance(float distance) { 12521 final float dpi = mResources.getDisplayMetrics().densityDpi; 12522 12523 invalidateViewProperty(true, false); 12524 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 12525 invalidateViewProperty(false, false); 12526 12527 invalidateParentIfNeededAndWasQuickRejected(); 12528 } 12529 12530 /** 12531 * The degrees that the view is rotated around the pivot point. 12532 * 12533 * @see #setRotation(float) 12534 * @see #getPivotX() 12535 * @see #getPivotY() 12536 * 12537 * @return The degrees of rotation. 12538 */ 12539 @ViewDebug.ExportedProperty(category = "drawing") 12540 public float getRotation() { 12541 return mRenderNode.getRotation(); 12542 } 12543 12544 /** 12545 * Sets the degrees that the view is rotated around the pivot point. Increasing values 12546 * result in clockwise rotation. 12547 * 12548 * @param rotation The degrees of rotation. 12549 * 12550 * @see #getRotation() 12551 * @see #getPivotX() 12552 * @see #getPivotY() 12553 * @see #setRotationX(float) 12554 * @see #setRotationY(float) 12555 * 12556 * @attr ref android.R.styleable#View_rotation 12557 */ 12558 public void setRotation(float rotation) { 12559 if (rotation != getRotation()) { 12560 // Double-invalidation is necessary to capture view's old and new areas 12561 invalidateViewProperty(true, false); 12562 mRenderNode.setRotation(rotation); 12563 invalidateViewProperty(false, true); 12564 12565 invalidateParentIfNeededAndWasQuickRejected(); 12566 notifySubtreeAccessibilityStateChangedIfNeeded(); 12567 } 12568 } 12569 12570 /** 12571 * The degrees that the view is rotated around the vertical axis through the pivot point. 12572 * 12573 * @see #getPivotX() 12574 * @see #getPivotY() 12575 * @see #setRotationY(float) 12576 * 12577 * @return The degrees of Y rotation. 12578 */ 12579 @ViewDebug.ExportedProperty(category = "drawing") 12580 public float getRotationY() { 12581 return mRenderNode.getRotationY(); 12582 } 12583 12584 /** 12585 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 12586 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 12587 * down the y axis. 12588 * 12589 * When rotating large views, it is recommended to adjust the camera distance 12590 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12591 * 12592 * @param rotationY The degrees of Y rotation. 12593 * 12594 * @see #getRotationY() 12595 * @see #getPivotX() 12596 * @see #getPivotY() 12597 * @see #setRotation(float) 12598 * @see #setRotationX(float) 12599 * @see #setCameraDistance(float) 12600 * 12601 * @attr ref android.R.styleable#View_rotationY 12602 */ 12603 public void setRotationY(float rotationY) { 12604 if (rotationY != getRotationY()) { 12605 invalidateViewProperty(true, false); 12606 mRenderNode.setRotationY(rotationY); 12607 invalidateViewProperty(false, true); 12608 12609 invalidateParentIfNeededAndWasQuickRejected(); 12610 notifySubtreeAccessibilityStateChangedIfNeeded(); 12611 } 12612 } 12613 12614 /** 12615 * The degrees that the view is rotated around the horizontal axis through the pivot point. 12616 * 12617 * @see #getPivotX() 12618 * @see #getPivotY() 12619 * @see #setRotationX(float) 12620 * 12621 * @return The degrees of X rotation. 12622 */ 12623 @ViewDebug.ExportedProperty(category = "drawing") 12624 public float getRotationX() { 12625 return mRenderNode.getRotationX(); 12626 } 12627 12628 /** 12629 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 12630 * Increasing values result in clockwise rotation from the viewpoint of looking down the 12631 * x axis. 12632 * 12633 * When rotating large views, it is recommended to adjust the camera distance 12634 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12635 * 12636 * @param rotationX The degrees of X rotation. 12637 * 12638 * @see #getRotationX() 12639 * @see #getPivotX() 12640 * @see #getPivotY() 12641 * @see #setRotation(float) 12642 * @see #setRotationY(float) 12643 * @see #setCameraDistance(float) 12644 * 12645 * @attr ref android.R.styleable#View_rotationX 12646 */ 12647 public void setRotationX(float rotationX) { 12648 if (rotationX != getRotationX()) { 12649 invalidateViewProperty(true, false); 12650 mRenderNode.setRotationX(rotationX); 12651 invalidateViewProperty(false, true); 12652 12653 invalidateParentIfNeededAndWasQuickRejected(); 12654 notifySubtreeAccessibilityStateChangedIfNeeded(); 12655 } 12656 } 12657 12658 /** 12659 * The amount that the view is scaled in x around the pivot point, as a proportion of 12660 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12661 * 12662 * <p>By default, this is 1.0f. 12663 * 12664 * @see #getPivotX() 12665 * @see #getPivotY() 12666 * @return The scaling factor. 12667 */ 12668 @ViewDebug.ExportedProperty(category = "drawing") 12669 public float getScaleX() { 12670 return mRenderNode.getScaleX(); 12671 } 12672 12673 /** 12674 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12675 * the view's unscaled width. A value of 1 means that no scaling is applied. 12676 * 12677 * @param scaleX The scaling factor. 12678 * @see #getPivotX() 12679 * @see #getPivotY() 12680 * 12681 * @attr ref android.R.styleable#View_scaleX 12682 */ 12683 public void setScaleX(float scaleX) { 12684 if (scaleX != getScaleX()) { 12685 invalidateViewProperty(true, false); 12686 mRenderNode.setScaleX(scaleX); 12687 invalidateViewProperty(false, true); 12688 12689 invalidateParentIfNeededAndWasQuickRejected(); 12690 notifySubtreeAccessibilityStateChangedIfNeeded(); 12691 } 12692 } 12693 12694 /** 12695 * The amount that the view is scaled in y around the pivot point, as a proportion of 12696 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12697 * 12698 * <p>By default, this is 1.0f. 12699 * 12700 * @see #getPivotX() 12701 * @see #getPivotY() 12702 * @return The scaling factor. 12703 */ 12704 @ViewDebug.ExportedProperty(category = "drawing") 12705 public float getScaleY() { 12706 return mRenderNode.getScaleY(); 12707 } 12708 12709 /** 12710 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12711 * the view's unscaled width. A value of 1 means that no scaling is applied. 12712 * 12713 * @param scaleY The scaling factor. 12714 * @see #getPivotX() 12715 * @see #getPivotY() 12716 * 12717 * @attr ref android.R.styleable#View_scaleY 12718 */ 12719 public void setScaleY(float scaleY) { 12720 if (scaleY != getScaleY()) { 12721 invalidateViewProperty(true, false); 12722 mRenderNode.setScaleY(scaleY); 12723 invalidateViewProperty(false, true); 12724 12725 invalidateParentIfNeededAndWasQuickRejected(); 12726 notifySubtreeAccessibilityStateChangedIfNeeded(); 12727 } 12728 } 12729 12730 /** 12731 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12732 * and {@link #setScaleX(float) scaled}. 12733 * 12734 * @see #getRotation() 12735 * @see #getScaleX() 12736 * @see #getScaleY() 12737 * @see #getPivotY() 12738 * @return The x location of the pivot point. 12739 * 12740 * @attr ref android.R.styleable#View_transformPivotX 12741 */ 12742 @ViewDebug.ExportedProperty(category = "drawing") 12743 public float getPivotX() { 12744 return mRenderNode.getPivotX(); 12745 } 12746 12747 /** 12748 * Sets the x location of the point around which the view is 12749 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12750 * By default, the pivot point is centered on the object. 12751 * Setting this property disables this behavior and causes the view to use only the 12752 * explicitly set pivotX and pivotY values. 12753 * 12754 * @param pivotX The x location of the pivot point. 12755 * @see #getRotation() 12756 * @see #getScaleX() 12757 * @see #getScaleY() 12758 * @see #getPivotY() 12759 * 12760 * @attr ref android.R.styleable#View_transformPivotX 12761 */ 12762 public void setPivotX(float pivotX) { 12763 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12764 invalidateViewProperty(true, false); 12765 mRenderNode.setPivotX(pivotX); 12766 invalidateViewProperty(false, true); 12767 12768 invalidateParentIfNeededAndWasQuickRejected(); 12769 } 12770 } 12771 12772 /** 12773 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12774 * and {@link #setScaleY(float) scaled}. 12775 * 12776 * @see #getRotation() 12777 * @see #getScaleX() 12778 * @see #getScaleY() 12779 * @see #getPivotY() 12780 * @return The y location of the pivot point. 12781 * 12782 * @attr ref android.R.styleable#View_transformPivotY 12783 */ 12784 @ViewDebug.ExportedProperty(category = "drawing") 12785 public float getPivotY() { 12786 return mRenderNode.getPivotY(); 12787 } 12788 12789 /** 12790 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12791 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12792 * Setting this property disables this behavior and causes the view to use only the 12793 * explicitly set pivotX and pivotY values. 12794 * 12795 * @param pivotY The y location of the pivot point. 12796 * @see #getRotation() 12797 * @see #getScaleX() 12798 * @see #getScaleY() 12799 * @see #getPivotY() 12800 * 12801 * @attr ref android.R.styleable#View_transformPivotY 12802 */ 12803 public void setPivotY(float pivotY) { 12804 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12805 invalidateViewProperty(true, false); 12806 mRenderNode.setPivotY(pivotY); 12807 invalidateViewProperty(false, true); 12808 12809 invalidateParentIfNeededAndWasQuickRejected(); 12810 } 12811 } 12812 12813 /** 12814 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12815 * completely transparent and 1 means the view is completely opaque. 12816 * 12817 * <p>By default this is 1.0f. 12818 * @return The opacity of the view. 12819 */ 12820 @ViewDebug.ExportedProperty(category = "drawing") 12821 public float getAlpha() { 12822 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12823 } 12824 12825 /** 12826 * Sets the behavior for overlapping rendering for this view (see {@link 12827 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12828 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12829 * providing the value which is then used internally. That is, when {@link 12830 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12831 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12832 * instead. 12833 * 12834 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12835 * instead of that returned by {@link #hasOverlappingRendering()}. 12836 * 12837 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12838 */ 12839 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12840 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12841 if (hasOverlappingRendering) { 12842 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12843 } else { 12844 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12845 } 12846 } 12847 12848 /** 12849 * Returns the value for overlapping rendering that is used internally. This is either 12850 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12851 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12852 * 12853 * @return The value for overlapping rendering being used internally. 12854 */ 12855 public final boolean getHasOverlappingRendering() { 12856 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12857 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12858 hasOverlappingRendering(); 12859 } 12860 12861 /** 12862 * Returns whether this View has content which overlaps. 12863 * 12864 * <p>This function, intended to be overridden by specific View types, is an optimization when 12865 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12866 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12867 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12868 * directly. An example of overlapping rendering is a TextView with a background image, such as 12869 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12870 * ImageView with only the foreground image. The default implementation returns true; subclasses 12871 * should override if they have cases which can be optimized.</p> 12872 * 12873 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12874 * necessitates that a View return true if it uses the methods internally without passing the 12875 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12876 * 12877 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12878 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12879 * 12880 * @return true if the content in this view might overlap, false otherwise. 12881 */ 12882 @ViewDebug.ExportedProperty(category = "drawing") 12883 public boolean hasOverlappingRendering() { 12884 return true; 12885 } 12886 12887 /** 12888 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12889 * completely transparent and 1 means the view is completely opaque. 12890 * 12891 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12892 * can have significant performance implications, especially for large views. It is best to use 12893 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12894 * 12895 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12896 * strongly recommended for performance reasons to either override 12897 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12898 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12899 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12900 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12901 * of rendering cost, even for simple or small views. Starting with 12902 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12903 * applied to the view at the rendering level.</p> 12904 * 12905 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12906 * responsible for applying the opacity itself.</p> 12907 * 12908 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12909 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12910 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12911 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12912 * 12913 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12914 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12915 * {@link #hasOverlappingRendering}.</p> 12916 * 12917 * @param alpha The opacity of the view. 12918 * 12919 * @see #hasOverlappingRendering() 12920 * @see #setLayerType(int, android.graphics.Paint) 12921 * 12922 * @attr ref android.R.styleable#View_alpha 12923 */ 12924 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12925 ensureTransformationInfo(); 12926 if (mTransformationInfo.mAlpha != alpha) { 12927 // Report visibility changes, which can affect children, to accessibility 12928 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 12929 notifySubtreeAccessibilityStateChangedIfNeeded(); 12930 } 12931 mTransformationInfo.mAlpha = alpha; 12932 if (onSetAlpha((int) (alpha * 255))) { 12933 mPrivateFlags |= PFLAG_ALPHA_SET; 12934 // subclass is handling alpha - don't optimize rendering cache invalidation 12935 invalidateParentCaches(); 12936 invalidate(true); 12937 } else { 12938 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12939 invalidateViewProperty(true, false); 12940 mRenderNode.setAlpha(getFinalAlpha()); 12941 } 12942 } 12943 } 12944 12945 /** 12946 * Faster version of setAlpha() which performs the same steps except there are 12947 * no calls to invalidate(). The caller of this function should perform proper invalidation 12948 * on the parent and this object. The return value indicates whether the subclass handles 12949 * alpha (the return value for onSetAlpha()). 12950 * 12951 * @param alpha The new value for the alpha property 12952 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12953 * the new value for the alpha property is different from the old value 12954 */ 12955 boolean setAlphaNoInvalidation(float alpha) { 12956 ensureTransformationInfo(); 12957 if (mTransformationInfo.mAlpha != alpha) { 12958 mTransformationInfo.mAlpha = alpha; 12959 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12960 if (subclassHandlesAlpha) { 12961 mPrivateFlags |= PFLAG_ALPHA_SET; 12962 return true; 12963 } else { 12964 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12965 mRenderNode.setAlpha(getFinalAlpha()); 12966 } 12967 } 12968 return false; 12969 } 12970 12971 /** 12972 * This property is hidden and intended only for use by the Fade transition, which 12973 * animates it to produce a visual translucency that does not side-effect (or get 12974 * affected by) the real alpha property. This value is composited with the other 12975 * alpha value (and the AlphaAnimation value, when that is present) to produce 12976 * a final visual translucency result, which is what is passed into the DisplayList. 12977 * 12978 * @hide 12979 */ 12980 public void setTransitionAlpha(float alpha) { 12981 ensureTransformationInfo(); 12982 if (mTransformationInfo.mTransitionAlpha != alpha) { 12983 mTransformationInfo.mTransitionAlpha = alpha; 12984 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12985 invalidateViewProperty(true, false); 12986 mRenderNode.setAlpha(getFinalAlpha()); 12987 } 12988 } 12989 12990 /** 12991 * Calculates the visual alpha of this view, which is a combination of the actual 12992 * alpha value and the transitionAlpha value (if set). 12993 */ 12994 private float getFinalAlpha() { 12995 if (mTransformationInfo != null) { 12996 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12997 } 12998 return 1; 12999 } 13000 13001 /** 13002 * This property is hidden and intended only for use by the Fade transition, which 13003 * animates it to produce a visual translucency that does not side-effect (or get 13004 * affected by) the real alpha property. This value is composited with the other 13005 * alpha value (and the AlphaAnimation value, when that is present) to produce 13006 * a final visual translucency result, which is what is passed into the DisplayList. 13007 * 13008 * @hide 13009 */ 13010 @ViewDebug.ExportedProperty(category = "drawing") 13011 public float getTransitionAlpha() { 13012 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 13013 } 13014 13015 /** 13016 * Top position of this view relative to its parent. 13017 * 13018 * @return The top of this view, in pixels. 13019 */ 13020 @ViewDebug.CapturedViewProperty 13021 public final int getTop() { 13022 return mTop; 13023 } 13024 13025 /** 13026 * Sets the top position of this view relative to its parent. This method is meant to be called 13027 * by the layout system and should not generally be called otherwise, because the property 13028 * may be changed at any time by the layout. 13029 * 13030 * @param top The top of this view, in pixels. 13031 */ 13032 public final void setTop(int top) { 13033 if (top != mTop) { 13034 final boolean matrixIsIdentity = hasIdentityMatrix(); 13035 if (matrixIsIdentity) { 13036 if (mAttachInfo != null) { 13037 int minTop; 13038 int yLoc; 13039 if (top < mTop) { 13040 minTop = top; 13041 yLoc = top - mTop; 13042 } else { 13043 minTop = mTop; 13044 yLoc = 0; 13045 } 13046 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 13047 } 13048 } else { 13049 // Double-invalidation is necessary to capture view's old and new areas 13050 invalidate(true); 13051 } 13052 13053 int width = mRight - mLeft; 13054 int oldHeight = mBottom - mTop; 13055 13056 mTop = top; 13057 mRenderNode.setTop(mTop); 13058 13059 sizeChange(width, mBottom - mTop, width, oldHeight); 13060 13061 if (!matrixIsIdentity) { 13062 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13063 invalidate(true); 13064 } 13065 mBackgroundSizeChanged = true; 13066 if (mForegroundInfo != null) { 13067 mForegroundInfo.mBoundsChanged = true; 13068 } 13069 invalidateParentIfNeeded(); 13070 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 13071 // View was rejected last time it was drawn by its parent; this may have changed 13072 invalidateParentIfNeeded(); 13073 } 13074 } 13075 } 13076 13077 /** 13078 * Bottom position of this view relative to its parent. 13079 * 13080 * @return The bottom of this view, in pixels. 13081 */ 13082 @ViewDebug.CapturedViewProperty 13083 public final int getBottom() { 13084 return mBottom; 13085 } 13086 13087 /** 13088 * True if this view has changed since the last time being drawn. 13089 * 13090 * @return The dirty state of this view. 13091 */ 13092 public boolean isDirty() { 13093 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 13094 } 13095 13096 /** 13097 * Sets the bottom position of this view relative to its parent. This method is meant to be 13098 * called by the layout system and should not generally be called otherwise, because the 13099 * property may be changed at any time by the layout. 13100 * 13101 * @param bottom The bottom of this view, in pixels. 13102 */ 13103 public final void setBottom(int bottom) { 13104 if (bottom != mBottom) { 13105 final boolean matrixIsIdentity = hasIdentityMatrix(); 13106 if (matrixIsIdentity) { 13107 if (mAttachInfo != null) { 13108 int maxBottom; 13109 if (bottom < mBottom) { 13110 maxBottom = mBottom; 13111 } else { 13112 maxBottom = bottom; 13113 } 13114 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 13115 } 13116 } else { 13117 // Double-invalidation is necessary to capture view's old and new areas 13118 invalidate(true); 13119 } 13120 13121 int width = mRight - mLeft; 13122 int oldHeight = mBottom - mTop; 13123 13124 mBottom = bottom; 13125 mRenderNode.setBottom(mBottom); 13126 13127 sizeChange(width, mBottom - mTop, width, oldHeight); 13128 13129 if (!matrixIsIdentity) { 13130 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13131 invalidate(true); 13132 } 13133 mBackgroundSizeChanged = true; 13134 if (mForegroundInfo != null) { 13135 mForegroundInfo.mBoundsChanged = true; 13136 } 13137 invalidateParentIfNeeded(); 13138 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 13139 // View was rejected last time it was drawn by its parent; this may have changed 13140 invalidateParentIfNeeded(); 13141 } 13142 } 13143 } 13144 13145 /** 13146 * Left position of this view relative to its parent. 13147 * 13148 * @return The left edge of this view, in pixels. 13149 */ 13150 @ViewDebug.CapturedViewProperty 13151 public final int getLeft() { 13152 return mLeft; 13153 } 13154 13155 /** 13156 * Sets the left position of this view relative to its parent. This method is meant to be called 13157 * by the layout system and should not generally be called otherwise, because the property 13158 * may be changed at any time by the layout. 13159 * 13160 * @param left The left of this view, in pixels. 13161 */ 13162 public final void setLeft(int left) { 13163 if (left != mLeft) { 13164 final boolean matrixIsIdentity = hasIdentityMatrix(); 13165 if (matrixIsIdentity) { 13166 if (mAttachInfo != null) { 13167 int minLeft; 13168 int xLoc; 13169 if (left < mLeft) { 13170 minLeft = left; 13171 xLoc = left - mLeft; 13172 } else { 13173 minLeft = mLeft; 13174 xLoc = 0; 13175 } 13176 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 13177 } 13178 } else { 13179 // Double-invalidation is necessary to capture view's old and new areas 13180 invalidate(true); 13181 } 13182 13183 int oldWidth = mRight - mLeft; 13184 int height = mBottom - mTop; 13185 13186 mLeft = left; 13187 mRenderNode.setLeft(left); 13188 13189 sizeChange(mRight - mLeft, height, oldWidth, height); 13190 13191 if (!matrixIsIdentity) { 13192 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13193 invalidate(true); 13194 } 13195 mBackgroundSizeChanged = true; 13196 if (mForegroundInfo != null) { 13197 mForegroundInfo.mBoundsChanged = true; 13198 } 13199 invalidateParentIfNeeded(); 13200 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 13201 // View was rejected last time it was drawn by its parent; this may have changed 13202 invalidateParentIfNeeded(); 13203 } 13204 } 13205 } 13206 13207 /** 13208 * Right position of this view relative to its parent. 13209 * 13210 * @return The right edge of this view, in pixels. 13211 */ 13212 @ViewDebug.CapturedViewProperty 13213 public final int getRight() { 13214 return mRight; 13215 } 13216 13217 /** 13218 * Sets the right position of this view relative to its parent. This method is meant to be called 13219 * by the layout system and should not generally be called otherwise, because the property 13220 * may be changed at any time by the layout. 13221 * 13222 * @param right The right of this view, in pixels. 13223 */ 13224 public final void setRight(int right) { 13225 if (right != mRight) { 13226 final boolean matrixIsIdentity = hasIdentityMatrix(); 13227 if (matrixIsIdentity) { 13228 if (mAttachInfo != null) { 13229 int maxRight; 13230 if (right < mRight) { 13231 maxRight = mRight; 13232 } else { 13233 maxRight = right; 13234 } 13235 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 13236 } 13237 } else { 13238 // Double-invalidation is necessary to capture view's old and new areas 13239 invalidate(true); 13240 } 13241 13242 int oldWidth = mRight - mLeft; 13243 int height = mBottom - mTop; 13244 13245 mRight = right; 13246 mRenderNode.setRight(mRight); 13247 13248 sizeChange(mRight - mLeft, height, oldWidth, height); 13249 13250 if (!matrixIsIdentity) { 13251 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13252 invalidate(true); 13253 } 13254 mBackgroundSizeChanged = true; 13255 if (mForegroundInfo != null) { 13256 mForegroundInfo.mBoundsChanged = true; 13257 } 13258 invalidateParentIfNeeded(); 13259 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 13260 // View was rejected last time it was drawn by its parent; this may have changed 13261 invalidateParentIfNeeded(); 13262 } 13263 } 13264 } 13265 13266 /** 13267 * The visual x position of this view, in pixels. This is equivalent to the 13268 * {@link #setTranslationX(float) translationX} property plus the current 13269 * {@link #getLeft() left} property. 13270 * 13271 * @return The visual x position of this view, in pixels. 13272 */ 13273 @ViewDebug.ExportedProperty(category = "drawing") 13274 public float getX() { 13275 return mLeft + getTranslationX(); 13276 } 13277 13278 /** 13279 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 13280 * {@link #setTranslationX(float) translationX} property to be the difference between 13281 * the x value passed in and the current {@link #getLeft() left} property. 13282 * 13283 * @param x The visual x position of this view, in pixels. 13284 */ 13285 public void setX(float x) { 13286 setTranslationX(x - mLeft); 13287 } 13288 13289 /** 13290 * The visual y position of this view, in pixels. This is equivalent to the 13291 * {@link #setTranslationY(float) translationY} property plus the current 13292 * {@link #getTop() top} property. 13293 * 13294 * @return The visual y position of this view, in pixels. 13295 */ 13296 @ViewDebug.ExportedProperty(category = "drawing") 13297 public float getY() { 13298 return mTop + getTranslationY(); 13299 } 13300 13301 /** 13302 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 13303 * {@link #setTranslationY(float) translationY} property to be the difference between 13304 * the y value passed in and the current {@link #getTop() top} property. 13305 * 13306 * @param y The visual y position of this view, in pixels. 13307 */ 13308 public void setY(float y) { 13309 setTranslationY(y - mTop); 13310 } 13311 13312 /** 13313 * The visual z position of this view, in pixels. This is equivalent to the 13314 * {@link #setTranslationZ(float) translationZ} property plus the current 13315 * {@link #getElevation() elevation} property. 13316 * 13317 * @return The visual z position of this view, in pixels. 13318 */ 13319 @ViewDebug.ExportedProperty(category = "drawing") 13320 public float getZ() { 13321 return getElevation() + getTranslationZ(); 13322 } 13323 13324 /** 13325 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 13326 * {@link #setTranslationZ(float) translationZ} property to be the difference between 13327 * the x value passed in and the current {@link #getElevation() elevation} property. 13328 * 13329 * @param z The visual z position of this view, in pixels. 13330 */ 13331 public void setZ(float z) { 13332 setTranslationZ(z - getElevation()); 13333 } 13334 13335 /** 13336 * The base elevation of this view relative to its parent, in pixels. 13337 * 13338 * @return The base depth position of the view, in pixels. 13339 */ 13340 @ViewDebug.ExportedProperty(category = "drawing") 13341 public float getElevation() { 13342 return mRenderNode.getElevation(); 13343 } 13344 13345 /** 13346 * Sets the base elevation of this view, in pixels. 13347 * 13348 * @attr ref android.R.styleable#View_elevation 13349 */ 13350 public void setElevation(float elevation) { 13351 if (elevation != getElevation()) { 13352 invalidateViewProperty(true, false); 13353 mRenderNode.setElevation(elevation); 13354 invalidateViewProperty(false, true); 13355 13356 invalidateParentIfNeededAndWasQuickRejected(); 13357 } 13358 } 13359 13360 /** 13361 * The horizontal location of this view relative to its {@link #getLeft() left} position. 13362 * This position is post-layout, in addition to wherever the object's 13363 * layout placed it. 13364 * 13365 * @return The horizontal position of this view relative to its left position, in pixels. 13366 */ 13367 @ViewDebug.ExportedProperty(category = "drawing") 13368 public float getTranslationX() { 13369 return mRenderNode.getTranslationX(); 13370 } 13371 13372 /** 13373 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 13374 * This effectively positions the object post-layout, in addition to wherever the object's 13375 * layout placed it. 13376 * 13377 * @param translationX The horizontal position of this view relative to its left position, 13378 * in pixels. 13379 * 13380 * @attr ref android.R.styleable#View_translationX 13381 */ 13382 public void setTranslationX(float translationX) { 13383 if (translationX != getTranslationX()) { 13384 invalidateViewProperty(true, false); 13385 mRenderNode.setTranslationX(translationX); 13386 invalidateViewProperty(false, true); 13387 13388 invalidateParentIfNeededAndWasQuickRejected(); 13389 notifySubtreeAccessibilityStateChangedIfNeeded(); 13390 } 13391 } 13392 13393 /** 13394 * The vertical location of this view relative to its {@link #getTop() top} position. 13395 * This position is post-layout, in addition to wherever the object's 13396 * layout placed it. 13397 * 13398 * @return The vertical position of this view relative to its top position, 13399 * in pixels. 13400 */ 13401 @ViewDebug.ExportedProperty(category = "drawing") 13402 public float getTranslationY() { 13403 return mRenderNode.getTranslationY(); 13404 } 13405 13406 /** 13407 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 13408 * This effectively positions the object post-layout, in addition to wherever the object's 13409 * layout placed it. 13410 * 13411 * @param translationY The vertical position of this view relative to its top position, 13412 * in pixels. 13413 * 13414 * @attr ref android.R.styleable#View_translationY 13415 */ 13416 public void setTranslationY(float translationY) { 13417 if (translationY != getTranslationY()) { 13418 invalidateViewProperty(true, false); 13419 mRenderNode.setTranslationY(translationY); 13420 invalidateViewProperty(false, true); 13421 13422 invalidateParentIfNeededAndWasQuickRejected(); 13423 notifySubtreeAccessibilityStateChangedIfNeeded(); 13424 } 13425 } 13426 13427 /** 13428 * The depth location of this view relative to its {@link #getElevation() elevation}. 13429 * 13430 * @return The depth of this view relative to its elevation. 13431 */ 13432 @ViewDebug.ExportedProperty(category = "drawing") 13433 public float getTranslationZ() { 13434 return mRenderNode.getTranslationZ(); 13435 } 13436 13437 /** 13438 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 13439 * 13440 * @attr ref android.R.styleable#View_translationZ 13441 */ 13442 public void setTranslationZ(float translationZ) { 13443 if (translationZ != getTranslationZ()) { 13444 invalidateViewProperty(true, false); 13445 mRenderNode.setTranslationZ(translationZ); 13446 invalidateViewProperty(false, true); 13447 13448 invalidateParentIfNeededAndWasQuickRejected(); 13449 } 13450 } 13451 13452 /** @hide */ 13453 public void setAnimationMatrix(Matrix matrix) { 13454 invalidateViewProperty(true, false); 13455 mRenderNode.setAnimationMatrix(matrix); 13456 invalidateViewProperty(false, true); 13457 13458 invalidateParentIfNeededAndWasQuickRejected(); 13459 } 13460 13461 /** 13462 * Returns the current StateListAnimator if exists. 13463 * 13464 * @return StateListAnimator or null if it does not exists 13465 * @see #setStateListAnimator(android.animation.StateListAnimator) 13466 */ 13467 public StateListAnimator getStateListAnimator() { 13468 return mStateListAnimator; 13469 } 13470 13471 /** 13472 * Attaches the provided StateListAnimator to this View. 13473 * <p> 13474 * Any previously attached StateListAnimator will be detached. 13475 * 13476 * @param stateListAnimator The StateListAnimator to update the view 13477 * @see {@link android.animation.StateListAnimator} 13478 */ 13479 public void setStateListAnimator(StateListAnimator stateListAnimator) { 13480 if (mStateListAnimator == stateListAnimator) { 13481 return; 13482 } 13483 if (mStateListAnimator != null) { 13484 mStateListAnimator.setTarget(null); 13485 } 13486 mStateListAnimator = stateListAnimator; 13487 if (stateListAnimator != null) { 13488 stateListAnimator.setTarget(this); 13489 if (isAttachedToWindow()) { 13490 stateListAnimator.setState(getDrawableState()); 13491 } 13492 } 13493 } 13494 13495 /** 13496 * Returns whether the Outline should be used to clip the contents of the View. 13497 * <p> 13498 * Note that this flag will only be respected if the View's Outline returns true from 13499 * {@link Outline#canClip()}. 13500 * 13501 * @see #setOutlineProvider(ViewOutlineProvider) 13502 * @see #setClipToOutline(boolean) 13503 */ 13504 public final boolean getClipToOutline() { 13505 return mRenderNode.getClipToOutline(); 13506 } 13507 13508 /** 13509 * Sets whether the View's Outline should be used to clip the contents of the View. 13510 * <p> 13511 * Only a single non-rectangular clip can be applied on a View at any time. 13512 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 13513 * circular reveal} animation take priority over Outline clipping, and 13514 * child Outline clipping takes priority over Outline clipping done by a 13515 * parent. 13516 * <p> 13517 * Note that this flag will only be respected if the View's Outline returns true from 13518 * {@link Outline#canClip()}. 13519 * 13520 * @see #setOutlineProvider(ViewOutlineProvider) 13521 * @see #getClipToOutline() 13522 */ 13523 public void setClipToOutline(boolean clipToOutline) { 13524 damageInParent(); 13525 if (getClipToOutline() != clipToOutline) { 13526 mRenderNode.setClipToOutline(clipToOutline); 13527 } 13528 } 13529 13530 // correspond to the enum values of View_outlineProvider 13531 private static final int PROVIDER_BACKGROUND = 0; 13532 private static final int PROVIDER_NONE = 1; 13533 private static final int PROVIDER_BOUNDS = 2; 13534 private static final int PROVIDER_PADDED_BOUNDS = 3; 13535 private void setOutlineProviderFromAttribute(int providerInt) { 13536 switch (providerInt) { 13537 case PROVIDER_BACKGROUND: 13538 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 13539 break; 13540 case PROVIDER_NONE: 13541 setOutlineProvider(null); 13542 break; 13543 case PROVIDER_BOUNDS: 13544 setOutlineProvider(ViewOutlineProvider.BOUNDS); 13545 break; 13546 case PROVIDER_PADDED_BOUNDS: 13547 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 13548 break; 13549 } 13550 } 13551 13552 /** 13553 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 13554 * the shape of the shadow it casts, and enables outline clipping. 13555 * <p> 13556 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 13557 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 13558 * outline provider with this method allows this behavior to be overridden. 13559 * <p> 13560 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 13561 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 13562 * <p> 13563 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 13564 * 13565 * @see #setClipToOutline(boolean) 13566 * @see #getClipToOutline() 13567 * @see #getOutlineProvider() 13568 */ 13569 public void setOutlineProvider(ViewOutlineProvider provider) { 13570 mOutlineProvider = provider; 13571 invalidateOutline(); 13572 } 13573 13574 /** 13575 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 13576 * that defines the shape of the shadow it casts, and enables outline clipping. 13577 * 13578 * @see #setOutlineProvider(ViewOutlineProvider) 13579 */ 13580 public ViewOutlineProvider getOutlineProvider() { 13581 return mOutlineProvider; 13582 } 13583 13584 /** 13585 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 13586 * 13587 * @see #setOutlineProvider(ViewOutlineProvider) 13588 */ 13589 public void invalidateOutline() { 13590 rebuildOutline(); 13591 13592 notifySubtreeAccessibilityStateChangedIfNeeded(); 13593 invalidateViewProperty(false, false); 13594 } 13595 13596 /** 13597 * Internal version of {@link #invalidateOutline()} which invalidates the 13598 * outline without invalidating the view itself. This is intended to be called from 13599 * within methods in the View class itself which are the result of the view being 13600 * invalidated already. For example, when we are drawing the background of a View, 13601 * we invalidate the outline in case it changed in the meantime, but we do not 13602 * need to invalidate the view because we're already drawing the background as part 13603 * of drawing the view in response to an earlier invalidation of the view. 13604 */ 13605 private void rebuildOutline() { 13606 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 13607 if (mAttachInfo == null) return; 13608 13609 if (mOutlineProvider == null) { 13610 // no provider, remove outline 13611 mRenderNode.setOutline(null); 13612 } else { 13613 final Outline outline = mAttachInfo.mTmpOutline; 13614 outline.setEmpty(); 13615 outline.setAlpha(1.0f); 13616 13617 mOutlineProvider.getOutline(this, outline); 13618 mRenderNode.setOutline(outline); 13619 } 13620 } 13621 13622 /** 13623 * HierarchyViewer only 13624 * 13625 * @hide 13626 */ 13627 @ViewDebug.ExportedProperty(category = "drawing") 13628 public boolean hasShadow() { 13629 return mRenderNode.hasShadow(); 13630 } 13631 13632 13633 /** @hide */ 13634 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13635 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13636 invalidateViewProperty(false, false); 13637 } 13638 13639 /** 13640 * Hit rectangle in parent's coordinates 13641 * 13642 * @param outRect The hit rectangle of the view. 13643 */ 13644 public void getHitRect(Rect outRect) { 13645 if (hasIdentityMatrix() || mAttachInfo == null) { 13646 outRect.set(mLeft, mTop, mRight, mBottom); 13647 } else { 13648 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13649 tmpRect.set(0, 0, getWidth(), getHeight()); 13650 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13651 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13652 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13653 } 13654 } 13655 13656 /** 13657 * Determines whether the given point, in local coordinates is inside the view. 13658 */ 13659 /*package*/ final boolean pointInView(float localX, float localY) { 13660 return pointInView(localX, localY, 0); 13661 } 13662 13663 /** 13664 * Utility method to determine whether the given point, in local coordinates, 13665 * is inside the view, where the area of the view is expanded by the slop factor. 13666 * This method is called while processing touch-move events to determine if the event 13667 * is still within the view. 13668 * 13669 * @hide 13670 */ 13671 public boolean pointInView(float localX, float localY, float slop) { 13672 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13673 localY < ((mBottom - mTop) + slop); 13674 } 13675 13676 /** 13677 * When a view has focus and the user navigates away from it, the next view is searched for 13678 * starting from the rectangle filled in by this method. 13679 * 13680 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13681 * of the view. However, if your view maintains some idea of internal selection, 13682 * such as a cursor, or a selected row or column, you should override this method and 13683 * fill in a more specific rectangle. 13684 * 13685 * @param r The rectangle to fill in, in this view's coordinates. 13686 */ 13687 public void getFocusedRect(Rect r) { 13688 getDrawingRect(r); 13689 } 13690 13691 /** 13692 * If some part of this view is not clipped by any of its parents, then 13693 * return that area in r in global (root) coordinates. To convert r to local 13694 * coordinates (without taking possible View rotations into account), offset 13695 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13696 * If the view is completely clipped or translated out, return false. 13697 * 13698 * @param r If true is returned, r holds the global coordinates of the 13699 * visible portion of this view. 13700 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13701 * between this view and its root. globalOffet may be null. 13702 * @return true if r is non-empty (i.e. part of the view is visible at the 13703 * root level. 13704 */ 13705 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13706 int width = mRight - mLeft; 13707 int height = mBottom - mTop; 13708 if (width > 0 && height > 0) { 13709 r.set(0, 0, width, height); 13710 if (globalOffset != null) { 13711 globalOffset.set(-mScrollX, -mScrollY); 13712 } 13713 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13714 } 13715 return false; 13716 } 13717 13718 public final boolean getGlobalVisibleRect(Rect r) { 13719 return getGlobalVisibleRect(r, null); 13720 } 13721 13722 public final boolean getLocalVisibleRect(Rect r) { 13723 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13724 if (getGlobalVisibleRect(r, offset)) { 13725 r.offset(-offset.x, -offset.y); // make r local 13726 return true; 13727 } 13728 return false; 13729 } 13730 13731 /** 13732 * Offset this view's vertical location by the specified number of pixels. 13733 * 13734 * @param offset the number of pixels to offset the view by 13735 */ 13736 public void offsetTopAndBottom(int offset) { 13737 if (offset != 0) { 13738 final boolean matrixIsIdentity = hasIdentityMatrix(); 13739 if (matrixIsIdentity) { 13740 if (isHardwareAccelerated()) { 13741 invalidateViewProperty(false, false); 13742 } else { 13743 final ViewParent p = mParent; 13744 if (p != null && mAttachInfo != null) { 13745 final Rect r = mAttachInfo.mTmpInvalRect; 13746 int minTop; 13747 int maxBottom; 13748 int yLoc; 13749 if (offset < 0) { 13750 minTop = mTop + offset; 13751 maxBottom = mBottom; 13752 yLoc = offset; 13753 } else { 13754 minTop = mTop; 13755 maxBottom = mBottom + offset; 13756 yLoc = 0; 13757 } 13758 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13759 p.invalidateChild(this, r); 13760 } 13761 } 13762 } else { 13763 invalidateViewProperty(false, false); 13764 } 13765 13766 mTop += offset; 13767 mBottom += offset; 13768 mRenderNode.offsetTopAndBottom(offset); 13769 if (isHardwareAccelerated()) { 13770 invalidateViewProperty(false, false); 13771 invalidateParentIfNeededAndWasQuickRejected(); 13772 } else { 13773 if (!matrixIsIdentity) { 13774 invalidateViewProperty(false, true); 13775 } 13776 invalidateParentIfNeeded(); 13777 } 13778 notifySubtreeAccessibilityStateChangedIfNeeded(); 13779 } 13780 } 13781 13782 /** 13783 * Offset this view's horizontal location by the specified amount of pixels. 13784 * 13785 * @param offset the number of pixels to offset the view by 13786 */ 13787 public void offsetLeftAndRight(int offset) { 13788 if (offset != 0) { 13789 final boolean matrixIsIdentity = hasIdentityMatrix(); 13790 if (matrixIsIdentity) { 13791 if (isHardwareAccelerated()) { 13792 invalidateViewProperty(false, false); 13793 } else { 13794 final ViewParent p = mParent; 13795 if (p != null && mAttachInfo != null) { 13796 final Rect r = mAttachInfo.mTmpInvalRect; 13797 int minLeft; 13798 int maxRight; 13799 if (offset < 0) { 13800 minLeft = mLeft + offset; 13801 maxRight = mRight; 13802 } else { 13803 minLeft = mLeft; 13804 maxRight = mRight + offset; 13805 } 13806 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13807 p.invalidateChild(this, r); 13808 } 13809 } 13810 } else { 13811 invalidateViewProperty(false, false); 13812 } 13813 13814 mLeft += offset; 13815 mRight += offset; 13816 mRenderNode.offsetLeftAndRight(offset); 13817 if (isHardwareAccelerated()) { 13818 invalidateViewProperty(false, false); 13819 invalidateParentIfNeededAndWasQuickRejected(); 13820 } else { 13821 if (!matrixIsIdentity) { 13822 invalidateViewProperty(false, true); 13823 } 13824 invalidateParentIfNeeded(); 13825 } 13826 notifySubtreeAccessibilityStateChangedIfNeeded(); 13827 } 13828 } 13829 13830 /** 13831 * Get the LayoutParams associated with this view. All views should have 13832 * layout parameters. These supply parameters to the <i>parent</i> of this 13833 * view specifying how it should be arranged. There are many subclasses of 13834 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13835 * of ViewGroup that are responsible for arranging their children. 13836 * 13837 * This method may return null if this View is not attached to a parent 13838 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13839 * was not invoked successfully. When a View is attached to a parent 13840 * ViewGroup, this method must not return null. 13841 * 13842 * @return The LayoutParams associated with this view, or null if no 13843 * parameters have been set yet 13844 */ 13845 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13846 public ViewGroup.LayoutParams getLayoutParams() { 13847 return mLayoutParams; 13848 } 13849 13850 /** 13851 * Set the layout parameters associated with this view. These supply 13852 * parameters to the <i>parent</i> of this view specifying how it should be 13853 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13854 * correspond to the different subclasses of ViewGroup that are responsible 13855 * for arranging their children. 13856 * 13857 * @param params The layout parameters for this view, cannot be null 13858 */ 13859 public void setLayoutParams(ViewGroup.LayoutParams params) { 13860 if (params == null) { 13861 throw new NullPointerException("Layout parameters cannot be null"); 13862 } 13863 mLayoutParams = params; 13864 resolveLayoutParams(); 13865 if (mParent instanceof ViewGroup) { 13866 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13867 } 13868 requestLayout(); 13869 } 13870 13871 /** 13872 * Resolve the layout parameters depending on the resolved layout direction 13873 * 13874 * @hide 13875 */ 13876 public void resolveLayoutParams() { 13877 if (mLayoutParams != null) { 13878 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13879 } 13880 } 13881 13882 /** 13883 * Set the scrolled position of your view. This will cause a call to 13884 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13885 * invalidated. 13886 * @param x the x position to scroll to 13887 * @param y the y position to scroll to 13888 */ 13889 public void scrollTo(int x, int y) { 13890 if (mScrollX != x || mScrollY != y) { 13891 int oldX = mScrollX; 13892 int oldY = mScrollY; 13893 mScrollX = x; 13894 mScrollY = y; 13895 invalidateParentCaches(); 13896 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13897 if (!awakenScrollBars()) { 13898 postInvalidateOnAnimation(); 13899 } 13900 } 13901 } 13902 13903 /** 13904 * Move the scrolled position of your view. This will cause a call to 13905 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13906 * invalidated. 13907 * @param x the amount of pixels to scroll by horizontally 13908 * @param y the amount of pixels to scroll by vertically 13909 */ 13910 public void scrollBy(int x, int y) { 13911 scrollTo(mScrollX + x, mScrollY + y); 13912 } 13913 13914 /** 13915 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13916 * animation to fade the scrollbars out after a default delay. If a subclass 13917 * provides animated scrolling, the start delay should equal the duration 13918 * of the scrolling animation.</p> 13919 * 13920 * <p>The animation starts only if at least one of the scrollbars is 13921 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13922 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13923 * this method returns true, and false otherwise. If the animation is 13924 * started, this method calls {@link #invalidate()}; in that case the 13925 * caller should not call {@link #invalidate()}.</p> 13926 * 13927 * <p>This method should be invoked every time a subclass directly updates 13928 * the scroll parameters.</p> 13929 * 13930 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13931 * and {@link #scrollTo(int, int)}.</p> 13932 * 13933 * @return true if the animation is played, false otherwise 13934 * 13935 * @see #awakenScrollBars(int) 13936 * @see #scrollBy(int, int) 13937 * @see #scrollTo(int, int) 13938 * @see #isHorizontalScrollBarEnabled() 13939 * @see #isVerticalScrollBarEnabled() 13940 * @see #setHorizontalScrollBarEnabled(boolean) 13941 * @see #setVerticalScrollBarEnabled(boolean) 13942 */ 13943 protected boolean awakenScrollBars() { 13944 return mScrollCache != null && 13945 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13946 } 13947 13948 /** 13949 * Trigger the scrollbars to draw. 13950 * This method differs from awakenScrollBars() only in its default duration. 13951 * initialAwakenScrollBars() will show the scroll bars for longer than 13952 * usual to give the user more of a chance to notice them. 13953 * 13954 * @return true if the animation is played, false otherwise. 13955 */ 13956 private boolean initialAwakenScrollBars() { 13957 return mScrollCache != null && 13958 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13959 } 13960 13961 /** 13962 * <p> 13963 * Trigger the scrollbars to draw. When invoked this method starts an 13964 * animation to fade the scrollbars out after a fixed delay. If a subclass 13965 * provides animated scrolling, the start delay should equal the duration of 13966 * the scrolling animation. 13967 * </p> 13968 * 13969 * <p> 13970 * The animation starts only if at least one of the scrollbars is enabled, 13971 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13972 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13973 * this method returns true, and false otherwise. If the animation is 13974 * started, this method calls {@link #invalidate()}; in that case the caller 13975 * should not call {@link #invalidate()}. 13976 * </p> 13977 * 13978 * <p> 13979 * This method should be invoked every time a subclass directly updates the 13980 * scroll parameters. 13981 * </p> 13982 * 13983 * @param startDelay the delay, in milliseconds, after which the animation 13984 * should start; when the delay is 0, the animation starts 13985 * immediately 13986 * @return true if the animation is played, false otherwise 13987 * 13988 * @see #scrollBy(int, int) 13989 * @see #scrollTo(int, int) 13990 * @see #isHorizontalScrollBarEnabled() 13991 * @see #isVerticalScrollBarEnabled() 13992 * @see #setHorizontalScrollBarEnabled(boolean) 13993 * @see #setVerticalScrollBarEnabled(boolean) 13994 */ 13995 protected boolean awakenScrollBars(int startDelay) { 13996 return awakenScrollBars(startDelay, true); 13997 } 13998 13999 /** 14000 * <p> 14001 * Trigger the scrollbars to draw. When invoked this method starts an 14002 * animation to fade the scrollbars out after a fixed delay. If a subclass 14003 * provides animated scrolling, the start delay should equal the duration of 14004 * the scrolling animation. 14005 * </p> 14006 * 14007 * <p> 14008 * The animation starts only if at least one of the scrollbars is enabled, 14009 * as specified by {@link #isHorizontalScrollBarEnabled()} and 14010 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14011 * this method returns true, and false otherwise. If the animation is 14012 * started, this method calls {@link #invalidate()} if the invalidate parameter 14013 * is set to true; in that case the caller 14014 * should not call {@link #invalidate()}. 14015 * </p> 14016 * 14017 * <p> 14018 * This method should be invoked every time a subclass directly updates the 14019 * scroll parameters. 14020 * </p> 14021 * 14022 * @param startDelay the delay, in milliseconds, after which the animation 14023 * should start; when the delay is 0, the animation starts 14024 * immediately 14025 * 14026 * @param invalidate Whether this method should call invalidate 14027 * 14028 * @return true if the animation is played, false otherwise 14029 * 14030 * @see #scrollBy(int, int) 14031 * @see #scrollTo(int, int) 14032 * @see #isHorizontalScrollBarEnabled() 14033 * @see #isVerticalScrollBarEnabled() 14034 * @see #setHorizontalScrollBarEnabled(boolean) 14035 * @see #setVerticalScrollBarEnabled(boolean) 14036 */ 14037 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 14038 final ScrollabilityCache scrollCache = mScrollCache; 14039 14040 if (scrollCache == null || !scrollCache.fadeScrollBars) { 14041 return false; 14042 } 14043 14044 if (scrollCache.scrollBar == null) { 14045 scrollCache.scrollBar = new ScrollBarDrawable(); 14046 scrollCache.scrollBar.setState(getDrawableState()); 14047 scrollCache.scrollBar.setCallback(this); 14048 } 14049 14050 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 14051 14052 if (invalidate) { 14053 // Invalidate to show the scrollbars 14054 postInvalidateOnAnimation(); 14055 } 14056 14057 if (scrollCache.state == ScrollabilityCache.OFF) { 14058 // FIXME: this is copied from WindowManagerService. 14059 // We should get this value from the system when it 14060 // is possible to do so. 14061 final int KEY_REPEAT_FIRST_DELAY = 750; 14062 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 14063 } 14064 14065 // Tell mScrollCache when we should start fading. This may 14066 // extend the fade start time if one was already scheduled 14067 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 14068 scrollCache.fadeStartTime = fadeStartTime; 14069 scrollCache.state = ScrollabilityCache.ON; 14070 14071 // Schedule our fader to run, unscheduling any old ones first 14072 if (mAttachInfo != null) { 14073 mAttachInfo.mHandler.removeCallbacks(scrollCache); 14074 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 14075 } 14076 14077 return true; 14078 } 14079 14080 return false; 14081 } 14082 14083 /** 14084 * Do not invalidate views which are not visible and which are not running an animation. They 14085 * will not get drawn and they should not set dirty flags as if they will be drawn 14086 */ 14087 private boolean skipInvalidate() { 14088 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 14089 (!(mParent instanceof ViewGroup) || 14090 !((ViewGroup) mParent).isViewTransitioning(this)); 14091 } 14092 14093 /** 14094 * Mark the area defined by dirty as needing to be drawn. If the view is 14095 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 14096 * point in the future. 14097 * <p> 14098 * This must be called from a UI thread. To call from a non-UI thread, call 14099 * {@link #postInvalidate()}. 14100 * <p> 14101 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 14102 * {@code dirty}. 14103 * 14104 * @param dirty the rectangle representing the bounds of the dirty region 14105 */ 14106 public void invalidate(Rect dirty) { 14107 final int scrollX = mScrollX; 14108 final int scrollY = mScrollY; 14109 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 14110 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 14111 } 14112 14113 /** 14114 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 14115 * coordinates of the dirty rect are relative to the view. If the view is 14116 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 14117 * point in the future. 14118 * <p> 14119 * This must be called from a UI thread. To call from a non-UI thread, call 14120 * {@link #postInvalidate()}. 14121 * 14122 * @param l the left position of the dirty region 14123 * @param t the top position of the dirty region 14124 * @param r the right position of the dirty region 14125 * @param b the bottom position of the dirty region 14126 */ 14127 public void invalidate(int l, int t, int r, int b) { 14128 final int scrollX = mScrollX; 14129 final int scrollY = mScrollY; 14130 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 14131 } 14132 14133 /** 14134 * Invalidate the whole view. If the view is visible, 14135 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 14136 * the future. 14137 * <p> 14138 * This must be called from a UI thread. To call from a non-UI thread, call 14139 * {@link #postInvalidate()}. 14140 */ 14141 public void invalidate() { 14142 invalidate(true); 14143 } 14144 14145 /** 14146 * This is where the invalidate() work actually happens. A full invalidate() 14147 * causes the drawing cache to be invalidated, but this function can be 14148 * called with invalidateCache set to false to skip that invalidation step 14149 * for cases that do not need it (for example, a component that remains at 14150 * the same dimensions with the same content). 14151 * 14152 * @param invalidateCache Whether the drawing cache for this view should be 14153 * invalidated as well. This is usually true for a full 14154 * invalidate, but may be set to false if the View's contents or 14155 * dimensions have not changed. 14156 * @hide 14157 */ 14158 public void invalidate(boolean invalidateCache) { 14159 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 14160 } 14161 14162 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 14163 boolean fullInvalidate) { 14164 if (mGhostView != null) { 14165 mGhostView.invalidate(true); 14166 return; 14167 } 14168 14169 if (skipInvalidate()) { 14170 return; 14171 } 14172 14173 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 14174 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 14175 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 14176 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 14177 if (fullInvalidate) { 14178 mLastIsOpaque = isOpaque(); 14179 mPrivateFlags &= ~PFLAG_DRAWN; 14180 } 14181 14182 mPrivateFlags |= PFLAG_DIRTY; 14183 14184 if (invalidateCache) { 14185 mPrivateFlags |= PFLAG_INVALIDATED; 14186 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14187 } 14188 14189 // Propagate the damage rectangle to the parent view. 14190 final AttachInfo ai = mAttachInfo; 14191 final ViewParent p = mParent; 14192 if (p != null && ai != null && l < r && t < b) { 14193 final Rect damage = ai.mTmpInvalRect; 14194 damage.set(l, t, r, b); 14195 p.invalidateChild(this, damage); 14196 } 14197 14198 // Damage the entire projection receiver, if necessary. 14199 if (mBackground != null && mBackground.isProjected()) { 14200 final View receiver = getProjectionReceiver(); 14201 if (receiver != null) { 14202 receiver.damageInParent(); 14203 } 14204 } 14205 } 14206 } 14207 14208 /** 14209 * @return this view's projection receiver, or {@code null} if none exists 14210 */ 14211 private View getProjectionReceiver() { 14212 ViewParent p = getParent(); 14213 while (p != null && p instanceof View) { 14214 final View v = (View) p; 14215 if (v.isProjectionReceiver()) { 14216 return v; 14217 } 14218 p = p.getParent(); 14219 } 14220 14221 return null; 14222 } 14223 14224 /** 14225 * @return whether the view is a projection receiver 14226 */ 14227 private boolean isProjectionReceiver() { 14228 return mBackground != null; 14229 } 14230 14231 /** 14232 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 14233 * set any flags or handle all of the cases handled by the default invalidation methods. 14234 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 14235 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 14236 * walk up the hierarchy, transforming the dirty rect as necessary. 14237 * 14238 * The method also handles normal invalidation logic if display list properties are not 14239 * being used in this view. The invalidateParent and forceRedraw flags are used by that 14240 * backup approach, to handle these cases used in the various property-setting methods. 14241 * 14242 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 14243 * are not being used in this view 14244 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 14245 * list properties are not being used in this view 14246 */ 14247 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 14248 if (!isHardwareAccelerated() 14249 || !mRenderNode.isValid() 14250 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 14251 if (invalidateParent) { 14252 invalidateParentCaches(); 14253 } 14254 if (forceRedraw) { 14255 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14256 } 14257 invalidate(false); 14258 } else { 14259 damageInParent(); 14260 } 14261 } 14262 14263 /** 14264 * Tells the parent view to damage this view's bounds. 14265 * 14266 * @hide 14267 */ 14268 protected void damageInParent() { 14269 final AttachInfo ai = mAttachInfo; 14270 final ViewParent p = mParent; 14271 if (p != null && ai != null) { 14272 final Rect r = ai.mTmpInvalRect; 14273 r.set(0, 0, mRight - mLeft, mBottom - mTop); 14274 if (mParent instanceof ViewGroup) { 14275 ((ViewGroup) mParent).damageChild(this, r); 14276 } else { 14277 mParent.invalidateChild(this, r); 14278 } 14279 } 14280 } 14281 14282 /** 14283 * Utility method to transform a given Rect by the current matrix of this view. 14284 */ 14285 void transformRect(final Rect rect) { 14286 if (!getMatrix().isIdentity()) { 14287 RectF boundingRect = mAttachInfo.mTmpTransformRect; 14288 boundingRect.set(rect); 14289 getMatrix().mapRect(boundingRect); 14290 rect.set((int) Math.floor(boundingRect.left), 14291 (int) Math.floor(boundingRect.top), 14292 (int) Math.ceil(boundingRect.right), 14293 (int) Math.ceil(boundingRect.bottom)); 14294 } 14295 } 14296 14297 /** 14298 * Used to indicate that the parent of this view should clear its caches. This functionality 14299 * is used to force the parent to rebuild its display list (when hardware-accelerated), 14300 * which is necessary when various parent-managed properties of the view change, such as 14301 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 14302 * clears the parent caches and does not causes an invalidate event. 14303 * 14304 * @hide 14305 */ 14306 protected void invalidateParentCaches() { 14307 if (mParent instanceof View) { 14308 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 14309 } 14310 } 14311 14312 /** 14313 * Used to indicate that the parent of this view should be invalidated. This functionality 14314 * is used to force the parent to rebuild its display list (when hardware-accelerated), 14315 * which is necessary when various parent-managed properties of the view change, such as 14316 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 14317 * an invalidation event to the parent. 14318 * 14319 * @hide 14320 */ 14321 protected void invalidateParentIfNeeded() { 14322 if (isHardwareAccelerated() && mParent instanceof View) { 14323 ((View) mParent).invalidate(true); 14324 } 14325 } 14326 14327 /** 14328 * @hide 14329 */ 14330 protected void invalidateParentIfNeededAndWasQuickRejected() { 14331 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 14332 // View was rejected last time it was drawn by its parent; this may have changed 14333 invalidateParentIfNeeded(); 14334 } 14335 } 14336 14337 /** 14338 * Indicates whether this View is opaque. An opaque View guarantees that it will 14339 * draw all the pixels overlapping its bounds using a fully opaque color. 14340 * 14341 * Subclasses of View should override this method whenever possible to indicate 14342 * whether an instance is opaque. Opaque Views are treated in a special way by 14343 * the View hierarchy, possibly allowing it to perform optimizations during 14344 * invalidate/draw passes. 14345 * 14346 * @return True if this View is guaranteed to be fully opaque, false otherwise. 14347 */ 14348 @ViewDebug.ExportedProperty(category = "drawing") 14349 public boolean isOpaque() { 14350 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 14351 getFinalAlpha() >= 1.0f; 14352 } 14353 14354 /** 14355 * @hide 14356 */ 14357 protected void computeOpaqueFlags() { 14358 // Opaque if: 14359 // - Has a background 14360 // - Background is opaque 14361 // - Doesn't have scrollbars or scrollbars overlay 14362 14363 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 14364 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 14365 } else { 14366 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 14367 } 14368 14369 final int flags = mViewFlags; 14370 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 14371 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 14372 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 14373 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 14374 } else { 14375 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 14376 } 14377 } 14378 14379 /** 14380 * @hide 14381 */ 14382 protected boolean hasOpaqueScrollbars() { 14383 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 14384 } 14385 14386 /** 14387 * @return A handler associated with the thread running the View. This 14388 * handler can be used to pump events in the UI events queue. 14389 */ 14390 public Handler getHandler() { 14391 final AttachInfo attachInfo = mAttachInfo; 14392 if (attachInfo != null) { 14393 return attachInfo.mHandler; 14394 } 14395 return null; 14396 } 14397 14398 /** 14399 * Returns the queue of runnable for this view. 14400 * 14401 * @return the queue of runnables for this view 14402 */ 14403 private HandlerActionQueue getRunQueue() { 14404 if (mRunQueue == null) { 14405 mRunQueue = new HandlerActionQueue(); 14406 } 14407 return mRunQueue; 14408 } 14409 14410 /** 14411 * Gets the view root associated with the View. 14412 * @return The view root, or null if none. 14413 * @hide 14414 */ 14415 public ViewRootImpl getViewRootImpl() { 14416 if (mAttachInfo != null) { 14417 return mAttachInfo.mViewRootImpl; 14418 } 14419 return null; 14420 } 14421 14422 /** 14423 * @hide 14424 */ 14425 public ThreadedRenderer getThreadedRenderer() { 14426 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 14427 } 14428 14429 /** 14430 * <p>Causes the Runnable to be added to the message queue. 14431 * The runnable will be run on the user interface thread.</p> 14432 * 14433 * @param action The Runnable that will be executed. 14434 * 14435 * @return Returns true if the Runnable was successfully placed in to the 14436 * message queue. Returns false on failure, usually because the 14437 * looper processing the message queue is exiting. 14438 * 14439 * @see #postDelayed 14440 * @see #removeCallbacks 14441 */ 14442 public boolean post(Runnable action) { 14443 final AttachInfo attachInfo = mAttachInfo; 14444 if (attachInfo != null) { 14445 return attachInfo.mHandler.post(action); 14446 } 14447 14448 // Postpone the runnable until we know on which thread it needs to run. 14449 // Assume that the runnable will be successfully placed after attach. 14450 getRunQueue().post(action); 14451 return true; 14452 } 14453 14454 /** 14455 * <p>Causes the Runnable to be added to the message queue, to be run 14456 * after the specified amount of time elapses. 14457 * The runnable will be run on the user interface thread.</p> 14458 * 14459 * @param action The Runnable that will be executed. 14460 * @param delayMillis The delay (in milliseconds) until the Runnable 14461 * will be executed. 14462 * 14463 * @return true if the Runnable was successfully placed in to the 14464 * message queue. Returns false on failure, usually because the 14465 * looper processing the message queue is exiting. Note that a 14466 * result of true does not mean the Runnable will be processed -- 14467 * if the looper is quit before the delivery time of the message 14468 * occurs then the message will be dropped. 14469 * 14470 * @see #post 14471 * @see #removeCallbacks 14472 */ 14473 public boolean postDelayed(Runnable action, long delayMillis) { 14474 final AttachInfo attachInfo = mAttachInfo; 14475 if (attachInfo != null) { 14476 return attachInfo.mHandler.postDelayed(action, delayMillis); 14477 } 14478 14479 // Postpone the runnable until we know on which thread it needs to run. 14480 // Assume that the runnable will be successfully placed after attach. 14481 getRunQueue().postDelayed(action, delayMillis); 14482 return true; 14483 } 14484 14485 /** 14486 * <p>Causes the Runnable to execute on the next animation time step. 14487 * The runnable will be run on the user interface thread.</p> 14488 * 14489 * @param action The Runnable that will be executed. 14490 * 14491 * @see #postOnAnimationDelayed 14492 * @see #removeCallbacks 14493 */ 14494 public void postOnAnimation(Runnable action) { 14495 final AttachInfo attachInfo = mAttachInfo; 14496 if (attachInfo != null) { 14497 attachInfo.mViewRootImpl.mChoreographer.postCallback( 14498 Choreographer.CALLBACK_ANIMATION, action, null); 14499 } else { 14500 // Postpone the runnable until we know 14501 // on which thread it needs to run. 14502 getRunQueue().post(action); 14503 } 14504 } 14505 14506 /** 14507 * <p>Causes the Runnable to execute on the next animation time step, 14508 * after the specified amount of time elapses. 14509 * The runnable will be run on the user interface thread.</p> 14510 * 14511 * @param action The Runnable that will be executed. 14512 * @param delayMillis The delay (in milliseconds) until the Runnable 14513 * will be executed. 14514 * 14515 * @see #postOnAnimation 14516 * @see #removeCallbacks 14517 */ 14518 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 14519 final AttachInfo attachInfo = mAttachInfo; 14520 if (attachInfo != null) { 14521 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14522 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 14523 } else { 14524 // Postpone the runnable until we know 14525 // on which thread it needs to run. 14526 getRunQueue().postDelayed(action, delayMillis); 14527 } 14528 } 14529 14530 /** 14531 * <p>Removes the specified Runnable from the message queue.</p> 14532 * 14533 * @param action The Runnable to remove from the message handling queue 14534 * 14535 * @return true if this view could ask the Handler to remove the Runnable, 14536 * false otherwise. When the returned value is true, the Runnable 14537 * may or may not have been actually removed from the message queue 14538 * (for instance, if the Runnable was not in the queue already.) 14539 * 14540 * @see #post 14541 * @see #postDelayed 14542 * @see #postOnAnimation 14543 * @see #postOnAnimationDelayed 14544 */ 14545 public boolean removeCallbacks(Runnable action) { 14546 if (action != null) { 14547 final AttachInfo attachInfo = mAttachInfo; 14548 if (attachInfo != null) { 14549 attachInfo.mHandler.removeCallbacks(action); 14550 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14551 Choreographer.CALLBACK_ANIMATION, action, null); 14552 } 14553 getRunQueue().removeCallbacks(action); 14554 } 14555 return true; 14556 } 14557 14558 /** 14559 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 14560 * Use this to invalidate the View from a non-UI thread.</p> 14561 * 14562 * <p>This method can be invoked from outside of the UI thread 14563 * only when this View is attached to a window.</p> 14564 * 14565 * @see #invalidate() 14566 * @see #postInvalidateDelayed(long) 14567 */ 14568 public void postInvalidate() { 14569 postInvalidateDelayed(0); 14570 } 14571 14572 /** 14573 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14574 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 14575 * 14576 * <p>This method can be invoked from outside of the UI thread 14577 * only when this View is attached to a window.</p> 14578 * 14579 * @param left The left coordinate of the rectangle to invalidate. 14580 * @param top The top coordinate of the rectangle to invalidate. 14581 * @param right The right coordinate of the rectangle to invalidate. 14582 * @param bottom The bottom coordinate of the rectangle to invalidate. 14583 * 14584 * @see #invalidate(int, int, int, int) 14585 * @see #invalidate(Rect) 14586 * @see #postInvalidateDelayed(long, int, int, int, int) 14587 */ 14588 public void postInvalidate(int left, int top, int right, int bottom) { 14589 postInvalidateDelayed(0, left, top, right, bottom); 14590 } 14591 14592 /** 14593 * <p>Cause an invalidate to happen on a subsequent cycle through the event 14594 * loop. Waits for the specified amount of time.</p> 14595 * 14596 * <p>This method can be invoked from outside of the UI thread 14597 * only when this View is attached to a window.</p> 14598 * 14599 * @param delayMilliseconds the duration in milliseconds to delay the 14600 * invalidation by 14601 * 14602 * @see #invalidate() 14603 * @see #postInvalidate() 14604 */ 14605 public void postInvalidateDelayed(long delayMilliseconds) { 14606 // We try only with the AttachInfo because there's no point in invalidating 14607 // if we are not attached to our window 14608 final AttachInfo attachInfo = mAttachInfo; 14609 if (attachInfo != null) { 14610 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14611 } 14612 } 14613 14614 /** 14615 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14616 * through the event loop. Waits for the specified amount of time.</p> 14617 * 14618 * <p>This method can be invoked from outside of the UI thread 14619 * only when this View is attached to a window.</p> 14620 * 14621 * @param delayMilliseconds the duration in milliseconds to delay the 14622 * invalidation by 14623 * @param left The left coordinate of the rectangle to invalidate. 14624 * @param top The top coordinate of the rectangle to invalidate. 14625 * @param right The right coordinate of the rectangle to invalidate. 14626 * @param bottom The bottom coordinate of the rectangle to invalidate. 14627 * 14628 * @see #invalidate(int, int, int, int) 14629 * @see #invalidate(Rect) 14630 * @see #postInvalidate(int, int, int, int) 14631 */ 14632 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14633 int right, int bottom) { 14634 14635 // We try only with the AttachInfo because there's no point in invalidating 14636 // if we are not attached to our window 14637 final AttachInfo attachInfo = mAttachInfo; 14638 if (attachInfo != null) { 14639 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14640 info.target = this; 14641 info.left = left; 14642 info.top = top; 14643 info.right = right; 14644 info.bottom = bottom; 14645 14646 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14647 } 14648 } 14649 14650 /** 14651 * <p>Cause an invalidate to happen on the next animation time step, typically the 14652 * next display frame.</p> 14653 * 14654 * <p>This method can be invoked from outside of the UI thread 14655 * only when this View is attached to a window.</p> 14656 * 14657 * @see #invalidate() 14658 */ 14659 public void postInvalidateOnAnimation() { 14660 // We try only with the AttachInfo because there's no point in invalidating 14661 // if we are not attached to our window 14662 final AttachInfo attachInfo = mAttachInfo; 14663 if (attachInfo != null) { 14664 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14665 } 14666 } 14667 14668 /** 14669 * <p>Cause an invalidate of the specified area to happen on the next animation 14670 * time step, typically the next display frame.</p> 14671 * 14672 * <p>This method can be invoked from outside of the UI thread 14673 * only when this View is attached to a window.</p> 14674 * 14675 * @param left The left coordinate of the rectangle to invalidate. 14676 * @param top The top coordinate of the rectangle to invalidate. 14677 * @param right The right coordinate of the rectangle to invalidate. 14678 * @param bottom The bottom coordinate of the rectangle to invalidate. 14679 * 14680 * @see #invalidate(int, int, int, int) 14681 * @see #invalidate(Rect) 14682 */ 14683 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14684 // We try only with the AttachInfo because there's no point in invalidating 14685 // if we are not attached to our window 14686 final AttachInfo attachInfo = mAttachInfo; 14687 if (attachInfo != null) { 14688 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14689 info.target = this; 14690 info.left = left; 14691 info.top = top; 14692 info.right = right; 14693 info.bottom = bottom; 14694 14695 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14696 } 14697 } 14698 14699 /** 14700 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14701 * This event is sent at most once every 14702 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14703 */ 14704 private void postSendViewScrolledAccessibilityEventCallback() { 14705 if (mSendViewScrolledAccessibilityEvent == null) { 14706 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14707 } 14708 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14709 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14710 postDelayed(mSendViewScrolledAccessibilityEvent, 14711 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14712 } 14713 } 14714 14715 /** 14716 * Called by a parent to request that a child update its values for mScrollX 14717 * and mScrollY if necessary. This will typically be done if the child is 14718 * animating a scroll using a {@link android.widget.Scroller Scroller} 14719 * object. 14720 */ 14721 public void computeScroll() { 14722 } 14723 14724 /** 14725 * <p>Indicate whether the horizontal edges are faded when the view is 14726 * scrolled horizontally.</p> 14727 * 14728 * @return true if the horizontal edges should are faded on scroll, false 14729 * otherwise 14730 * 14731 * @see #setHorizontalFadingEdgeEnabled(boolean) 14732 * 14733 * @attr ref android.R.styleable#View_requiresFadingEdge 14734 */ 14735 public boolean isHorizontalFadingEdgeEnabled() { 14736 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14737 } 14738 14739 /** 14740 * <p>Define whether the horizontal edges should be faded when this view 14741 * is scrolled horizontally.</p> 14742 * 14743 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14744 * be faded when the view is scrolled 14745 * horizontally 14746 * 14747 * @see #isHorizontalFadingEdgeEnabled() 14748 * 14749 * @attr ref android.R.styleable#View_requiresFadingEdge 14750 */ 14751 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14752 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14753 if (horizontalFadingEdgeEnabled) { 14754 initScrollCache(); 14755 } 14756 14757 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14758 } 14759 } 14760 14761 /** 14762 * <p>Indicate whether the vertical edges are faded when the view is 14763 * scrolled horizontally.</p> 14764 * 14765 * @return true if the vertical edges should are faded on scroll, false 14766 * otherwise 14767 * 14768 * @see #setVerticalFadingEdgeEnabled(boolean) 14769 * 14770 * @attr ref android.R.styleable#View_requiresFadingEdge 14771 */ 14772 public boolean isVerticalFadingEdgeEnabled() { 14773 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14774 } 14775 14776 /** 14777 * <p>Define whether the vertical edges should be faded when this view 14778 * is scrolled vertically.</p> 14779 * 14780 * @param verticalFadingEdgeEnabled true if the vertical edges should 14781 * be faded when the view is scrolled 14782 * vertically 14783 * 14784 * @see #isVerticalFadingEdgeEnabled() 14785 * 14786 * @attr ref android.R.styleable#View_requiresFadingEdge 14787 */ 14788 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14789 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14790 if (verticalFadingEdgeEnabled) { 14791 initScrollCache(); 14792 } 14793 14794 mViewFlags ^= FADING_EDGE_VERTICAL; 14795 } 14796 } 14797 14798 /** 14799 * Returns the strength, or intensity, of the top faded edge. The strength is 14800 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14801 * returns 0.0 or 1.0 but no value in between. 14802 * 14803 * Subclasses should override this method to provide a smoother fade transition 14804 * when scrolling occurs. 14805 * 14806 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14807 */ 14808 protected float getTopFadingEdgeStrength() { 14809 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14810 } 14811 14812 /** 14813 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14814 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14815 * returns 0.0 or 1.0 but no value in between. 14816 * 14817 * Subclasses should override this method to provide a smoother fade transition 14818 * when scrolling occurs. 14819 * 14820 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14821 */ 14822 protected float getBottomFadingEdgeStrength() { 14823 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14824 computeVerticalScrollRange() ? 1.0f : 0.0f; 14825 } 14826 14827 /** 14828 * Returns the strength, or intensity, of the left faded edge. The strength is 14829 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14830 * returns 0.0 or 1.0 but no value in between. 14831 * 14832 * Subclasses should override this method to provide a smoother fade transition 14833 * when scrolling occurs. 14834 * 14835 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14836 */ 14837 protected float getLeftFadingEdgeStrength() { 14838 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14839 } 14840 14841 /** 14842 * Returns the strength, or intensity, of the right faded edge. The strength is 14843 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14844 * returns 0.0 or 1.0 but no value in between. 14845 * 14846 * Subclasses should override this method to provide a smoother fade transition 14847 * when scrolling occurs. 14848 * 14849 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14850 */ 14851 protected float getRightFadingEdgeStrength() { 14852 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14853 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14854 } 14855 14856 /** 14857 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14858 * scrollbar is not drawn by default.</p> 14859 * 14860 * @return true if the horizontal scrollbar should be painted, false 14861 * otherwise 14862 * 14863 * @see #setHorizontalScrollBarEnabled(boolean) 14864 */ 14865 public boolean isHorizontalScrollBarEnabled() { 14866 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14867 } 14868 14869 /** 14870 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14871 * scrollbar is not drawn by default.</p> 14872 * 14873 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14874 * be painted 14875 * 14876 * @see #isHorizontalScrollBarEnabled() 14877 */ 14878 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14879 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14880 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14881 computeOpaqueFlags(); 14882 resolvePadding(); 14883 } 14884 } 14885 14886 /** 14887 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14888 * scrollbar is not drawn by default.</p> 14889 * 14890 * @return true if the vertical scrollbar should be painted, false 14891 * otherwise 14892 * 14893 * @see #setVerticalScrollBarEnabled(boolean) 14894 */ 14895 public boolean isVerticalScrollBarEnabled() { 14896 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14897 } 14898 14899 /** 14900 * <p>Define whether the vertical scrollbar should be drawn or not. The 14901 * scrollbar is not drawn by default.</p> 14902 * 14903 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14904 * be painted 14905 * 14906 * @see #isVerticalScrollBarEnabled() 14907 */ 14908 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14909 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14910 mViewFlags ^= SCROLLBARS_VERTICAL; 14911 computeOpaqueFlags(); 14912 resolvePadding(); 14913 } 14914 } 14915 14916 /** 14917 * @hide 14918 */ 14919 protected void recomputePadding() { 14920 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14921 } 14922 14923 /** 14924 * Define whether scrollbars will fade when the view is not scrolling. 14925 * 14926 * @param fadeScrollbars whether to enable fading 14927 * 14928 * @attr ref android.R.styleable#View_fadeScrollbars 14929 */ 14930 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14931 initScrollCache(); 14932 final ScrollabilityCache scrollabilityCache = mScrollCache; 14933 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14934 if (fadeScrollbars) { 14935 scrollabilityCache.state = ScrollabilityCache.OFF; 14936 } else { 14937 scrollabilityCache.state = ScrollabilityCache.ON; 14938 } 14939 } 14940 14941 /** 14942 * 14943 * Returns true if scrollbars will fade when this view is not scrolling 14944 * 14945 * @return true if scrollbar fading is enabled 14946 * 14947 * @attr ref android.R.styleable#View_fadeScrollbars 14948 */ 14949 public boolean isScrollbarFadingEnabled() { 14950 return mScrollCache != null && mScrollCache.fadeScrollBars; 14951 } 14952 14953 /** 14954 * 14955 * Returns the delay before scrollbars fade. 14956 * 14957 * @return the delay before scrollbars fade 14958 * 14959 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14960 */ 14961 public int getScrollBarDefaultDelayBeforeFade() { 14962 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14963 mScrollCache.scrollBarDefaultDelayBeforeFade; 14964 } 14965 14966 /** 14967 * Define the delay before scrollbars fade. 14968 * 14969 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14970 * 14971 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14972 */ 14973 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14974 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14975 } 14976 14977 /** 14978 * 14979 * Returns the scrollbar fade duration. 14980 * 14981 * @return the scrollbar fade duration, in milliseconds 14982 * 14983 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14984 */ 14985 public int getScrollBarFadeDuration() { 14986 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14987 mScrollCache.scrollBarFadeDuration; 14988 } 14989 14990 /** 14991 * Define the scrollbar fade duration. 14992 * 14993 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 14994 * 14995 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14996 */ 14997 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14998 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14999 } 15000 15001 /** 15002 * 15003 * Returns the scrollbar size. 15004 * 15005 * @return the scrollbar size 15006 * 15007 * @attr ref android.R.styleable#View_scrollbarSize 15008 */ 15009 public int getScrollBarSize() { 15010 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 15011 mScrollCache.scrollBarSize; 15012 } 15013 15014 /** 15015 * Define the scrollbar size. 15016 * 15017 * @param scrollBarSize - the scrollbar size 15018 * 15019 * @attr ref android.R.styleable#View_scrollbarSize 15020 */ 15021 public void setScrollBarSize(int scrollBarSize) { 15022 getScrollCache().scrollBarSize = scrollBarSize; 15023 } 15024 15025 /** 15026 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 15027 * inset. When inset, they add to the padding of the view. And the scrollbars 15028 * can be drawn inside the padding area or on the edge of the view. For example, 15029 * if a view has a background drawable and you want to draw the scrollbars 15030 * inside the padding specified by the drawable, you can use 15031 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 15032 * appear at the edge of the view, ignoring the padding, then you can use 15033 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 15034 * @param style the style of the scrollbars. Should be one of 15035 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 15036 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 15037 * @see #SCROLLBARS_INSIDE_OVERLAY 15038 * @see #SCROLLBARS_INSIDE_INSET 15039 * @see #SCROLLBARS_OUTSIDE_OVERLAY 15040 * @see #SCROLLBARS_OUTSIDE_INSET 15041 * 15042 * @attr ref android.R.styleable#View_scrollbarStyle 15043 */ 15044 public void setScrollBarStyle(@ScrollBarStyle int style) { 15045 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 15046 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 15047 computeOpaqueFlags(); 15048 resolvePadding(); 15049 } 15050 } 15051 15052 /** 15053 * <p>Returns the current scrollbar style.</p> 15054 * @return the current scrollbar style 15055 * @see #SCROLLBARS_INSIDE_OVERLAY 15056 * @see #SCROLLBARS_INSIDE_INSET 15057 * @see #SCROLLBARS_OUTSIDE_OVERLAY 15058 * @see #SCROLLBARS_OUTSIDE_INSET 15059 * 15060 * @attr ref android.R.styleable#View_scrollbarStyle 15061 */ 15062 @ViewDebug.ExportedProperty(mapping = { 15063 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 15064 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 15065 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 15066 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 15067 }) 15068 @ScrollBarStyle 15069 public int getScrollBarStyle() { 15070 return mViewFlags & SCROLLBARS_STYLE_MASK; 15071 } 15072 15073 /** 15074 * <p>Compute the horizontal range that the horizontal scrollbar 15075 * represents.</p> 15076 * 15077 * <p>The range is expressed in arbitrary units that must be the same as the 15078 * units used by {@link #computeHorizontalScrollExtent()} and 15079 * {@link #computeHorizontalScrollOffset()}.</p> 15080 * 15081 * <p>The default range is the drawing width of this view.</p> 15082 * 15083 * @return the total horizontal range represented by the horizontal 15084 * scrollbar 15085 * 15086 * @see #computeHorizontalScrollExtent() 15087 * @see #computeHorizontalScrollOffset() 15088 * @see android.widget.ScrollBarDrawable 15089 */ 15090 protected int computeHorizontalScrollRange() { 15091 return getWidth(); 15092 } 15093 15094 /** 15095 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 15096 * within the horizontal range. This value is used to compute the position 15097 * of the thumb within the scrollbar's track.</p> 15098 * 15099 * <p>The range is expressed in arbitrary units that must be the same as the 15100 * units used by {@link #computeHorizontalScrollRange()} and 15101 * {@link #computeHorizontalScrollExtent()}.</p> 15102 * 15103 * <p>The default offset is the scroll offset of this view.</p> 15104 * 15105 * @return the horizontal offset of the scrollbar's thumb 15106 * 15107 * @see #computeHorizontalScrollRange() 15108 * @see #computeHorizontalScrollExtent() 15109 * @see android.widget.ScrollBarDrawable 15110 */ 15111 protected int computeHorizontalScrollOffset() { 15112 return mScrollX; 15113 } 15114 15115 /** 15116 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 15117 * within the horizontal range. This value is used to compute the length 15118 * of the thumb within the scrollbar's track.</p> 15119 * 15120 * <p>The range is expressed in arbitrary units that must be the same as the 15121 * units used by {@link #computeHorizontalScrollRange()} and 15122 * {@link #computeHorizontalScrollOffset()}.</p> 15123 * 15124 * <p>The default extent is the drawing width of this view.</p> 15125 * 15126 * @return the horizontal extent of the scrollbar's thumb 15127 * 15128 * @see #computeHorizontalScrollRange() 15129 * @see #computeHorizontalScrollOffset() 15130 * @see android.widget.ScrollBarDrawable 15131 */ 15132 protected int computeHorizontalScrollExtent() { 15133 return getWidth(); 15134 } 15135 15136 /** 15137 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 15138 * 15139 * <p>The range is expressed in arbitrary units that must be the same as the 15140 * units used by {@link #computeVerticalScrollExtent()} and 15141 * {@link #computeVerticalScrollOffset()}.</p> 15142 * 15143 * @return the total vertical range represented by the vertical scrollbar 15144 * 15145 * <p>The default range is the drawing height of this view.</p> 15146 * 15147 * @see #computeVerticalScrollExtent() 15148 * @see #computeVerticalScrollOffset() 15149 * @see android.widget.ScrollBarDrawable 15150 */ 15151 protected int computeVerticalScrollRange() { 15152 return getHeight(); 15153 } 15154 15155 /** 15156 * <p>Compute the vertical offset of the vertical scrollbar's thumb 15157 * within the horizontal range. This value is used to compute the position 15158 * of the thumb within the scrollbar's track.</p> 15159 * 15160 * <p>The range is expressed in arbitrary units that must be the same as the 15161 * units used by {@link #computeVerticalScrollRange()} and 15162 * {@link #computeVerticalScrollExtent()}.</p> 15163 * 15164 * <p>The default offset is the scroll offset of this view.</p> 15165 * 15166 * @return the vertical offset of the scrollbar's thumb 15167 * 15168 * @see #computeVerticalScrollRange() 15169 * @see #computeVerticalScrollExtent() 15170 * @see android.widget.ScrollBarDrawable 15171 */ 15172 protected int computeVerticalScrollOffset() { 15173 return mScrollY; 15174 } 15175 15176 /** 15177 * <p>Compute the vertical extent of the vertical scrollbar's thumb 15178 * within the vertical range. This value is used to compute the length 15179 * of the thumb within the scrollbar's track.</p> 15180 * 15181 * <p>The range is expressed in arbitrary units that must be the same as the 15182 * units used by {@link #computeVerticalScrollRange()} and 15183 * {@link #computeVerticalScrollOffset()}.</p> 15184 * 15185 * <p>The default extent is the drawing height of this view.</p> 15186 * 15187 * @return the vertical extent of the scrollbar's thumb 15188 * 15189 * @see #computeVerticalScrollRange() 15190 * @see #computeVerticalScrollOffset() 15191 * @see android.widget.ScrollBarDrawable 15192 */ 15193 protected int computeVerticalScrollExtent() { 15194 return getHeight(); 15195 } 15196 15197 /** 15198 * Check if this view can be scrolled horizontally in a certain direction. 15199 * 15200 * @param direction Negative to check scrolling left, positive to check scrolling right. 15201 * @return true if this view can be scrolled in the specified direction, false otherwise. 15202 */ 15203 public boolean canScrollHorizontally(int direction) { 15204 final int offset = computeHorizontalScrollOffset(); 15205 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 15206 if (range == 0) return false; 15207 if (direction < 0) { 15208 return offset > 0; 15209 } else { 15210 return offset < range - 1; 15211 } 15212 } 15213 15214 /** 15215 * Check if this view can be scrolled vertically in a certain direction. 15216 * 15217 * @param direction Negative to check scrolling up, positive to check scrolling down. 15218 * @return true if this view can be scrolled in the specified direction, false otherwise. 15219 */ 15220 public boolean canScrollVertically(int direction) { 15221 final int offset = computeVerticalScrollOffset(); 15222 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 15223 if (range == 0) return false; 15224 if (direction < 0) { 15225 return offset > 0; 15226 } else { 15227 return offset < range - 1; 15228 } 15229 } 15230 15231 void getScrollIndicatorBounds(@NonNull Rect out) { 15232 out.left = mScrollX; 15233 out.right = mScrollX + mRight - mLeft; 15234 out.top = mScrollY; 15235 out.bottom = mScrollY + mBottom - mTop; 15236 } 15237 15238 private void onDrawScrollIndicators(Canvas c) { 15239 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 15240 // No scroll indicators enabled. 15241 return; 15242 } 15243 15244 final Drawable dr = mScrollIndicatorDrawable; 15245 if (dr == null) { 15246 // Scroll indicators aren't supported here. 15247 return; 15248 } 15249 15250 final int h = dr.getIntrinsicHeight(); 15251 final int w = dr.getIntrinsicWidth(); 15252 final Rect rect = mAttachInfo.mTmpInvalRect; 15253 getScrollIndicatorBounds(rect); 15254 15255 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 15256 final boolean canScrollUp = canScrollVertically(-1); 15257 if (canScrollUp) { 15258 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 15259 dr.draw(c); 15260 } 15261 } 15262 15263 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 15264 final boolean canScrollDown = canScrollVertically(1); 15265 if (canScrollDown) { 15266 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 15267 dr.draw(c); 15268 } 15269 } 15270 15271 final int leftRtl; 15272 final int rightRtl; 15273 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15274 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 15275 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 15276 } else { 15277 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 15278 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 15279 } 15280 15281 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 15282 if ((mPrivateFlags3 & leftMask) != 0) { 15283 final boolean canScrollLeft = canScrollHorizontally(-1); 15284 if (canScrollLeft) { 15285 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 15286 dr.draw(c); 15287 } 15288 } 15289 15290 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 15291 if ((mPrivateFlags3 & rightMask) != 0) { 15292 final boolean canScrollRight = canScrollHorizontally(1); 15293 if (canScrollRight) { 15294 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 15295 dr.draw(c); 15296 } 15297 } 15298 } 15299 15300 private void getHorizontalScrollBarBounds(Rect bounds) { 15301 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 15302 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 15303 && !isVerticalScrollBarHidden(); 15304 final int size = getHorizontalScrollbarHeight(); 15305 final int verticalScrollBarGap = drawVerticalScrollBar ? 15306 getVerticalScrollbarWidth() : 0; 15307 final int width = mRight - mLeft; 15308 final int height = mBottom - mTop; 15309 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 15310 bounds.left = mScrollX + (mPaddingLeft & inside); 15311 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 15312 bounds.bottom = bounds.top + size; 15313 } 15314 15315 private void getVerticalScrollBarBounds(Rect bounds) { 15316 if (mRoundScrollbarRenderer == null) { 15317 getStraightVerticalScrollBarBounds(bounds); 15318 } else { 15319 getRoundVerticalScrollBarBounds(bounds); 15320 } 15321 } 15322 15323 private void getRoundVerticalScrollBarBounds(Rect bounds) { 15324 final int width = mRight - mLeft; 15325 final int height = mBottom - mTop; 15326 // Do not take padding into account as we always want the scrollbars 15327 // to hug the screen for round wearable devices. 15328 bounds.left = mScrollX; 15329 bounds.top = mScrollY; 15330 bounds.right = bounds.left + width; 15331 bounds.bottom = mScrollY + height; 15332 } 15333 15334 private void getStraightVerticalScrollBarBounds(Rect bounds) { 15335 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 15336 final int size = getVerticalScrollbarWidth(); 15337 int verticalScrollbarPosition = mVerticalScrollbarPosition; 15338 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 15339 verticalScrollbarPosition = isLayoutRtl() ? 15340 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 15341 } 15342 final int width = mRight - mLeft; 15343 final int height = mBottom - mTop; 15344 switch (verticalScrollbarPosition) { 15345 default: 15346 case SCROLLBAR_POSITION_RIGHT: 15347 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 15348 break; 15349 case SCROLLBAR_POSITION_LEFT: 15350 bounds.left = mScrollX + (mUserPaddingLeft & inside); 15351 break; 15352 } 15353 bounds.top = mScrollY + (mPaddingTop & inside); 15354 bounds.right = bounds.left + size; 15355 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 15356 } 15357 15358 /** 15359 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 15360 * scrollbars are painted only if they have been awakened first.</p> 15361 * 15362 * @param canvas the canvas on which to draw the scrollbars 15363 * 15364 * @see #awakenScrollBars(int) 15365 */ 15366 protected final void onDrawScrollBars(Canvas canvas) { 15367 // scrollbars are drawn only when the animation is running 15368 final ScrollabilityCache cache = mScrollCache; 15369 15370 if (cache != null) { 15371 15372 int state = cache.state; 15373 15374 if (state == ScrollabilityCache.OFF) { 15375 return; 15376 } 15377 15378 boolean invalidate = false; 15379 15380 if (state == ScrollabilityCache.FADING) { 15381 // We're fading -- get our fade interpolation 15382 if (cache.interpolatorValues == null) { 15383 cache.interpolatorValues = new float[1]; 15384 } 15385 15386 float[] values = cache.interpolatorValues; 15387 15388 // Stops the animation if we're done 15389 if (cache.scrollBarInterpolator.timeToValues(values) == 15390 Interpolator.Result.FREEZE_END) { 15391 cache.state = ScrollabilityCache.OFF; 15392 } else { 15393 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 15394 } 15395 15396 // This will make the scroll bars inval themselves after 15397 // drawing. We only want this when we're fading so that 15398 // we prevent excessive redraws 15399 invalidate = true; 15400 } else { 15401 // We're just on -- but we may have been fading before so 15402 // reset alpha 15403 cache.scrollBar.mutate().setAlpha(255); 15404 } 15405 15406 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 15407 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 15408 && !isVerticalScrollBarHidden(); 15409 15410 // Fork out the scroll bar drawing for round wearable devices. 15411 if (mRoundScrollbarRenderer != null) { 15412 if (drawVerticalScrollBar) { 15413 final Rect bounds = cache.mScrollBarBounds; 15414 getVerticalScrollBarBounds(bounds); 15415 mRoundScrollbarRenderer.drawRoundScrollbars( 15416 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 15417 if (invalidate) { 15418 invalidate(); 15419 } 15420 } 15421 // Do not draw horizontal scroll bars for round wearable devices. 15422 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 15423 final ScrollBarDrawable scrollBar = cache.scrollBar; 15424 15425 if (drawHorizontalScrollBar) { 15426 scrollBar.setParameters(computeHorizontalScrollRange(), 15427 computeHorizontalScrollOffset(), 15428 computeHorizontalScrollExtent(), false); 15429 final Rect bounds = cache.mScrollBarBounds; 15430 getHorizontalScrollBarBounds(bounds); 15431 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 15432 bounds.right, bounds.bottom); 15433 if (invalidate) { 15434 invalidate(bounds); 15435 } 15436 } 15437 15438 if (drawVerticalScrollBar) { 15439 scrollBar.setParameters(computeVerticalScrollRange(), 15440 computeVerticalScrollOffset(), 15441 computeVerticalScrollExtent(), true); 15442 final Rect bounds = cache.mScrollBarBounds; 15443 getVerticalScrollBarBounds(bounds); 15444 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 15445 bounds.right, bounds.bottom); 15446 if (invalidate) { 15447 invalidate(bounds); 15448 } 15449 } 15450 } 15451 } 15452 } 15453 15454 /** 15455 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 15456 * FastScroller is visible. 15457 * @return whether to temporarily hide the vertical scrollbar 15458 * @hide 15459 */ 15460 protected boolean isVerticalScrollBarHidden() { 15461 return false; 15462 } 15463 15464 /** 15465 * <p>Draw the horizontal scrollbar if 15466 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 15467 * 15468 * @param canvas the canvas on which to draw the scrollbar 15469 * @param scrollBar the scrollbar's drawable 15470 * 15471 * @see #isHorizontalScrollBarEnabled() 15472 * @see #computeHorizontalScrollRange() 15473 * @see #computeHorizontalScrollExtent() 15474 * @see #computeHorizontalScrollOffset() 15475 * @see android.widget.ScrollBarDrawable 15476 * @hide 15477 */ 15478 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 15479 int l, int t, int r, int b) { 15480 scrollBar.setBounds(l, t, r, b); 15481 scrollBar.draw(canvas); 15482 } 15483 15484 /** 15485 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 15486 * returns true.</p> 15487 * 15488 * @param canvas the canvas on which to draw the scrollbar 15489 * @param scrollBar the scrollbar's drawable 15490 * 15491 * @see #isVerticalScrollBarEnabled() 15492 * @see #computeVerticalScrollRange() 15493 * @see #computeVerticalScrollExtent() 15494 * @see #computeVerticalScrollOffset() 15495 * @see android.widget.ScrollBarDrawable 15496 * @hide 15497 */ 15498 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 15499 int l, int t, int r, int b) { 15500 scrollBar.setBounds(l, t, r, b); 15501 scrollBar.draw(canvas); 15502 } 15503 15504 /** 15505 * Implement this to do your drawing. 15506 * 15507 * @param canvas the canvas on which the background will be drawn 15508 */ 15509 protected void onDraw(Canvas canvas) { 15510 } 15511 15512 /* 15513 * Caller is responsible for calling requestLayout if necessary. 15514 * (This allows addViewInLayout to not request a new layout.) 15515 */ 15516 void assignParent(ViewParent parent) { 15517 if (mParent == null) { 15518 mParent = parent; 15519 } else if (parent == null) { 15520 mParent = null; 15521 } else { 15522 throw new RuntimeException("view " + this + " being added, but" 15523 + " it already has a parent"); 15524 } 15525 } 15526 15527 /** 15528 * This is called when the view is attached to a window. At this point it 15529 * has a Surface and will start drawing. Note that this function is 15530 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 15531 * however it may be called any time before the first onDraw -- including 15532 * before or after {@link #onMeasure(int, int)}. 15533 * 15534 * @see #onDetachedFromWindow() 15535 */ 15536 @CallSuper 15537 protected void onAttachedToWindow() { 15538 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 15539 mParent.requestTransparentRegion(this); 15540 } 15541 15542 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15543 15544 jumpDrawablesToCurrentState(); 15545 15546 resetSubtreeAccessibilityStateChanged(); 15547 15548 // rebuild, since Outline not maintained while View is detached 15549 rebuildOutline(); 15550 15551 if (isFocused()) { 15552 InputMethodManager imm = InputMethodManager.peekInstance(); 15553 if (imm != null) { 15554 imm.focusIn(this); 15555 } 15556 } 15557 } 15558 15559 /** 15560 * Resolve all RTL related properties. 15561 * 15562 * @return true if resolution of RTL properties has been done 15563 * 15564 * @hide 15565 */ 15566 public boolean resolveRtlPropertiesIfNeeded() { 15567 if (!needRtlPropertiesResolution()) return false; 15568 15569 // Order is important here: LayoutDirection MUST be resolved first 15570 if (!isLayoutDirectionResolved()) { 15571 resolveLayoutDirection(); 15572 resolveLayoutParams(); 15573 } 15574 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 15575 if (!isTextDirectionResolved()) { 15576 resolveTextDirection(); 15577 } 15578 if (!isTextAlignmentResolved()) { 15579 resolveTextAlignment(); 15580 } 15581 // Should resolve Drawables before Padding because we need the layout direction of the 15582 // Drawable to correctly resolve Padding. 15583 if (!areDrawablesResolved()) { 15584 resolveDrawables(); 15585 } 15586 if (!isPaddingResolved()) { 15587 resolvePadding(); 15588 } 15589 onRtlPropertiesChanged(getLayoutDirection()); 15590 return true; 15591 } 15592 15593 /** 15594 * Reset resolution of all RTL related properties. 15595 * 15596 * @hide 15597 */ 15598 public void resetRtlProperties() { 15599 resetResolvedLayoutDirection(); 15600 resetResolvedTextDirection(); 15601 resetResolvedTextAlignment(); 15602 resetResolvedPadding(); 15603 resetResolvedDrawables(); 15604 } 15605 15606 /** 15607 * @see #onScreenStateChanged(int) 15608 */ 15609 void dispatchScreenStateChanged(int screenState) { 15610 onScreenStateChanged(screenState); 15611 } 15612 15613 /** 15614 * This method is called whenever the state of the screen this view is 15615 * attached to changes. A state change will usually occurs when the screen 15616 * turns on or off (whether it happens automatically or the user does it 15617 * manually.) 15618 * 15619 * @param screenState The new state of the screen. Can be either 15620 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 15621 */ 15622 public void onScreenStateChanged(int screenState) { 15623 } 15624 15625 /** 15626 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 15627 */ 15628 private boolean hasRtlSupport() { 15629 return mContext.getApplicationInfo().hasRtlSupport(); 15630 } 15631 15632 /** 15633 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 15634 * RTL not supported) 15635 */ 15636 private boolean isRtlCompatibilityMode() { 15637 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 15638 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 15639 } 15640 15641 /** 15642 * @return true if RTL properties need resolution. 15643 * 15644 */ 15645 private boolean needRtlPropertiesResolution() { 15646 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15647 } 15648 15649 /** 15650 * Called when any RTL property (layout direction or text direction or text alignment) has 15651 * been changed. 15652 * 15653 * Subclasses need to override this method to take care of cached information that depends on the 15654 * resolved layout direction, or to inform child views that inherit their layout direction. 15655 * 15656 * The default implementation does nothing. 15657 * 15658 * @param layoutDirection the direction of the layout 15659 * 15660 * @see #LAYOUT_DIRECTION_LTR 15661 * @see #LAYOUT_DIRECTION_RTL 15662 */ 15663 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15664 } 15665 15666 /** 15667 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15668 * that the parent directionality can and will be resolved before its children. 15669 * 15670 * @return true if resolution has been done, false otherwise. 15671 * 15672 * @hide 15673 */ 15674 public boolean resolveLayoutDirection() { 15675 // Clear any previous layout direction resolution 15676 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15677 15678 if (hasRtlSupport()) { 15679 // Set resolved depending on layout direction 15680 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15681 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15682 case LAYOUT_DIRECTION_INHERIT: 15683 // We cannot resolve yet. LTR is by default and let the resolution happen again 15684 // later to get the correct resolved value 15685 if (!canResolveLayoutDirection()) return false; 15686 15687 // Parent has not yet resolved, LTR is still the default 15688 try { 15689 if (!mParent.isLayoutDirectionResolved()) return false; 15690 15691 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15692 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15693 } 15694 } catch (AbstractMethodError e) { 15695 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15696 " does not fully implement ViewParent", e); 15697 } 15698 break; 15699 case LAYOUT_DIRECTION_RTL: 15700 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15701 break; 15702 case LAYOUT_DIRECTION_LOCALE: 15703 if((LAYOUT_DIRECTION_RTL == 15704 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15705 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15706 } 15707 break; 15708 default: 15709 // Nothing to do, LTR by default 15710 } 15711 } 15712 15713 // Set to resolved 15714 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15715 return true; 15716 } 15717 15718 /** 15719 * Check if layout direction resolution can be done. 15720 * 15721 * @return true if layout direction resolution can be done otherwise return false. 15722 */ 15723 public boolean canResolveLayoutDirection() { 15724 switch (getRawLayoutDirection()) { 15725 case LAYOUT_DIRECTION_INHERIT: 15726 if (mParent != null) { 15727 try { 15728 return mParent.canResolveLayoutDirection(); 15729 } catch (AbstractMethodError e) { 15730 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15731 " does not fully implement ViewParent", e); 15732 } 15733 } 15734 return false; 15735 15736 default: 15737 return true; 15738 } 15739 } 15740 15741 /** 15742 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15743 * {@link #onMeasure(int, int)}. 15744 * 15745 * @hide 15746 */ 15747 public void resetResolvedLayoutDirection() { 15748 // Reset the current resolved bits 15749 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15750 } 15751 15752 /** 15753 * @return true if the layout direction is inherited. 15754 * 15755 * @hide 15756 */ 15757 public boolean isLayoutDirectionInherited() { 15758 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15759 } 15760 15761 /** 15762 * @return true if layout direction has been resolved. 15763 */ 15764 public boolean isLayoutDirectionResolved() { 15765 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15766 } 15767 15768 /** 15769 * Return if padding has been resolved 15770 * 15771 * @hide 15772 */ 15773 boolean isPaddingResolved() { 15774 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15775 } 15776 15777 /** 15778 * Resolves padding depending on layout direction, if applicable, and 15779 * recomputes internal padding values to adjust for scroll bars. 15780 * 15781 * @hide 15782 */ 15783 public void resolvePadding() { 15784 final int resolvedLayoutDirection = getLayoutDirection(); 15785 15786 if (!isRtlCompatibilityMode()) { 15787 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15788 // If start / end padding are defined, they will be resolved (hence overriding) to 15789 // left / right or right / left depending on the resolved layout direction. 15790 // If start / end padding are not defined, use the left / right ones. 15791 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15792 Rect padding = sThreadLocal.get(); 15793 if (padding == null) { 15794 padding = new Rect(); 15795 sThreadLocal.set(padding); 15796 } 15797 mBackground.getPadding(padding); 15798 if (!mLeftPaddingDefined) { 15799 mUserPaddingLeftInitial = padding.left; 15800 } 15801 if (!mRightPaddingDefined) { 15802 mUserPaddingRightInitial = padding.right; 15803 } 15804 } 15805 switch (resolvedLayoutDirection) { 15806 case LAYOUT_DIRECTION_RTL: 15807 if (mUserPaddingStart != UNDEFINED_PADDING) { 15808 mUserPaddingRight = mUserPaddingStart; 15809 } else { 15810 mUserPaddingRight = mUserPaddingRightInitial; 15811 } 15812 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15813 mUserPaddingLeft = mUserPaddingEnd; 15814 } else { 15815 mUserPaddingLeft = mUserPaddingLeftInitial; 15816 } 15817 break; 15818 case LAYOUT_DIRECTION_LTR: 15819 default: 15820 if (mUserPaddingStart != UNDEFINED_PADDING) { 15821 mUserPaddingLeft = mUserPaddingStart; 15822 } else { 15823 mUserPaddingLeft = mUserPaddingLeftInitial; 15824 } 15825 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15826 mUserPaddingRight = mUserPaddingEnd; 15827 } else { 15828 mUserPaddingRight = mUserPaddingRightInitial; 15829 } 15830 } 15831 15832 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15833 } 15834 15835 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15836 onRtlPropertiesChanged(resolvedLayoutDirection); 15837 15838 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15839 } 15840 15841 /** 15842 * Reset the resolved layout direction. 15843 * 15844 * @hide 15845 */ 15846 public void resetResolvedPadding() { 15847 resetResolvedPaddingInternal(); 15848 } 15849 15850 /** 15851 * Used when we only want to reset *this* view's padding and not trigger overrides 15852 * in ViewGroup that reset children too. 15853 */ 15854 void resetResolvedPaddingInternal() { 15855 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15856 } 15857 15858 /** 15859 * This is called when the view is detached from a window. At this point it 15860 * no longer has a surface for drawing. 15861 * 15862 * @see #onAttachedToWindow() 15863 */ 15864 @CallSuper 15865 protected void onDetachedFromWindow() { 15866 } 15867 15868 /** 15869 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15870 * after onDetachedFromWindow(). 15871 * 15872 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15873 * The super method should be called at the end of the overridden method to ensure 15874 * subclasses are destroyed first 15875 * 15876 * @hide 15877 */ 15878 @CallSuper 15879 protected void onDetachedFromWindowInternal() { 15880 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15881 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15882 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15883 15884 removeUnsetPressCallback(); 15885 removeLongPressCallback(); 15886 removePerformClickCallback(); 15887 removeSendViewScrolledAccessibilityEventCallback(); 15888 stopNestedScroll(); 15889 15890 // Anything that started animating right before detach should already 15891 // be in its final state when re-attached. 15892 jumpDrawablesToCurrentState(); 15893 15894 destroyDrawingCache(); 15895 15896 cleanupDraw(); 15897 mCurrentAnimation = null; 15898 15899 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 15900 hideTooltip(); 15901 } 15902 } 15903 15904 private void cleanupDraw() { 15905 resetDisplayList(); 15906 if (mAttachInfo != null) { 15907 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15908 } 15909 } 15910 15911 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15912 } 15913 15914 /** 15915 * @return The number of times this view has been attached to a window 15916 */ 15917 protected int getWindowAttachCount() { 15918 return mWindowAttachCount; 15919 } 15920 15921 /** 15922 * Retrieve a unique token identifying the window this view is attached to. 15923 * @return Return the window's token for use in 15924 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15925 */ 15926 public IBinder getWindowToken() { 15927 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15928 } 15929 15930 /** 15931 * Retrieve the {@link WindowId} for the window this view is 15932 * currently attached to. 15933 */ 15934 public WindowId getWindowId() { 15935 if (mAttachInfo == null) { 15936 return null; 15937 } 15938 if (mAttachInfo.mWindowId == null) { 15939 try { 15940 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15941 mAttachInfo.mWindowToken); 15942 mAttachInfo.mWindowId = new WindowId( 15943 mAttachInfo.mIWindowId); 15944 } catch (RemoteException e) { 15945 } 15946 } 15947 return mAttachInfo.mWindowId; 15948 } 15949 15950 /** 15951 * Retrieve a unique token identifying the top-level "real" window of 15952 * the window that this view is attached to. That is, this is like 15953 * {@link #getWindowToken}, except if the window this view in is a panel 15954 * window (attached to another containing window), then the token of 15955 * the containing window is returned instead. 15956 * 15957 * @return Returns the associated window token, either 15958 * {@link #getWindowToken()} or the containing window's token. 15959 */ 15960 public IBinder getApplicationWindowToken() { 15961 AttachInfo ai = mAttachInfo; 15962 if (ai != null) { 15963 IBinder appWindowToken = ai.mPanelParentWindowToken; 15964 if (appWindowToken == null) { 15965 appWindowToken = ai.mWindowToken; 15966 } 15967 return appWindowToken; 15968 } 15969 return null; 15970 } 15971 15972 /** 15973 * Gets the logical display to which the view's window has been attached. 15974 * 15975 * @return The logical display, or null if the view is not currently attached to a window. 15976 */ 15977 public Display getDisplay() { 15978 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15979 } 15980 15981 /** 15982 * Retrieve private session object this view hierarchy is using to 15983 * communicate with the window manager. 15984 * @return the session object to communicate with the window manager 15985 */ 15986 /*package*/ IWindowSession getWindowSession() { 15987 return mAttachInfo != null ? mAttachInfo.mSession : null; 15988 } 15989 15990 /** 15991 * Return the visibility value of the least visible component passed. 15992 */ 15993 int combineVisibility(int vis1, int vis2) { 15994 // This works because VISIBLE < INVISIBLE < GONE. 15995 return Math.max(vis1, vis2); 15996 } 15997 15998 /** 15999 * @param info the {@link android.view.View.AttachInfo} to associated with 16000 * this view 16001 */ 16002 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 16003 mAttachInfo = info; 16004 if (mOverlay != null) { 16005 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 16006 } 16007 mWindowAttachCount++; 16008 // We will need to evaluate the drawable state at least once. 16009 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16010 if (mFloatingTreeObserver != null) { 16011 info.mTreeObserver.merge(mFloatingTreeObserver); 16012 mFloatingTreeObserver = null; 16013 } 16014 16015 registerPendingFrameMetricsObservers(); 16016 16017 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 16018 mAttachInfo.mScrollContainers.add(this); 16019 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 16020 } 16021 // Transfer all pending runnables. 16022 if (mRunQueue != null) { 16023 mRunQueue.executeActions(info.mHandler); 16024 mRunQueue = null; 16025 } 16026 performCollectViewAttributes(mAttachInfo, visibility); 16027 onAttachedToWindow(); 16028 16029 ListenerInfo li = mListenerInfo; 16030 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 16031 li != null ? li.mOnAttachStateChangeListeners : null; 16032 if (listeners != null && listeners.size() > 0) { 16033 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 16034 // perform the dispatching. The iterator is a safe guard against listeners that 16035 // could mutate the list by calling the various add/remove methods. This prevents 16036 // the array from being modified while we iterate it. 16037 for (OnAttachStateChangeListener listener : listeners) { 16038 listener.onViewAttachedToWindow(this); 16039 } 16040 } 16041 16042 int vis = info.mWindowVisibility; 16043 if (vis != GONE) { 16044 onWindowVisibilityChanged(vis); 16045 if (isShown()) { 16046 // Calling onVisibilityAggregated directly here since the subtree will also 16047 // receive dispatchAttachedToWindow and this same call 16048 onVisibilityAggregated(vis == VISIBLE); 16049 } 16050 } 16051 16052 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 16053 // As all views in the subtree will already receive dispatchAttachedToWindow 16054 // traversing the subtree again here is not desired. 16055 onVisibilityChanged(this, visibility); 16056 16057 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 16058 // If nobody has evaluated the drawable state yet, then do it now. 16059 refreshDrawableState(); 16060 } 16061 needGlobalAttributesUpdate(false); 16062 } 16063 16064 void dispatchDetachedFromWindow() { 16065 AttachInfo info = mAttachInfo; 16066 if (info != null) { 16067 int vis = info.mWindowVisibility; 16068 if (vis != GONE) { 16069 onWindowVisibilityChanged(GONE); 16070 if (isShown()) { 16071 // Invoking onVisibilityAggregated directly here since the subtree 16072 // will also receive detached from window 16073 onVisibilityAggregated(false); 16074 } 16075 } 16076 } 16077 16078 onDetachedFromWindow(); 16079 onDetachedFromWindowInternal(); 16080 16081 InputMethodManager imm = InputMethodManager.peekInstance(); 16082 if (imm != null) { 16083 imm.onViewDetachedFromWindow(this); 16084 } 16085 16086 ListenerInfo li = mListenerInfo; 16087 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 16088 li != null ? li.mOnAttachStateChangeListeners : null; 16089 if (listeners != null && listeners.size() > 0) { 16090 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 16091 // perform the dispatching. The iterator is a safe guard against listeners that 16092 // could mutate the list by calling the various add/remove methods. This prevents 16093 // the array from being modified while we iterate it. 16094 for (OnAttachStateChangeListener listener : listeners) { 16095 listener.onViewDetachedFromWindow(this); 16096 } 16097 } 16098 16099 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 16100 mAttachInfo.mScrollContainers.remove(this); 16101 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 16102 } 16103 16104 mAttachInfo = null; 16105 if (mOverlay != null) { 16106 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 16107 } 16108 } 16109 16110 /** 16111 * Cancel any deferred high-level input events that were previously posted to the event queue. 16112 * 16113 * <p>Many views post high-level events such as click handlers to the event queue 16114 * to run deferred in order to preserve a desired user experience - clearing visible 16115 * pressed states before executing, etc. This method will abort any events of this nature 16116 * that are currently in flight.</p> 16117 * 16118 * <p>Custom views that generate their own high-level deferred input events should override 16119 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 16120 * 16121 * <p>This will also cancel pending input events for any child views.</p> 16122 * 16123 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 16124 * This will not impact newer events posted after this call that may occur as a result of 16125 * lower-level input events still waiting in the queue. If you are trying to prevent 16126 * double-submitted events for the duration of some sort of asynchronous transaction 16127 * you should also take other steps to protect against unexpected double inputs e.g. calling 16128 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 16129 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 16130 */ 16131 public final void cancelPendingInputEvents() { 16132 dispatchCancelPendingInputEvents(); 16133 } 16134 16135 /** 16136 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 16137 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 16138 */ 16139 void dispatchCancelPendingInputEvents() { 16140 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 16141 onCancelPendingInputEvents(); 16142 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 16143 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 16144 " did not call through to super.onCancelPendingInputEvents()"); 16145 } 16146 } 16147 16148 /** 16149 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 16150 * a parent view. 16151 * 16152 * <p>This method is responsible for removing any pending high-level input events that were 16153 * posted to the event queue to run later. Custom view classes that post their own deferred 16154 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 16155 * {@link android.os.Handler} should override this method, call 16156 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 16157 * </p> 16158 */ 16159 public void onCancelPendingInputEvents() { 16160 removePerformClickCallback(); 16161 cancelLongPress(); 16162 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 16163 } 16164 16165 /** 16166 * Store this view hierarchy's frozen state into the given container. 16167 * 16168 * @param container The SparseArray in which to save the view's state. 16169 * 16170 * @see #restoreHierarchyState(android.util.SparseArray) 16171 * @see #dispatchSaveInstanceState(android.util.SparseArray) 16172 * @see #onSaveInstanceState() 16173 */ 16174 public void saveHierarchyState(SparseArray<Parcelable> container) { 16175 dispatchSaveInstanceState(container); 16176 } 16177 16178 /** 16179 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 16180 * this view and its children. May be overridden to modify how freezing happens to a 16181 * view's children; for example, some views may want to not store state for their children. 16182 * 16183 * @param container The SparseArray in which to save the view's state. 16184 * 16185 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 16186 * @see #saveHierarchyState(android.util.SparseArray) 16187 * @see #onSaveInstanceState() 16188 */ 16189 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 16190 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 16191 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 16192 Parcelable state = onSaveInstanceState(); 16193 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 16194 throw new IllegalStateException( 16195 "Derived class did not call super.onSaveInstanceState()"); 16196 } 16197 if (state != null) { 16198 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 16199 // + ": " + state); 16200 container.put(mID, state); 16201 } 16202 } 16203 } 16204 16205 /** 16206 * Hook allowing a view to generate a representation of its internal state 16207 * that can later be used to create a new instance with that same state. 16208 * This state should only contain information that is not persistent or can 16209 * not be reconstructed later. For example, you will never store your 16210 * current position on screen because that will be computed again when a 16211 * new instance of the view is placed in its view hierarchy. 16212 * <p> 16213 * Some examples of things you may store here: the current cursor position 16214 * in a text view (but usually not the text itself since that is stored in a 16215 * content provider or other persistent storage), the currently selected 16216 * item in a list view. 16217 * 16218 * @return Returns a Parcelable object containing the view's current dynamic 16219 * state, or null if there is nothing interesting to save. The 16220 * default implementation returns null. 16221 * @see #onRestoreInstanceState(android.os.Parcelable) 16222 * @see #saveHierarchyState(android.util.SparseArray) 16223 * @see #dispatchSaveInstanceState(android.util.SparseArray) 16224 * @see #setSaveEnabled(boolean) 16225 */ 16226 @CallSuper 16227 protected Parcelable onSaveInstanceState() { 16228 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 16229 if (mStartActivityRequestWho != null) { 16230 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 16231 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 16232 return state; 16233 } 16234 return BaseSavedState.EMPTY_STATE; 16235 } 16236 16237 /** 16238 * Restore this view hierarchy's frozen state from the given container. 16239 * 16240 * @param container The SparseArray which holds previously frozen states. 16241 * 16242 * @see #saveHierarchyState(android.util.SparseArray) 16243 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 16244 * @see #onRestoreInstanceState(android.os.Parcelable) 16245 */ 16246 public void restoreHierarchyState(SparseArray<Parcelable> container) { 16247 dispatchRestoreInstanceState(container); 16248 } 16249 16250 /** 16251 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 16252 * state for this view and its children. May be overridden to modify how restoring 16253 * happens to a view's children; for example, some views may want to not store state 16254 * for their children. 16255 * 16256 * @param container The SparseArray which holds previously saved state. 16257 * 16258 * @see #dispatchSaveInstanceState(android.util.SparseArray) 16259 * @see #restoreHierarchyState(android.util.SparseArray) 16260 * @see #onRestoreInstanceState(android.os.Parcelable) 16261 */ 16262 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 16263 if (mID != NO_ID) { 16264 Parcelable state = container.get(mID); 16265 if (state != null) { 16266 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 16267 // + ": " + state); 16268 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 16269 onRestoreInstanceState(state); 16270 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 16271 throw new IllegalStateException( 16272 "Derived class did not call super.onRestoreInstanceState()"); 16273 } 16274 } 16275 } 16276 } 16277 16278 /** 16279 * Hook allowing a view to re-apply a representation of its internal state that had previously 16280 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 16281 * null state. 16282 * 16283 * @param state The frozen state that had previously been returned by 16284 * {@link #onSaveInstanceState}. 16285 * 16286 * @see #onSaveInstanceState() 16287 * @see #restoreHierarchyState(android.util.SparseArray) 16288 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 16289 */ 16290 @CallSuper 16291 protected void onRestoreInstanceState(Parcelable state) { 16292 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 16293 if (state != null && !(state instanceof AbsSavedState)) { 16294 throw new IllegalArgumentException("Wrong state class, expecting View State but " 16295 + "received " + state.getClass().toString() + " instead. This usually happens " 16296 + "when two views of different type have the same id in the same hierarchy. " 16297 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 16298 + "other views do not use the same id."); 16299 } 16300 if (state != null && state instanceof BaseSavedState) { 16301 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 16302 } 16303 } 16304 16305 /** 16306 * <p>Return the time at which the drawing of the view hierarchy started.</p> 16307 * 16308 * @return the drawing start time in milliseconds 16309 */ 16310 public long getDrawingTime() { 16311 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 16312 } 16313 16314 /** 16315 * <p>Enables or disables the duplication of the parent's state into this view. When 16316 * duplication is enabled, this view gets its drawable state from its parent rather 16317 * than from its own internal properties.</p> 16318 * 16319 * <p>Note: in the current implementation, setting this property to true after the 16320 * view was added to a ViewGroup might have no effect at all. This property should 16321 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 16322 * 16323 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 16324 * property is enabled, an exception will be thrown.</p> 16325 * 16326 * <p>Note: if the child view uses and updates additional states which are unknown to the 16327 * parent, these states should not be affected by this method.</p> 16328 * 16329 * @param enabled True to enable duplication of the parent's drawable state, false 16330 * to disable it. 16331 * 16332 * @see #getDrawableState() 16333 * @see #isDuplicateParentStateEnabled() 16334 */ 16335 public void setDuplicateParentStateEnabled(boolean enabled) { 16336 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 16337 } 16338 16339 /** 16340 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 16341 * 16342 * @return True if this view's drawable state is duplicated from the parent, 16343 * false otherwise 16344 * 16345 * @see #getDrawableState() 16346 * @see #setDuplicateParentStateEnabled(boolean) 16347 */ 16348 public boolean isDuplicateParentStateEnabled() { 16349 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 16350 } 16351 16352 /** 16353 * <p>Specifies the type of layer backing this view. The layer can be 16354 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 16355 * {@link #LAYER_TYPE_HARDWARE}.</p> 16356 * 16357 * <p>A layer is associated with an optional {@link android.graphics.Paint} 16358 * instance that controls how the layer is composed on screen. The following 16359 * properties of the paint are taken into account when composing the layer:</p> 16360 * <ul> 16361 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 16362 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 16363 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 16364 * </ul> 16365 * 16366 * <p>If this view has an alpha value set to < 1.0 by calling 16367 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 16368 * by this view's alpha value.</p> 16369 * 16370 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 16371 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 16372 * for more information on when and how to use layers.</p> 16373 * 16374 * @param layerType The type of layer to use with this view, must be one of 16375 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 16376 * {@link #LAYER_TYPE_HARDWARE} 16377 * @param paint The paint used to compose the layer. This argument is optional 16378 * and can be null. It is ignored when the layer type is 16379 * {@link #LAYER_TYPE_NONE} 16380 * 16381 * @see #getLayerType() 16382 * @see #LAYER_TYPE_NONE 16383 * @see #LAYER_TYPE_SOFTWARE 16384 * @see #LAYER_TYPE_HARDWARE 16385 * @see #setAlpha(float) 16386 * 16387 * @attr ref android.R.styleable#View_layerType 16388 */ 16389 public void setLayerType(int layerType, @Nullable Paint paint) { 16390 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 16391 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 16392 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 16393 } 16394 16395 boolean typeChanged = mRenderNode.setLayerType(layerType); 16396 16397 if (!typeChanged) { 16398 setLayerPaint(paint); 16399 return; 16400 } 16401 16402 if (layerType != LAYER_TYPE_SOFTWARE) { 16403 // Destroy any previous software drawing cache if present 16404 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 16405 // drawing cache created in View#draw when drawing to a SW canvas. 16406 destroyDrawingCache(); 16407 } 16408 16409 mLayerType = layerType; 16410 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 16411 mRenderNode.setLayerPaint(mLayerPaint); 16412 16413 // draw() behaves differently if we are on a layer, so we need to 16414 // invalidate() here 16415 invalidateParentCaches(); 16416 invalidate(true); 16417 } 16418 16419 /** 16420 * Updates the {@link Paint} object used with the current layer (used only if the current 16421 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 16422 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 16423 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 16424 * ensure that the view gets redrawn immediately. 16425 * 16426 * <p>A layer is associated with an optional {@link android.graphics.Paint} 16427 * instance that controls how the layer is composed on screen. The following 16428 * properties of the paint are taken into account when composing the layer:</p> 16429 * <ul> 16430 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 16431 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 16432 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 16433 * </ul> 16434 * 16435 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 16436 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 16437 * 16438 * @param paint The paint used to compose the layer. This argument is optional 16439 * and can be null. It is ignored when the layer type is 16440 * {@link #LAYER_TYPE_NONE} 16441 * 16442 * @see #setLayerType(int, android.graphics.Paint) 16443 */ 16444 public void setLayerPaint(@Nullable Paint paint) { 16445 int layerType = getLayerType(); 16446 if (layerType != LAYER_TYPE_NONE) { 16447 mLayerPaint = paint; 16448 if (layerType == LAYER_TYPE_HARDWARE) { 16449 if (mRenderNode.setLayerPaint(paint)) { 16450 invalidateViewProperty(false, false); 16451 } 16452 } else { 16453 invalidate(); 16454 } 16455 } 16456 } 16457 16458 /** 16459 * Indicates what type of layer is currently associated with this view. By default 16460 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 16461 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 16462 * for more information on the different types of layers. 16463 * 16464 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 16465 * {@link #LAYER_TYPE_HARDWARE} 16466 * 16467 * @see #setLayerType(int, android.graphics.Paint) 16468 * @see #buildLayer() 16469 * @see #LAYER_TYPE_NONE 16470 * @see #LAYER_TYPE_SOFTWARE 16471 * @see #LAYER_TYPE_HARDWARE 16472 */ 16473 public int getLayerType() { 16474 return mLayerType; 16475 } 16476 16477 /** 16478 * Forces this view's layer to be created and this view to be rendered 16479 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 16480 * invoking this method will have no effect. 16481 * 16482 * This method can for instance be used to render a view into its layer before 16483 * starting an animation. If this view is complex, rendering into the layer 16484 * before starting the animation will avoid skipping frames. 16485 * 16486 * @throws IllegalStateException If this view is not attached to a window 16487 * 16488 * @see #setLayerType(int, android.graphics.Paint) 16489 */ 16490 public void buildLayer() { 16491 if (mLayerType == LAYER_TYPE_NONE) return; 16492 16493 final AttachInfo attachInfo = mAttachInfo; 16494 if (attachInfo == null) { 16495 throw new IllegalStateException("This view must be attached to a window first"); 16496 } 16497 16498 if (getWidth() == 0 || getHeight() == 0) { 16499 return; 16500 } 16501 16502 switch (mLayerType) { 16503 case LAYER_TYPE_HARDWARE: 16504 updateDisplayListIfDirty(); 16505 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 16506 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 16507 } 16508 break; 16509 case LAYER_TYPE_SOFTWARE: 16510 buildDrawingCache(true); 16511 break; 16512 } 16513 } 16514 16515 /** 16516 * Destroys all hardware rendering resources. This method is invoked 16517 * when the system needs to reclaim resources. Upon execution of this 16518 * method, you should free any OpenGL resources created by the view. 16519 * 16520 * Note: you <strong>must</strong> call 16521 * <code>super.destroyHardwareResources()</code> when overriding 16522 * this method. 16523 * 16524 * @hide 16525 */ 16526 @CallSuper 16527 protected void destroyHardwareResources() { 16528 // Although the Layer will be destroyed by RenderNode, we want to release 16529 // the staging display list, which is also a signal to RenderNode that it's 16530 // safe to free its copy of the display list as it knows that we will 16531 // push an updated DisplayList if we try to draw again 16532 resetDisplayList(); 16533 if (mOverlay != null) { 16534 mOverlay.getOverlayView().destroyHardwareResources(); 16535 } 16536 if (mGhostView != null) { 16537 mGhostView.destroyHardwareResources(); 16538 } 16539 } 16540 16541 /** 16542 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 16543 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 16544 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 16545 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 16546 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 16547 * null.</p> 16548 * 16549 * <p>Enabling the drawing cache is similar to 16550 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 16551 * acceleration is turned off. When hardware acceleration is turned on, enabling the 16552 * drawing cache has no effect on rendering because the system uses a different mechanism 16553 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 16554 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 16555 * for information on how to enable software and hardware layers.</p> 16556 * 16557 * <p>This API can be used to manually generate 16558 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 16559 * {@link #getDrawingCache()}.</p> 16560 * 16561 * @param enabled true to enable the drawing cache, false otherwise 16562 * 16563 * @see #isDrawingCacheEnabled() 16564 * @see #getDrawingCache() 16565 * @see #buildDrawingCache() 16566 * @see #setLayerType(int, android.graphics.Paint) 16567 */ 16568 public void setDrawingCacheEnabled(boolean enabled) { 16569 mCachingFailed = false; 16570 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 16571 } 16572 16573 /** 16574 * <p>Indicates whether the drawing cache is enabled for this view.</p> 16575 * 16576 * @return true if the drawing cache is enabled 16577 * 16578 * @see #setDrawingCacheEnabled(boolean) 16579 * @see #getDrawingCache() 16580 */ 16581 @ViewDebug.ExportedProperty(category = "drawing") 16582 public boolean isDrawingCacheEnabled() { 16583 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 16584 } 16585 16586 /** 16587 * Debugging utility which recursively outputs the dirty state of a view and its 16588 * descendants. 16589 * 16590 * @hide 16591 */ 16592 @SuppressWarnings({"UnusedDeclaration"}) 16593 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 16594 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 16595 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 16596 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 16597 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 16598 if (clear) { 16599 mPrivateFlags &= clearMask; 16600 } 16601 if (this instanceof ViewGroup) { 16602 ViewGroup parent = (ViewGroup) this; 16603 final int count = parent.getChildCount(); 16604 for (int i = 0; i < count; i++) { 16605 final View child = parent.getChildAt(i); 16606 child.outputDirtyFlags(indent + " ", clear, clearMask); 16607 } 16608 } 16609 } 16610 16611 /** 16612 * This method is used by ViewGroup to cause its children to restore or recreate their 16613 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 16614 * to recreate its own display list, which would happen if it went through the normal 16615 * draw/dispatchDraw mechanisms. 16616 * 16617 * @hide 16618 */ 16619 protected void dispatchGetDisplayList() {} 16620 16621 /** 16622 * A view that is not attached or hardware accelerated cannot create a display list. 16623 * This method checks these conditions and returns the appropriate result. 16624 * 16625 * @return true if view has the ability to create a display list, false otherwise. 16626 * 16627 * @hide 16628 */ 16629 public boolean canHaveDisplayList() { 16630 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 16631 } 16632 16633 /** 16634 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 16635 * @hide 16636 */ 16637 @NonNull 16638 public RenderNode updateDisplayListIfDirty() { 16639 final RenderNode renderNode = mRenderNode; 16640 if (!canHaveDisplayList()) { 16641 // can't populate RenderNode, don't try 16642 return renderNode; 16643 } 16644 16645 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 16646 || !renderNode.isValid() 16647 || (mRecreateDisplayList)) { 16648 // Don't need to recreate the display list, just need to tell our 16649 // children to restore/recreate theirs 16650 if (renderNode.isValid() 16651 && !mRecreateDisplayList) { 16652 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16653 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16654 dispatchGetDisplayList(); 16655 16656 return renderNode; // no work needed 16657 } 16658 16659 // If we got here, we're recreating it. Mark it as such to ensure that 16660 // we copy in child display lists into ours in drawChild() 16661 mRecreateDisplayList = true; 16662 16663 int width = mRight - mLeft; 16664 int height = mBottom - mTop; 16665 int layerType = getLayerType(); 16666 16667 final DisplayListCanvas canvas = renderNode.start(width, height); 16668 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16669 16670 try { 16671 if (layerType == LAYER_TYPE_SOFTWARE) { 16672 buildDrawingCache(true); 16673 Bitmap cache = getDrawingCache(true); 16674 if (cache != null) { 16675 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16676 } 16677 } else { 16678 computeScroll(); 16679 16680 canvas.translate(-mScrollX, -mScrollY); 16681 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16682 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16683 16684 // Fast path for layouts with no backgrounds 16685 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16686 dispatchDraw(canvas); 16687 if (mOverlay != null && !mOverlay.isEmpty()) { 16688 mOverlay.getOverlayView().draw(canvas); 16689 } 16690 if (debugDraw()) { 16691 debugDrawFocus(canvas); 16692 } 16693 } else { 16694 draw(canvas); 16695 } 16696 } 16697 } finally { 16698 renderNode.end(canvas); 16699 setDisplayListProperties(renderNode); 16700 } 16701 } else { 16702 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16703 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16704 } 16705 return renderNode; 16706 } 16707 16708 private void resetDisplayList() { 16709 mRenderNode.discardDisplayList(); 16710 16711 if (mBackgroundRenderNode != null) { 16712 mBackgroundRenderNode.discardDisplayList(); 16713 } 16714 } 16715 16716 /** 16717 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16718 * 16719 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16720 * 16721 * @see #getDrawingCache(boolean) 16722 */ 16723 public Bitmap getDrawingCache() { 16724 return getDrawingCache(false); 16725 } 16726 16727 /** 16728 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16729 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16730 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16731 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16732 * request the drawing cache by calling this method and draw it on screen if the 16733 * returned bitmap is not null.</p> 16734 * 16735 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16736 * this method will create a bitmap of the same size as this view. Because this bitmap 16737 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16738 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16739 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16740 * size than the view. This implies that your application must be able to handle this 16741 * size.</p> 16742 * 16743 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16744 * the current density of the screen when the application is in compatibility 16745 * mode. 16746 * 16747 * @return A bitmap representing this view or null if cache is disabled. 16748 * 16749 * @see #setDrawingCacheEnabled(boolean) 16750 * @see #isDrawingCacheEnabled() 16751 * @see #buildDrawingCache(boolean) 16752 * @see #destroyDrawingCache() 16753 */ 16754 public Bitmap getDrawingCache(boolean autoScale) { 16755 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16756 return null; 16757 } 16758 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16759 buildDrawingCache(autoScale); 16760 } 16761 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16762 } 16763 16764 /** 16765 * <p>Frees the resources used by the drawing cache. If you call 16766 * {@link #buildDrawingCache()} manually without calling 16767 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16768 * should cleanup the cache with this method afterwards.</p> 16769 * 16770 * @see #setDrawingCacheEnabled(boolean) 16771 * @see #buildDrawingCache() 16772 * @see #getDrawingCache() 16773 */ 16774 public void destroyDrawingCache() { 16775 if (mDrawingCache != null) { 16776 mDrawingCache.recycle(); 16777 mDrawingCache = null; 16778 } 16779 if (mUnscaledDrawingCache != null) { 16780 mUnscaledDrawingCache.recycle(); 16781 mUnscaledDrawingCache = null; 16782 } 16783 } 16784 16785 /** 16786 * Setting a solid background color for the drawing cache's bitmaps will improve 16787 * performance and memory usage. Note, though that this should only be used if this 16788 * view will always be drawn on top of a solid color. 16789 * 16790 * @param color The background color to use for the drawing cache's bitmap 16791 * 16792 * @see #setDrawingCacheEnabled(boolean) 16793 * @see #buildDrawingCache() 16794 * @see #getDrawingCache() 16795 */ 16796 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16797 if (color != mDrawingCacheBackgroundColor) { 16798 mDrawingCacheBackgroundColor = color; 16799 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16800 } 16801 } 16802 16803 /** 16804 * @see #setDrawingCacheBackgroundColor(int) 16805 * 16806 * @return The background color to used for the drawing cache's bitmap 16807 */ 16808 @ColorInt 16809 public int getDrawingCacheBackgroundColor() { 16810 return mDrawingCacheBackgroundColor; 16811 } 16812 16813 /** 16814 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16815 * 16816 * @see #buildDrawingCache(boolean) 16817 */ 16818 public void buildDrawingCache() { 16819 buildDrawingCache(false); 16820 } 16821 16822 /** 16823 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16824 * 16825 * <p>If you call {@link #buildDrawingCache()} manually without calling 16826 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16827 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16828 * 16829 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16830 * this method will create a bitmap of the same size as this view. Because this bitmap 16831 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16832 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16833 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16834 * size than the view. This implies that your application must be able to handle this 16835 * size.</p> 16836 * 16837 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16838 * you do not need the drawing cache bitmap, calling this method will increase memory 16839 * usage and cause the view to be rendered in software once, thus negatively impacting 16840 * performance.</p> 16841 * 16842 * @see #getDrawingCache() 16843 * @see #destroyDrawingCache() 16844 */ 16845 public void buildDrawingCache(boolean autoScale) { 16846 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16847 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16848 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16849 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16850 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16851 } 16852 try { 16853 buildDrawingCacheImpl(autoScale); 16854 } finally { 16855 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16856 } 16857 } 16858 } 16859 16860 /** 16861 * private, internal implementation of buildDrawingCache, used to enable tracing 16862 */ 16863 private void buildDrawingCacheImpl(boolean autoScale) { 16864 mCachingFailed = false; 16865 16866 int width = mRight - mLeft; 16867 int height = mBottom - mTop; 16868 16869 final AttachInfo attachInfo = mAttachInfo; 16870 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16871 16872 if (autoScale && scalingRequired) { 16873 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16874 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16875 } 16876 16877 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16878 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16879 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16880 16881 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16882 final long drawingCacheSize = 16883 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16884 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16885 if (width > 0 && height > 0) { 16886 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16887 + " too large to fit into a software layer (or drawing cache), needs " 16888 + projectedBitmapSize + " bytes, only " 16889 + drawingCacheSize + " available"); 16890 } 16891 destroyDrawingCache(); 16892 mCachingFailed = true; 16893 return; 16894 } 16895 16896 boolean clear = true; 16897 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16898 16899 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16900 Bitmap.Config quality; 16901 if (!opaque) { 16902 // Never pick ARGB_4444 because it looks awful 16903 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16904 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16905 case DRAWING_CACHE_QUALITY_AUTO: 16906 case DRAWING_CACHE_QUALITY_LOW: 16907 case DRAWING_CACHE_QUALITY_HIGH: 16908 default: 16909 quality = Bitmap.Config.ARGB_8888; 16910 break; 16911 } 16912 } else { 16913 // Optimization for translucent windows 16914 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16915 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16916 } 16917 16918 // Try to cleanup memory 16919 if (bitmap != null) bitmap.recycle(); 16920 16921 try { 16922 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16923 width, height, quality); 16924 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16925 if (autoScale) { 16926 mDrawingCache = bitmap; 16927 } else { 16928 mUnscaledDrawingCache = bitmap; 16929 } 16930 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16931 } catch (OutOfMemoryError e) { 16932 // If there is not enough memory to create the bitmap cache, just 16933 // ignore the issue as bitmap caches are not required to draw the 16934 // view hierarchy 16935 if (autoScale) { 16936 mDrawingCache = null; 16937 } else { 16938 mUnscaledDrawingCache = null; 16939 } 16940 mCachingFailed = true; 16941 return; 16942 } 16943 16944 clear = drawingCacheBackgroundColor != 0; 16945 } 16946 16947 Canvas canvas; 16948 if (attachInfo != null) { 16949 canvas = attachInfo.mCanvas; 16950 if (canvas == null) { 16951 canvas = new Canvas(); 16952 } 16953 canvas.setBitmap(bitmap); 16954 // Temporarily clobber the cached Canvas in case one of our children 16955 // is also using a drawing cache. Without this, the children would 16956 // steal the canvas by attaching their own bitmap to it and bad, bad 16957 // thing would happen (invisible views, corrupted drawings, etc.) 16958 attachInfo.mCanvas = null; 16959 } else { 16960 // This case should hopefully never or seldom happen 16961 canvas = new Canvas(bitmap); 16962 } 16963 16964 if (clear) { 16965 bitmap.eraseColor(drawingCacheBackgroundColor); 16966 } 16967 16968 computeScroll(); 16969 final int restoreCount = canvas.save(); 16970 16971 if (autoScale && scalingRequired) { 16972 final float scale = attachInfo.mApplicationScale; 16973 canvas.scale(scale, scale); 16974 } 16975 16976 canvas.translate(-mScrollX, -mScrollY); 16977 16978 mPrivateFlags |= PFLAG_DRAWN; 16979 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16980 mLayerType != LAYER_TYPE_NONE) { 16981 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16982 } 16983 16984 // Fast path for layouts with no backgrounds 16985 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16986 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16987 dispatchDraw(canvas); 16988 if (mOverlay != null && !mOverlay.isEmpty()) { 16989 mOverlay.getOverlayView().draw(canvas); 16990 } 16991 } else { 16992 draw(canvas); 16993 } 16994 16995 canvas.restoreToCount(restoreCount); 16996 canvas.setBitmap(null); 16997 16998 if (attachInfo != null) { 16999 // Restore the cached Canvas for our siblings 17000 attachInfo.mCanvas = canvas; 17001 } 17002 } 17003 17004 /** 17005 * Create a snapshot of the view into a bitmap. We should probably make 17006 * some form of this public, but should think about the API. 17007 * 17008 * @hide 17009 */ 17010 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 17011 int width = mRight - mLeft; 17012 int height = mBottom - mTop; 17013 17014 final AttachInfo attachInfo = mAttachInfo; 17015 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 17016 width = (int) ((width * scale) + 0.5f); 17017 height = (int) ((height * scale) + 0.5f); 17018 17019 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 17020 width > 0 ? width : 1, height > 0 ? height : 1, quality); 17021 if (bitmap == null) { 17022 throw new OutOfMemoryError(); 17023 } 17024 17025 Resources resources = getResources(); 17026 if (resources != null) { 17027 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 17028 } 17029 17030 Canvas canvas; 17031 if (attachInfo != null) { 17032 canvas = attachInfo.mCanvas; 17033 if (canvas == null) { 17034 canvas = new Canvas(); 17035 } 17036 canvas.setBitmap(bitmap); 17037 // Temporarily clobber the cached Canvas in case one of our children 17038 // is also using a drawing cache. Without this, the children would 17039 // steal the canvas by attaching their own bitmap to it and bad, bad 17040 // things would happen (invisible views, corrupted drawings, etc.) 17041 attachInfo.mCanvas = null; 17042 } else { 17043 // This case should hopefully never or seldom happen 17044 canvas = new Canvas(bitmap); 17045 } 17046 17047 if ((backgroundColor & 0xff000000) != 0) { 17048 bitmap.eraseColor(backgroundColor); 17049 } 17050 17051 computeScroll(); 17052 final int restoreCount = canvas.save(); 17053 canvas.scale(scale, scale); 17054 canvas.translate(-mScrollX, -mScrollY); 17055 17056 // Temporarily remove the dirty mask 17057 int flags = mPrivateFlags; 17058 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17059 17060 // Fast path for layouts with no backgrounds 17061 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17062 dispatchDraw(canvas); 17063 if (mOverlay != null && !mOverlay.isEmpty()) { 17064 mOverlay.getOverlayView().draw(canvas); 17065 } 17066 } else { 17067 draw(canvas); 17068 } 17069 17070 mPrivateFlags = flags; 17071 17072 canvas.restoreToCount(restoreCount); 17073 canvas.setBitmap(null); 17074 17075 if (attachInfo != null) { 17076 // Restore the cached Canvas for our siblings 17077 attachInfo.mCanvas = canvas; 17078 } 17079 17080 return bitmap; 17081 } 17082 17083 /** 17084 * Indicates whether this View is currently in edit mode. A View is usually 17085 * in edit mode when displayed within a developer tool. For instance, if 17086 * this View is being drawn by a visual user interface builder, this method 17087 * should return true. 17088 * 17089 * Subclasses should check the return value of this method to provide 17090 * different behaviors if their normal behavior might interfere with the 17091 * host environment. For instance: the class spawns a thread in its 17092 * constructor, the drawing code relies on device-specific features, etc. 17093 * 17094 * This method is usually checked in the drawing code of custom widgets. 17095 * 17096 * @return True if this View is in edit mode, false otherwise. 17097 */ 17098 public boolean isInEditMode() { 17099 return false; 17100 } 17101 17102 /** 17103 * If the View draws content inside its padding and enables fading edges, 17104 * it needs to support padding offsets. Padding offsets are added to the 17105 * fading edges to extend the length of the fade so that it covers pixels 17106 * drawn inside the padding. 17107 * 17108 * Subclasses of this class should override this method if they need 17109 * to draw content inside the padding. 17110 * 17111 * @return True if padding offset must be applied, false otherwise. 17112 * 17113 * @see #getLeftPaddingOffset() 17114 * @see #getRightPaddingOffset() 17115 * @see #getTopPaddingOffset() 17116 * @see #getBottomPaddingOffset() 17117 * 17118 * @since CURRENT 17119 */ 17120 protected boolean isPaddingOffsetRequired() { 17121 return false; 17122 } 17123 17124 /** 17125 * Amount by which to extend the left fading region. Called only when 17126 * {@link #isPaddingOffsetRequired()} returns true. 17127 * 17128 * @return The left padding offset in pixels. 17129 * 17130 * @see #isPaddingOffsetRequired() 17131 * 17132 * @since CURRENT 17133 */ 17134 protected int getLeftPaddingOffset() { 17135 return 0; 17136 } 17137 17138 /** 17139 * Amount by which to extend the right fading region. Called only when 17140 * {@link #isPaddingOffsetRequired()} returns true. 17141 * 17142 * @return The right padding offset in pixels. 17143 * 17144 * @see #isPaddingOffsetRequired() 17145 * 17146 * @since CURRENT 17147 */ 17148 protected int getRightPaddingOffset() { 17149 return 0; 17150 } 17151 17152 /** 17153 * Amount by which to extend the top fading region. Called only when 17154 * {@link #isPaddingOffsetRequired()} returns true. 17155 * 17156 * @return The top padding offset in pixels. 17157 * 17158 * @see #isPaddingOffsetRequired() 17159 * 17160 * @since CURRENT 17161 */ 17162 protected int getTopPaddingOffset() { 17163 return 0; 17164 } 17165 17166 /** 17167 * Amount by which to extend the bottom fading region. Called only when 17168 * {@link #isPaddingOffsetRequired()} returns true. 17169 * 17170 * @return The bottom padding offset in pixels. 17171 * 17172 * @see #isPaddingOffsetRequired() 17173 * 17174 * @since CURRENT 17175 */ 17176 protected int getBottomPaddingOffset() { 17177 return 0; 17178 } 17179 17180 /** 17181 * @hide 17182 * @param offsetRequired 17183 */ 17184 protected int getFadeTop(boolean offsetRequired) { 17185 int top = mPaddingTop; 17186 if (offsetRequired) top += getTopPaddingOffset(); 17187 return top; 17188 } 17189 17190 /** 17191 * @hide 17192 * @param offsetRequired 17193 */ 17194 protected int getFadeHeight(boolean offsetRequired) { 17195 int padding = mPaddingTop; 17196 if (offsetRequired) padding += getTopPaddingOffset(); 17197 return mBottom - mTop - mPaddingBottom - padding; 17198 } 17199 17200 /** 17201 * <p>Indicates whether this view is attached to a hardware accelerated 17202 * window or not.</p> 17203 * 17204 * <p>Even if this method returns true, it does not mean that every call 17205 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 17206 * accelerated {@link android.graphics.Canvas}. For instance, if this view 17207 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 17208 * window is hardware accelerated, 17209 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 17210 * return false, and this method will return true.</p> 17211 * 17212 * @return True if the view is attached to a window and the window is 17213 * hardware accelerated; false in any other case. 17214 */ 17215 @ViewDebug.ExportedProperty(category = "drawing") 17216 public boolean isHardwareAccelerated() { 17217 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 17218 } 17219 17220 /** 17221 * Sets a rectangular area on this view to which the view will be clipped 17222 * when it is drawn. Setting the value to null will remove the clip bounds 17223 * and the view will draw normally, using its full bounds. 17224 * 17225 * @param clipBounds The rectangular area, in the local coordinates of 17226 * this view, to which future drawing operations will be clipped. 17227 */ 17228 public void setClipBounds(Rect clipBounds) { 17229 if (clipBounds == mClipBounds 17230 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 17231 return; 17232 } 17233 if (clipBounds != null) { 17234 if (mClipBounds == null) { 17235 mClipBounds = new Rect(clipBounds); 17236 } else { 17237 mClipBounds.set(clipBounds); 17238 } 17239 } else { 17240 mClipBounds = null; 17241 } 17242 mRenderNode.setClipBounds(mClipBounds); 17243 invalidateViewProperty(false, false); 17244 } 17245 17246 /** 17247 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 17248 * 17249 * @return A copy of the current clip bounds if clip bounds are set, 17250 * otherwise null. 17251 */ 17252 public Rect getClipBounds() { 17253 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 17254 } 17255 17256 17257 /** 17258 * Populates an output rectangle with the clip bounds of the view, 17259 * returning {@code true} if successful or {@code false} if the view's 17260 * clip bounds are {@code null}. 17261 * 17262 * @param outRect rectangle in which to place the clip bounds of the view 17263 * @return {@code true} if successful or {@code false} if the view's 17264 * clip bounds are {@code null} 17265 */ 17266 public boolean getClipBounds(Rect outRect) { 17267 if (mClipBounds != null) { 17268 outRect.set(mClipBounds); 17269 return true; 17270 } 17271 return false; 17272 } 17273 17274 /** 17275 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 17276 * case of an active Animation being run on the view. 17277 */ 17278 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 17279 Animation a, boolean scalingRequired) { 17280 Transformation invalidationTransform; 17281 final int flags = parent.mGroupFlags; 17282 final boolean initialized = a.isInitialized(); 17283 if (!initialized) { 17284 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 17285 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 17286 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 17287 onAnimationStart(); 17288 } 17289 17290 final Transformation t = parent.getChildTransformation(); 17291 boolean more = a.getTransformation(drawingTime, t, 1f); 17292 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 17293 if (parent.mInvalidationTransformation == null) { 17294 parent.mInvalidationTransformation = new Transformation(); 17295 } 17296 invalidationTransform = parent.mInvalidationTransformation; 17297 a.getTransformation(drawingTime, invalidationTransform, 1f); 17298 } else { 17299 invalidationTransform = t; 17300 } 17301 17302 if (more) { 17303 if (!a.willChangeBounds()) { 17304 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 17305 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 17306 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 17307 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 17308 // The child need to draw an animation, potentially offscreen, so 17309 // make sure we do not cancel invalidate requests 17310 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 17311 parent.invalidate(mLeft, mTop, mRight, mBottom); 17312 } 17313 } else { 17314 if (parent.mInvalidateRegion == null) { 17315 parent.mInvalidateRegion = new RectF(); 17316 } 17317 final RectF region = parent.mInvalidateRegion; 17318 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 17319 invalidationTransform); 17320 17321 // The child need to draw an animation, potentially offscreen, so 17322 // make sure we do not cancel invalidate requests 17323 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 17324 17325 final int left = mLeft + (int) region.left; 17326 final int top = mTop + (int) region.top; 17327 parent.invalidate(left, top, left + (int) (region.width() + .5f), 17328 top + (int) (region.height() + .5f)); 17329 } 17330 } 17331 return more; 17332 } 17333 17334 /** 17335 * This method is called by getDisplayList() when a display list is recorded for a View. 17336 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 17337 */ 17338 void setDisplayListProperties(RenderNode renderNode) { 17339 if (renderNode != null) { 17340 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 17341 renderNode.setClipToBounds(mParent instanceof ViewGroup 17342 && ((ViewGroup) mParent).getClipChildren()); 17343 17344 float alpha = 1; 17345 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 17346 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 17347 ViewGroup parentVG = (ViewGroup) mParent; 17348 final Transformation t = parentVG.getChildTransformation(); 17349 if (parentVG.getChildStaticTransformation(this, t)) { 17350 final int transformType = t.getTransformationType(); 17351 if (transformType != Transformation.TYPE_IDENTITY) { 17352 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 17353 alpha = t.getAlpha(); 17354 } 17355 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 17356 renderNode.setStaticMatrix(t.getMatrix()); 17357 } 17358 } 17359 } 17360 } 17361 if (mTransformationInfo != null) { 17362 alpha *= getFinalAlpha(); 17363 if (alpha < 1) { 17364 final int multipliedAlpha = (int) (255 * alpha); 17365 if (onSetAlpha(multipliedAlpha)) { 17366 alpha = 1; 17367 } 17368 } 17369 renderNode.setAlpha(alpha); 17370 } else if (alpha < 1) { 17371 renderNode.setAlpha(alpha); 17372 } 17373 } 17374 } 17375 17376 /** 17377 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 17378 * 17379 * This is where the View specializes rendering behavior based on layer type, 17380 * and hardware acceleration. 17381 */ 17382 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 17383 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 17384 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 17385 * 17386 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 17387 * HW accelerated, it can't handle drawing RenderNodes. 17388 */ 17389 boolean drawingWithRenderNode = mAttachInfo != null 17390 && mAttachInfo.mHardwareAccelerated 17391 && hardwareAcceleratedCanvas; 17392 17393 boolean more = false; 17394 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 17395 final int parentFlags = parent.mGroupFlags; 17396 17397 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 17398 parent.getChildTransformation().clear(); 17399 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17400 } 17401 17402 Transformation transformToApply = null; 17403 boolean concatMatrix = false; 17404 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 17405 final Animation a = getAnimation(); 17406 if (a != null) { 17407 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 17408 concatMatrix = a.willChangeTransformationMatrix(); 17409 if (concatMatrix) { 17410 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 17411 } 17412 transformToApply = parent.getChildTransformation(); 17413 } else { 17414 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 17415 // No longer animating: clear out old animation matrix 17416 mRenderNode.setAnimationMatrix(null); 17417 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 17418 } 17419 if (!drawingWithRenderNode 17420 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 17421 final Transformation t = parent.getChildTransformation(); 17422 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 17423 if (hasTransform) { 17424 final int transformType = t.getTransformationType(); 17425 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 17426 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 17427 } 17428 } 17429 } 17430 17431 concatMatrix |= !childHasIdentityMatrix; 17432 17433 // Sets the flag as early as possible to allow draw() implementations 17434 // to call invalidate() successfully when doing animations 17435 mPrivateFlags |= PFLAG_DRAWN; 17436 17437 if (!concatMatrix && 17438 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 17439 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 17440 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 17441 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 17442 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 17443 return more; 17444 } 17445 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 17446 17447 if (hardwareAcceleratedCanvas) { 17448 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 17449 // retain the flag's value temporarily in the mRecreateDisplayList flag 17450 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 17451 mPrivateFlags &= ~PFLAG_INVALIDATED; 17452 } 17453 17454 RenderNode renderNode = null; 17455 Bitmap cache = null; 17456 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 17457 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 17458 if (layerType != LAYER_TYPE_NONE) { 17459 // If not drawing with RenderNode, treat HW layers as SW 17460 layerType = LAYER_TYPE_SOFTWARE; 17461 buildDrawingCache(true); 17462 } 17463 cache = getDrawingCache(true); 17464 } 17465 17466 if (drawingWithRenderNode) { 17467 // Delay getting the display list until animation-driven alpha values are 17468 // set up and possibly passed on to the view 17469 renderNode = updateDisplayListIfDirty(); 17470 if (!renderNode.isValid()) { 17471 // Uncommon, but possible. If a view is removed from the hierarchy during the call 17472 // to getDisplayList(), the display list will be marked invalid and we should not 17473 // try to use it again. 17474 renderNode = null; 17475 drawingWithRenderNode = false; 17476 } 17477 } 17478 17479 int sx = 0; 17480 int sy = 0; 17481 if (!drawingWithRenderNode) { 17482 computeScroll(); 17483 sx = mScrollX; 17484 sy = mScrollY; 17485 } 17486 17487 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 17488 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 17489 17490 int restoreTo = -1; 17491 if (!drawingWithRenderNode || transformToApply != null) { 17492 restoreTo = canvas.save(); 17493 } 17494 if (offsetForScroll) { 17495 canvas.translate(mLeft - sx, mTop - sy); 17496 } else { 17497 if (!drawingWithRenderNode) { 17498 canvas.translate(mLeft, mTop); 17499 } 17500 if (scalingRequired) { 17501 if (drawingWithRenderNode) { 17502 // TODO: Might not need this if we put everything inside the DL 17503 restoreTo = canvas.save(); 17504 } 17505 // mAttachInfo cannot be null, otherwise scalingRequired == false 17506 final float scale = 1.0f / mAttachInfo.mApplicationScale; 17507 canvas.scale(scale, scale); 17508 } 17509 } 17510 17511 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 17512 if (transformToApply != null 17513 || alpha < 1 17514 || !hasIdentityMatrix() 17515 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 17516 if (transformToApply != null || !childHasIdentityMatrix) { 17517 int transX = 0; 17518 int transY = 0; 17519 17520 if (offsetForScroll) { 17521 transX = -sx; 17522 transY = -sy; 17523 } 17524 17525 if (transformToApply != null) { 17526 if (concatMatrix) { 17527 if (drawingWithRenderNode) { 17528 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 17529 } else { 17530 // Undo the scroll translation, apply the transformation matrix, 17531 // then redo the scroll translate to get the correct result. 17532 canvas.translate(-transX, -transY); 17533 canvas.concat(transformToApply.getMatrix()); 17534 canvas.translate(transX, transY); 17535 } 17536 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17537 } 17538 17539 float transformAlpha = transformToApply.getAlpha(); 17540 if (transformAlpha < 1) { 17541 alpha *= transformAlpha; 17542 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17543 } 17544 } 17545 17546 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 17547 canvas.translate(-transX, -transY); 17548 canvas.concat(getMatrix()); 17549 canvas.translate(transX, transY); 17550 } 17551 } 17552 17553 // Deal with alpha if it is or used to be <1 17554 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 17555 if (alpha < 1) { 17556 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17557 } else { 17558 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17559 } 17560 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17561 if (!drawingWithDrawingCache) { 17562 final int multipliedAlpha = (int) (255 * alpha); 17563 if (!onSetAlpha(multipliedAlpha)) { 17564 if (drawingWithRenderNode) { 17565 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 17566 } else if (layerType == LAYER_TYPE_NONE) { 17567 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 17568 multipliedAlpha); 17569 } 17570 } else { 17571 // Alpha is handled by the child directly, clobber the layer's alpha 17572 mPrivateFlags |= PFLAG_ALPHA_SET; 17573 } 17574 } 17575 } 17576 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17577 onSetAlpha(255); 17578 mPrivateFlags &= ~PFLAG_ALPHA_SET; 17579 } 17580 17581 if (!drawingWithRenderNode) { 17582 // apply clips directly, since RenderNode won't do it for this draw 17583 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 17584 if (offsetForScroll) { 17585 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 17586 } else { 17587 if (!scalingRequired || cache == null) { 17588 canvas.clipRect(0, 0, getWidth(), getHeight()); 17589 } else { 17590 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 17591 } 17592 } 17593 } 17594 17595 if (mClipBounds != null) { 17596 // clip bounds ignore scroll 17597 canvas.clipRect(mClipBounds); 17598 } 17599 } 17600 17601 if (!drawingWithDrawingCache) { 17602 if (drawingWithRenderNode) { 17603 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17604 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17605 } else { 17606 // Fast path for layouts with no backgrounds 17607 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17608 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17609 dispatchDraw(canvas); 17610 } else { 17611 draw(canvas); 17612 } 17613 } 17614 } else if (cache != null) { 17615 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17616 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 17617 // no layer paint, use temporary paint to draw bitmap 17618 Paint cachePaint = parent.mCachePaint; 17619 if (cachePaint == null) { 17620 cachePaint = new Paint(); 17621 cachePaint.setDither(false); 17622 parent.mCachePaint = cachePaint; 17623 } 17624 cachePaint.setAlpha((int) (alpha * 255)); 17625 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 17626 } else { 17627 // use layer paint to draw the bitmap, merging the two alphas, but also restore 17628 int layerPaintAlpha = mLayerPaint.getAlpha(); 17629 if (alpha < 1) { 17630 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 17631 } 17632 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17633 if (alpha < 1) { 17634 mLayerPaint.setAlpha(layerPaintAlpha); 17635 } 17636 } 17637 } 17638 17639 if (restoreTo >= 0) { 17640 canvas.restoreToCount(restoreTo); 17641 } 17642 17643 if (a != null && !more) { 17644 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17645 onSetAlpha(255); 17646 } 17647 parent.finishAnimatingView(this, a); 17648 } 17649 17650 if (more && hardwareAcceleratedCanvas) { 17651 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17652 // alpha animations should cause the child to recreate its display list 17653 invalidate(true); 17654 } 17655 } 17656 17657 mRecreateDisplayList = false; 17658 17659 return more; 17660 } 17661 17662 static Paint getDebugPaint() { 17663 if (sDebugPaint == null) { 17664 sDebugPaint = new Paint(); 17665 sDebugPaint.setAntiAlias(false); 17666 } 17667 return sDebugPaint; 17668 } 17669 17670 final int dipsToPixels(int dips) { 17671 float scale = getContext().getResources().getDisplayMetrics().density; 17672 return (int) (dips * scale + 0.5f); 17673 } 17674 17675 final private void debugDrawFocus(Canvas canvas) { 17676 if (isFocused()) { 17677 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 17678 final int l = mScrollX; 17679 final int r = l + mRight - mLeft; 17680 final int t = mScrollY; 17681 final int b = t + mBottom - mTop; 17682 17683 final Paint paint = getDebugPaint(); 17684 paint.setColor(DEBUG_CORNERS_COLOR); 17685 17686 // Draw squares in corners. 17687 paint.setStyle(Paint.Style.FILL); 17688 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 17689 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 17690 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 17691 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 17692 17693 // Draw big X across the view. 17694 paint.setStyle(Paint.Style.STROKE); 17695 canvas.drawLine(l, t, r, b, paint); 17696 canvas.drawLine(l, b, r, t, paint); 17697 } 17698 } 17699 17700 /** 17701 * Manually render this view (and all of its children) to the given Canvas. 17702 * The view must have already done a full layout before this function is 17703 * called. When implementing a view, implement 17704 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17705 * If you do need to override this method, call the superclass version. 17706 * 17707 * @param canvas The Canvas to which the View is rendered. 17708 */ 17709 @CallSuper 17710 public void draw(Canvas canvas) { 17711 final int privateFlags = mPrivateFlags; 17712 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17713 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17714 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17715 17716 /* 17717 * Draw traversal performs several drawing steps which must be executed 17718 * in the appropriate order: 17719 * 17720 * 1. Draw the background 17721 * 2. If necessary, save the canvas' layers to prepare for fading 17722 * 3. Draw view's content 17723 * 4. Draw children 17724 * 5. If necessary, draw the fading edges and restore layers 17725 * 6. Draw decorations (scrollbars for instance) 17726 */ 17727 17728 // Step 1, draw the background, if needed 17729 int saveCount; 17730 17731 if (!dirtyOpaque) { 17732 drawBackground(canvas); 17733 } 17734 17735 // skip step 2 & 5 if possible (common case) 17736 final int viewFlags = mViewFlags; 17737 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17738 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17739 if (!verticalEdges && !horizontalEdges) { 17740 // Step 3, draw the content 17741 if (!dirtyOpaque) onDraw(canvas); 17742 17743 // Step 4, draw the children 17744 dispatchDraw(canvas); 17745 17746 // Overlay is part of the content and draws beneath Foreground 17747 if (mOverlay != null && !mOverlay.isEmpty()) { 17748 mOverlay.getOverlayView().dispatchDraw(canvas); 17749 } 17750 17751 // Step 6, draw decorations (foreground, scrollbars) 17752 onDrawForeground(canvas); 17753 17754 if (debugDraw()) { 17755 debugDrawFocus(canvas); 17756 } 17757 17758 // we're done... 17759 return; 17760 } 17761 17762 /* 17763 * Here we do the full fledged routine... 17764 * (this is an uncommon case where speed matters less, 17765 * this is why we repeat some of the tests that have been 17766 * done above) 17767 */ 17768 17769 boolean drawTop = false; 17770 boolean drawBottom = false; 17771 boolean drawLeft = false; 17772 boolean drawRight = false; 17773 17774 float topFadeStrength = 0.0f; 17775 float bottomFadeStrength = 0.0f; 17776 float leftFadeStrength = 0.0f; 17777 float rightFadeStrength = 0.0f; 17778 17779 // Step 2, save the canvas' layers 17780 int paddingLeft = mPaddingLeft; 17781 17782 final boolean offsetRequired = isPaddingOffsetRequired(); 17783 if (offsetRequired) { 17784 paddingLeft += getLeftPaddingOffset(); 17785 } 17786 17787 int left = mScrollX + paddingLeft; 17788 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17789 int top = mScrollY + getFadeTop(offsetRequired); 17790 int bottom = top + getFadeHeight(offsetRequired); 17791 17792 if (offsetRequired) { 17793 right += getRightPaddingOffset(); 17794 bottom += getBottomPaddingOffset(); 17795 } 17796 17797 final ScrollabilityCache scrollabilityCache = mScrollCache; 17798 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17799 int length = (int) fadeHeight; 17800 17801 // clip the fade length if top and bottom fades overlap 17802 // overlapping fades produce odd-looking artifacts 17803 if (verticalEdges && (top + length > bottom - length)) { 17804 length = (bottom - top) / 2; 17805 } 17806 17807 // also clip horizontal fades if necessary 17808 if (horizontalEdges && (left + length > right - length)) { 17809 length = (right - left) / 2; 17810 } 17811 17812 if (verticalEdges) { 17813 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17814 drawTop = topFadeStrength * fadeHeight > 1.0f; 17815 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17816 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17817 } 17818 17819 if (horizontalEdges) { 17820 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17821 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17822 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17823 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17824 } 17825 17826 saveCount = canvas.getSaveCount(); 17827 17828 int solidColor = getSolidColor(); 17829 if (solidColor == 0) { 17830 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17831 17832 if (drawTop) { 17833 canvas.saveLayer(left, top, right, top + length, null, flags); 17834 } 17835 17836 if (drawBottom) { 17837 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17838 } 17839 17840 if (drawLeft) { 17841 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17842 } 17843 17844 if (drawRight) { 17845 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17846 } 17847 } else { 17848 scrollabilityCache.setFadeColor(solidColor); 17849 } 17850 17851 // Step 3, draw the content 17852 if (!dirtyOpaque) onDraw(canvas); 17853 17854 // Step 4, draw the children 17855 dispatchDraw(canvas); 17856 17857 // Step 5, draw the fade effect and restore layers 17858 final Paint p = scrollabilityCache.paint; 17859 final Matrix matrix = scrollabilityCache.matrix; 17860 final Shader fade = scrollabilityCache.shader; 17861 17862 if (drawTop) { 17863 matrix.setScale(1, fadeHeight * topFadeStrength); 17864 matrix.postTranslate(left, top); 17865 fade.setLocalMatrix(matrix); 17866 p.setShader(fade); 17867 canvas.drawRect(left, top, right, top + length, p); 17868 } 17869 17870 if (drawBottom) { 17871 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17872 matrix.postRotate(180); 17873 matrix.postTranslate(left, bottom); 17874 fade.setLocalMatrix(matrix); 17875 p.setShader(fade); 17876 canvas.drawRect(left, bottom - length, right, bottom, p); 17877 } 17878 17879 if (drawLeft) { 17880 matrix.setScale(1, fadeHeight * leftFadeStrength); 17881 matrix.postRotate(-90); 17882 matrix.postTranslate(left, top); 17883 fade.setLocalMatrix(matrix); 17884 p.setShader(fade); 17885 canvas.drawRect(left, top, left + length, bottom, p); 17886 } 17887 17888 if (drawRight) { 17889 matrix.setScale(1, fadeHeight * rightFadeStrength); 17890 matrix.postRotate(90); 17891 matrix.postTranslate(right, top); 17892 fade.setLocalMatrix(matrix); 17893 p.setShader(fade); 17894 canvas.drawRect(right - length, top, right, bottom, p); 17895 } 17896 17897 canvas.restoreToCount(saveCount); 17898 17899 // Overlay is part of the content and draws beneath Foreground 17900 if (mOverlay != null && !mOverlay.isEmpty()) { 17901 mOverlay.getOverlayView().dispatchDraw(canvas); 17902 } 17903 17904 // Step 6, draw decorations (foreground, scrollbars) 17905 onDrawForeground(canvas); 17906 17907 if (debugDraw()) { 17908 debugDrawFocus(canvas); 17909 } 17910 } 17911 17912 /** 17913 * Draws the background onto the specified canvas. 17914 * 17915 * @param canvas Canvas on which to draw the background 17916 */ 17917 private void drawBackground(Canvas canvas) { 17918 final Drawable background = mBackground; 17919 if (background == null) { 17920 return; 17921 } 17922 17923 setBackgroundBounds(); 17924 17925 // Attempt to use a display list if requested. 17926 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17927 && mAttachInfo.mThreadedRenderer != null) { 17928 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17929 17930 final RenderNode renderNode = mBackgroundRenderNode; 17931 if (renderNode != null && renderNode.isValid()) { 17932 setBackgroundRenderNodeProperties(renderNode); 17933 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17934 return; 17935 } 17936 } 17937 17938 final int scrollX = mScrollX; 17939 final int scrollY = mScrollY; 17940 if ((scrollX | scrollY) == 0) { 17941 background.draw(canvas); 17942 } else { 17943 canvas.translate(scrollX, scrollY); 17944 background.draw(canvas); 17945 canvas.translate(-scrollX, -scrollY); 17946 } 17947 } 17948 17949 /** 17950 * Sets the correct background bounds and rebuilds the outline, if needed. 17951 * <p/> 17952 * This is called by LayoutLib. 17953 */ 17954 void setBackgroundBounds() { 17955 if (mBackgroundSizeChanged && mBackground != null) { 17956 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17957 mBackgroundSizeChanged = false; 17958 rebuildOutline(); 17959 } 17960 } 17961 17962 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17963 renderNode.setTranslationX(mScrollX); 17964 renderNode.setTranslationY(mScrollY); 17965 } 17966 17967 /** 17968 * Creates a new display list or updates the existing display list for the 17969 * specified Drawable. 17970 * 17971 * @param drawable Drawable for which to create a display list 17972 * @param renderNode Existing RenderNode, or {@code null} 17973 * @return A valid display list for the specified drawable 17974 */ 17975 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17976 if (renderNode == null) { 17977 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17978 } 17979 17980 final Rect bounds = drawable.getBounds(); 17981 final int width = bounds.width(); 17982 final int height = bounds.height(); 17983 final DisplayListCanvas canvas = renderNode.start(width, height); 17984 17985 // Reverse left/top translation done by drawable canvas, which will 17986 // instead be applied by rendernode's LTRB bounds below. This way, the 17987 // drawable's bounds match with its rendernode bounds and its content 17988 // will lie within those bounds in the rendernode tree. 17989 canvas.translate(-bounds.left, -bounds.top); 17990 17991 try { 17992 drawable.draw(canvas); 17993 } finally { 17994 renderNode.end(canvas); 17995 } 17996 17997 // Set up drawable properties that are view-independent. 17998 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17999 renderNode.setProjectBackwards(drawable.isProjected()); 18000 renderNode.setProjectionReceiver(true); 18001 renderNode.setClipToBounds(false); 18002 return renderNode; 18003 } 18004 18005 /** 18006 * Returns the overlay for this view, creating it if it does not yet exist. 18007 * Adding drawables to the overlay will cause them to be displayed whenever 18008 * the view itself is redrawn. Objects in the overlay should be actively 18009 * managed: remove them when they should not be displayed anymore. The 18010 * overlay will always have the same size as its host view. 18011 * 18012 * <p>Note: Overlays do not currently work correctly with {@link 18013 * SurfaceView} or {@link TextureView}; contents in overlays for these 18014 * types of views may not display correctly.</p> 18015 * 18016 * @return The ViewOverlay object for this view. 18017 * @see ViewOverlay 18018 */ 18019 public ViewOverlay getOverlay() { 18020 if (mOverlay == null) { 18021 mOverlay = new ViewOverlay(mContext, this); 18022 } 18023 return mOverlay; 18024 } 18025 18026 /** 18027 * Override this if your view is known to always be drawn on top of a solid color background, 18028 * and needs to draw fading edges. Returning a non-zero color enables the view system to 18029 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 18030 * should be set to 0xFF. 18031 * 18032 * @see #setVerticalFadingEdgeEnabled(boolean) 18033 * @see #setHorizontalFadingEdgeEnabled(boolean) 18034 * 18035 * @return The known solid color background for this view, or 0 if the color may vary 18036 */ 18037 @ViewDebug.ExportedProperty(category = "drawing") 18038 @ColorInt 18039 public int getSolidColor() { 18040 return 0; 18041 } 18042 18043 /** 18044 * Build a human readable string representation of the specified view flags. 18045 * 18046 * @param flags the view flags to convert to a string 18047 * @return a String representing the supplied flags 18048 */ 18049 private static String printFlags(int flags) { 18050 String output = ""; 18051 int numFlags = 0; 18052 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 18053 output += "TAKES_FOCUS"; 18054 numFlags++; 18055 } 18056 18057 switch (flags & VISIBILITY_MASK) { 18058 case INVISIBLE: 18059 if (numFlags > 0) { 18060 output += " "; 18061 } 18062 output += "INVISIBLE"; 18063 // USELESS HERE numFlags++; 18064 break; 18065 case GONE: 18066 if (numFlags > 0) { 18067 output += " "; 18068 } 18069 output += "GONE"; 18070 // USELESS HERE numFlags++; 18071 break; 18072 default: 18073 break; 18074 } 18075 return output; 18076 } 18077 18078 /** 18079 * Build a human readable string representation of the specified private 18080 * view flags. 18081 * 18082 * @param privateFlags the private view flags to convert to a string 18083 * @return a String representing the supplied flags 18084 */ 18085 private static String printPrivateFlags(int privateFlags) { 18086 String output = ""; 18087 int numFlags = 0; 18088 18089 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 18090 output += "WANTS_FOCUS"; 18091 numFlags++; 18092 } 18093 18094 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 18095 if (numFlags > 0) { 18096 output += " "; 18097 } 18098 output += "FOCUSED"; 18099 numFlags++; 18100 } 18101 18102 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 18103 if (numFlags > 0) { 18104 output += " "; 18105 } 18106 output += "SELECTED"; 18107 numFlags++; 18108 } 18109 18110 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 18111 if (numFlags > 0) { 18112 output += " "; 18113 } 18114 output += "IS_ROOT_NAMESPACE"; 18115 numFlags++; 18116 } 18117 18118 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 18119 if (numFlags > 0) { 18120 output += " "; 18121 } 18122 output += "HAS_BOUNDS"; 18123 numFlags++; 18124 } 18125 18126 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 18127 if (numFlags > 0) { 18128 output += " "; 18129 } 18130 output += "DRAWN"; 18131 // USELESS HERE numFlags++; 18132 } 18133 return output; 18134 } 18135 18136 /** 18137 * <p>Indicates whether or not this view's layout will be requested during 18138 * the next hierarchy layout pass.</p> 18139 * 18140 * @return true if the layout will be forced during next layout pass 18141 */ 18142 public boolean isLayoutRequested() { 18143 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 18144 } 18145 18146 /** 18147 * Return true if o is a ViewGroup that is laying out using optical bounds. 18148 * @hide 18149 */ 18150 public static boolean isLayoutModeOptical(Object o) { 18151 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 18152 } 18153 18154 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 18155 Insets parentInsets = mParent instanceof View ? 18156 ((View) mParent).getOpticalInsets() : Insets.NONE; 18157 Insets childInsets = getOpticalInsets(); 18158 return setFrame( 18159 left + parentInsets.left - childInsets.left, 18160 top + parentInsets.top - childInsets.top, 18161 right + parentInsets.left + childInsets.right, 18162 bottom + parentInsets.top + childInsets.bottom); 18163 } 18164 18165 /** 18166 * Assign a size and position to a view and all of its 18167 * descendants 18168 * 18169 * <p>This is the second phase of the layout mechanism. 18170 * (The first is measuring). In this phase, each parent calls 18171 * layout on all of its children to position them. 18172 * This is typically done using the child measurements 18173 * that were stored in the measure pass().</p> 18174 * 18175 * <p>Derived classes should not override this method. 18176 * Derived classes with children should override 18177 * onLayout. In that method, they should 18178 * call layout on each of their children.</p> 18179 * 18180 * @param l Left position, relative to parent 18181 * @param t Top position, relative to parent 18182 * @param r Right position, relative to parent 18183 * @param b Bottom position, relative to parent 18184 */ 18185 @SuppressWarnings({"unchecked"}) 18186 public void layout(int l, int t, int r, int b) { 18187 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 18188 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 18189 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 18190 } 18191 18192 int oldL = mLeft; 18193 int oldT = mTop; 18194 int oldB = mBottom; 18195 int oldR = mRight; 18196 18197 boolean changed = isLayoutModeOptical(mParent) ? 18198 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 18199 18200 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 18201 onLayout(changed, l, t, r, b); 18202 18203 if (shouldDrawRoundScrollbar()) { 18204 if(mRoundScrollbarRenderer == null) { 18205 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 18206 } 18207 } else { 18208 mRoundScrollbarRenderer = null; 18209 } 18210 18211 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 18212 18213 ListenerInfo li = mListenerInfo; 18214 if (li != null && li.mOnLayoutChangeListeners != null) { 18215 ArrayList<OnLayoutChangeListener> listenersCopy = 18216 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 18217 int numListeners = listenersCopy.size(); 18218 for (int i = 0; i < numListeners; ++i) { 18219 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 18220 } 18221 } 18222 } 18223 18224 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 18225 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 18226 } 18227 18228 /** 18229 * Called from layout when this view should 18230 * assign a size and position to each of its children. 18231 * 18232 * Derived classes with children should override 18233 * this method and call layout on each of 18234 * their children. 18235 * @param changed This is a new size or position for this view 18236 * @param left Left position, relative to parent 18237 * @param top Top position, relative to parent 18238 * @param right Right position, relative to parent 18239 * @param bottom Bottom position, relative to parent 18240 */ 18241 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 18242 } 18243 18244 /** 18245 * Assign a size and position to this view. 18246 * 18247 * This is called from layout. 18248 * 18249 * @param left Left position, relative to parent 18250 * @param top Top position, relative to parent 18251 * @param right Right position, relative to parent 18252 * @param bottom Bottom position, relative to parent 18253 * @return true if the new size and position are different than the 18254 * previous ones 18255 * {@hide} 18256 */ 18257 protected boolean setFrame(int left, int top, int right, int bottom) { 18258 boolean changed = false; 18259 18260 if (DBG) { 18261 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 18262 + right + "," + bottom + ")"); 18263 } 18264 18265 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 18266 changed = true; 18267 18268 // Remember our drawn bit 18269 int drawn = mPrivateFlags & PFLAG_DRAWN; 18270 18271 int oldWidth = mRight - mLeft; 18272 int oldHeight = mBottom - mTop; 18273 int newWidth = right - left; 18274 int newHeight = bottom - top; 18275 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 18276 18277 // Invalidate our old position 18278 invalidate(sizeChanged); 18279 18280 mLeft = left; 18281 mTop = top; 18282 mRight = right; 18283 mBottom = bottom; 18284 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 18285 18286 mPrivateFlags |= PFLAG_HAS_BOUNDS; 18287 18288 18289 if (sizeChanged) { 18290 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 18291 } 18292 18293 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 18294 // If we are visible, force the DRAWN bit to on so that 18295 // this invalidate will go through (at least to our parent). 18296 // This is because someone may have invalidated this view 18297 // before this call to setFrame came in, thereby clearing 18298 // the DRAWN bit. 18299 mPrivateFlags |= PFLAG_DRAWN; 18300 invalidate(sizeChanged); 18301 // parent display list may need to be recreated based on a change in the bounds 18302 // of any child 18303 invalidateParentCaches(); 18304 } 18305 18306 // Reset drawn bit to original value (invalidate turns it off) 18307 mPrivateFlags |= drawn; 18308 18309 mBackgroundSizeChanged = true; 18310 if (mForegroundInfo != null) { 18311 mForegroundInfo.mBoundsChanged = true; 18312 } 18313 18314 notifySubtreeAccessibilityStateChangedIfNeeded(); 18315 } 18316 return changed; 18317 } 18318 18319 /** 18320 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 18321 * @hide 18322 */ 18323 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 18324 setFrame(left, top, right, bottom); 18325 } 18326 18327 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 18328 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 18329 if (mOverlay != null) { 18330 mOverlay.getOverlayView().setRight(newWidth); 18331 mOverlay.getOverlayView().setBottom(newHeight); 18332 } 18333 rebuildOutline(); 18334 } 18335 18336 /** 18337 * Finalize inflating a view from XML. This is called as the last phase 18338 * of inflation, after all child views have been added. 18339 * 18340 * <p>Even if the subclass overrides onFinishInflate, they should always be 18341 * sure to call the super method, so that we get called. 18342 */ 18343 @CallSuper 18344 protected void onFinishInflate() { 18345 } 18346 18347 /** 18348 * Returns the resources associated with this view. 18349 * 18350 * @return Resources object. 18351 */ 18352 public Resources getResources() { 18353 return mResources; 18354 } 18355 18356 /** 18357 * Invalidates the specified Drawable. 18358 * 18359 * @param drawable the drawable to invalidate 18360 */ 18361 @Override 18362 public void invalidateDrawable(@NonNull Drawable drawable) { 18363 if (verifyDrawable(drawable)) { 18364 final Rect dirty = drawable.getDirtyBounds(); 18365 final int scrollX = mScrollX; 18366 final int scrollY = mScrollY; 18367 18368 invalidate(dirty.left + scrollX, dirty.top + scrollY, 18369 dirty.right + scrollX, dirty.bottom + scrollY); 18370 rebuildOutline(); 18371 } 18372 } 18373 18374 /** 18375 * Schedules an action on a drawable to occur at a specified time. 18376 * 18377 * @param who the recipient of the action 18378 * @param what the action to run on the drawable 18379 * @param when the time at which the action must occur. Uses the 18380 * {@link SystemClock#uptimeMillis} timebase. 18381 */ 18382 @Override 18383 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 18384 if (verifyDrawable(who) && what != null) { 18385 final long delay = when - SystemClock.uptimeMillis(); 18386 if (mAttachInfo != null) { 18387 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 18388 Choreographer.CALLBACK_ANIMATION, what, who, 18389 Choreographer.subtractFrameDelay(delay)); 18390 } else { 18391 // Postpone the runnable until we know 18392 // on which thread it needs to run. 18393 getRunQueue().postDelayed(what, delay); 18394 } 18395 } 18396 } 18397 18398 /** 18399 * Cancels a scheduled action on a drawable. 18400 * 18401 * @param who the recipient of the action 18402 * @param what the action to cancel 18403 */ 18404 @Override 18405 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 18406 if (verifyDrawable(who) && what != null) { 18407 if (mAttachInfo != null) { 18408 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 18409 Choreographer.CALLBACK_ANIMATION, what, who); 18410 } 18411 getRunQueue().removeCallbacks(what); 18412 } 18413 } 18414 18415 /** 18416 * Unschedule any events associated with the given Drawable. This can be 18417 * used when selecting a new Drawable into a view, so that the previous 18418 * one is completely unscheduled. 18419 * 18420 * @param who The Drawable to unschedule. 18421 * 18422 * @see #drawableStateChanged 18423 */ 18424 public void unscheduleDrawable(Drawable who) { 18425 if (mAttachInfo != null && who != null) { 18426 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 18427 Choreographer.CALLBACK_ANIMATION, null, who); 18428 } 18429 } 18430 18431 /** 18432 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 18433 * that the View directionality can and will be resolved before its Drawables. 18434 * 18435 * Will call {@link View#onResolveDrawables} when resolution is done. 18436 * 18437 * @hide 18438 */ 18439 protected void resolveDrawables() { 18440 // Drawables resolution may need to happen before resolving the layout direction (which is 18441 // done only during the measure() call). 18442 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 18443 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 18444 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 18445 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 18446 // direction to be resolved as its resolved value will be the same as its raw value. 18447 if (!isLayoutDirectionResolved() && 18448 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 18449 return; 18450 } 18451 18452 final int layoutDirection = isLayoutDirectionResolved() ? 18453 getLayoutDirection() : getRawLayoutDirection(); 18454 18455 if (mBackground != null) { 18456 mBackground.setLayoutDirection(layoutDirection); 18457 } 18458 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18459 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 18460 } 18461 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 18462 onResolveDrawables(layoutDirection); 18463 } 18464 18465 boolean areDrawablesResolved() { 18466 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 18467 } 18468 18469 /** 18470 * Called when layout direction has been resolved. 18471 * 18472 * The default implementation does nothing. 18473 * 18474 * @param layoutDirection The resolved layout direction. 18475 * 18476 * @see #LAYOUT_DIRECTION_LTR 18477 * @see #LAYOUT_DIRECTION_RTL 18478 * 18479 * @hide 18480 */ 18481 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 18482 } 18483 18484 /** 18485 * @hide 18486 */ 18487 protected void resetResolvedDrawables() { 18488 resetResolvedDrawablesInternal(); 18489 } 18490 18491 void resetResolvedDrawablesInternal() { 18492 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 18493 } 18494 18495 /** 18496 * If your view subclass is displaying its own Drawable objects, it should 18497 * override this function and return true for any Drawable it is 18498 * displaying. This allows animations for those drawables to be 18499 * scheduled. 18500 * 18501 * <p>Be sure to call through to the super class when overriding this 18502 * function. 18503 * 18504 * @param who The Drawable to verify. Return true if it is one you are 18505 * displaying, else return the result of calling through to the 18506 * super class. 18507 * 18508 * @return boolean If true than the Drawable is being displayed in the 18509 * view; else false and it is not allowed to animate. 18510 * 18511 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 18512 * @see #drawableStateChanged() 18513 */ 18514 @CallSuper 18515 protected boolean verifyDrawable(@NonNull Drawable who) { 18516 // Avoid verifying the scroll bar drawable so that we don't end up in 18517 // an invalidation loop. This effectively prevents the scroll bar 18518 // drawable from triggering invalidations and scheduling runnables. 18519 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 18520 } 18521 18522 /** 18523 * This function is called whenever the state of the view changes in such 18524 * a way that it impacts the state of drawables being shown. 18525 * <p> 18526 * If the View has a StateListAnimator, it will also be called to run necessary state 18527 * change animations. 18528 * <p> 18529 * Be sure to call through to the superclass when overriding this function. 18530 * 18531 * @see Drawable#setState(int[]) 18532 */ 18533 @CallSuper 18534 protected void drawableStateChanged() { 18535 final int[] state = getDrawableState(); 18536 boolean changed = false; 18537 18538 final Drawable bg = mBackground; 18539 if (bg != null && bg.isStateful()) { 18540 changed |= bg.setState(state); 18541 } 18542 18543 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18544 if (fg != null && fg.isStateful()) { 18545 changed |= fg.setState(state); 18546 } 18547 18548 if (mScrollCache != null) { 18549 final Drawable scrollBar = mScrollCache.scrollBar; 18550 if (scrollBar != null && scrollBar.isStateful()) { 18551 changed |= scrollBar.setState(state) 18552 && mScrollCache.state != ScrollabilityCache.OFF; 18553 } 18554 } 18555 18556 if (mStateListAnimator != null) { 18557 mStateListAnimator.setState(state); 18558 } 18559 18560 if (changed) { 18561 invalidate(); 18562 } 18563 } 18564 18565 /** 18566 * This function is called whenever the view hotspot changes and needs to 18567 * be propagated to drawables or child views managed by the view. 18568 * <p> 18569 * Dispatching to child views is handled by 18570 * {@link #dispatchDrawableHotspotChanged(float, float)}. 18571 * <p> 18572 * Be sure to call through to the superclass when overriding this function. 18573 * 18574 * @param x hotspot x coordinate 18575 * @param y hotspot y coordinate 18576 */ 18577 @CallSuper 18578 public void drawableHotspotChanged(float x, float y) { 18579 if (mBackground != null) { 18580 mBackground.setHotspot(x, y); 18581 } 18582 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18583 mForegroundInfo.mDrawable.setHotspot(x, y); 18584 } 18585 18586 dispatchDrawableHotspotChanged(x, y); 18587 } 18588 18589 /** 18590 * Dispatches drawableHotspotChanged to all of this View's children. 18591 * 18592 * @param x hotspot x coordinate 18593 * @param y hotspot y coordinate 18594 * @see #drawableHotspotChanged(float, float) 18595 */ 18596 public void dispatchDrawableHotspotChanged(float x, float y) { 18597 } 18598 18599 /** 18600 * Call this to force a view to update its drawable state. This will cause 18601 * drawableStateChanged to be called on this view. Views that are interested 18602 * in the new state should call getDrawableState. 18603 * 18604 * @see #drawableStateChanged 18605 * @see #getDrawableState 18606 */ 18607 public void refreshDrawableState() { 18608 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 18609 drawableStateChanged(); 18610 18611 ViewParent parent = mParent; 18612 if (parent != null) { 18613 parent.childDrawableStateChanged(this); 18614 } 18615 } 18616 18617 /** 18618 * Return an array of resource IDs of the drawable states representing the 18619 * current state of the view. 18620 * 18621 * @return The current drawable state 18622 * 18623 * @see Drawable#setState(int[]) 18624 * @see #drawableStateChanged() 18625 * @see #onCreateDrawableState(int) 18626 */ 18627 public final int[] getDrawableState() { 18628 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 18629 return mDrawableState; 18630 } else { 18631 mDrawableState = onCreateDrawableState(0); 18632 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 18633 return mDrawableState; 18634 } 18635 } 18636 18637 /** 18638 * Generate the new {@link android.graphics.drawable.Drawable} state for 18639 * this view. This is called by the view 18640 * system when the cached Drawable state is determined to be invalid. To 18641 * retrieve the current state, you should use {@link #getDrawableState}. 18642 * 18643 * @param extraSpace if non-zero, this is the number of extra entries you 18644 * would like in the returned array in which you can place your own 18645 * states. 18646 * 18647 * @return Returns an array holding the current {@link Drawable} state of 18648 * the view. 18649 * 18650 * @see #mergeDrawableStates(int[], int[]) 18651 */ 18652 protected int[] onCreateDrawableState(int extraSpace) { 18653 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 18654 mParent instanceof View) { 18655 return ((View) mParent).onCreateDrawableState(extraSpace); 18656 } 18657 18658 int[] drawableState; 18659 18660 int privateFlags = mPrivateFlags; 18661 18662 int viewStateIndex = 0; 18663 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 18664 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 18665 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 18666 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 18667 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 18668 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 18669 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 18670 ThreadedRenderer.isAvailable()) { 18671 // This is set if HW acceleration is requested, even if the current 18672 // process doesn't allow it. This is just to allow app preview 18673 // windows to better match their app. 18674 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 18675 } 18676 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 18677 18678 final int privateFlags2 = mPrivateFlags2; 18679 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 18680 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 18681 } 18682 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 18683 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 18684 } 18685 18686 drawableState = StateSet.get(viewStateIndex); 18687 18688 //noinspection ConstantIfStatement 18689 if (false) { 18690 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18691 Log.i("View", toString() 18692 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18693 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18694 + " fo=" + hasFocus() 18695 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18696 + " wf=" + hasWindowFocus() 18697 + ": " + Arrays.toString(drawableState)); 18698 } 18699 18700 if (extraSpace == 0) { 18701 return drawableState; 18702 } 18703 18704 final int[] fullState; 18705 if (drawableState != null) { 18706 fullState = new int[drawableState.length + extraSpace]; 18707 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18708 } else { 18709 fullState = new int[extraSpace]; 18710 } 18711 18712 return fullState; 18713 } 18714 18715 /** 18716 * Merge your own state values in <var>additionalState</var> into the base 18717 * state values <var>baseState</var> that were returned by 18718 * {@link #onCreateDrawableState(int)}. 18719 * 18720 * @param baseState The base state values returned by 18721 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18722 * own additional state values. 18723 * 18724 * @param additionalState The additional state values you would like 18725 * added to <var>baseState</var>; this array is not modified. 18726 * 18727 * @return As a convenience, the <var>baseState</var> array you originally 18728 * passed into the function is returned. 18729 * 18730 * @see #onCreateDrawableState(int) 18731 */ 18732 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18733 final int N = baseState.length; 18734 int i = N - 1; 18735 while (i >= 0 && baseState[i] == 0) { 18736 i--; 18737 } 18738 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18739 return baseState; 18740 } 18741 18742 /** 18743 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18744 * on all Drawable objects associated with this view. 18745 * <p> 18746 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18747 * attached to this view. 18748 */ 18749 @CallSuper 18750 public void jumpDrawablesToCurrentState() { 18751 if (mBackground != null) { 18752 mBackground.jumpToCurrentState(); 18753 } 18754 if (mStateListAnimator != null) { 18755 mStateListAnimator.jumpToCurrentState(); 18756 } 18757 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18758 mForegroundInfo.mDrawable.jumpToCurrentState(); 18759 } 18760 } 18761 18762 /** 18763 * Sets the background color for this view. 18764 * @param color the color of the background 18765 */ 18766 @RemotableViewMethod 18767 public void setBackgroundColor(@ColorInt int color) { 18768 if (mBackground instanceof ColorDrawable) { 18769 ((ColorDrawable) mBackground.mutate()).setColor(color); 18770 computeOpaqueFlags(); 18771 mBackgroundResource = 0; 18772 } else { 18773 setBackground(new ColorDrawable(color)); 18774 } 18775 } 18776 18777 /** 18778 * Set the background to a given resource. The resource should refer to 18779 * a Drawable object or 0 to remove the background. 18780 * @param resid The identifier of the resource. 18781 * 18782 * @attr ref android.R.styleable#View_background 18783 */ 18784 @RemotableViewMethod 18785 public void setBackgroundResource(@DrawableRes int resid) { 18786 if (resid != 0 && resid == mBackgroundResource) { 18787 return; 18788 } 18789 18790 Drawable d = null; 18791 if (resid != 0) { 18792 d = mContext.getDrawable(resid); 18793 } 18794 setBackground(d); 18795 18796 mBackgroundResource = resid; 18797 } 18798 18799 /** 18800 * Set the background to a given Drawable, or remove the background. If the 18801 * background has padding, this View's padding is set to the background's 18802 * padding. However, when a background is removed, this View's padding isn't 18803 * touched. If setting the padding is desired, please use 18804 * {@link #setPadding(int, int, int, int)}. 18805 * 18806 * @param background The Drawable to use as the background, or null to remove the 18807 * background 18808 */ 18809 public void setBackground(Drawable background) { 18810 //noinspection deprecation 18811 setBackgroundDrawable(background); 18812 } 18813 18814 /** 18815 * @deprecated use {@link #setBackground(Drawable)} instead 18816 */ 18817 @Deprecated 18818 public void setBackgroundDrawable(Drawable background) { 18819 computeOpaqueFlags(); 18820 18821 if (background == mBackground) { 18822 return; 18823 } 18824 18825 boolean requestLayout = false; 18826 18827 mBackgroundResource = 0; 18828 18829 /* 18830 * Regardless of whether we're setting a new background or not, we want 18831 * to clear the previous drawable. setVisible first while we still have the callback set. 18832 */ 18833 if (mBackground != null) { 18834 if (isAttachedToWindow()) { 18835 mBackground.setVisible(false, false); 18836 } 18837 mBackground.setCallback(null); 18838 unscheduleDrawable(mBackground); 18839 } 18840 18841 if (background != null) { 18842 Rect padding = sThreadLocal.get(); 18843 if (padding == null) { 18844 padding = new Rect(); 18845 sThreadLocal.set(padding); 18846 } 18847 resetResolvedDrawablesInternal(); 18848 background.setLayoutDirection(getLayoutDirection()); 18849 if (background.getPadding(padding)) { 18850 resetResolvedPaddingInternal(); 18851 switch (background.getLayoutDirection()) { 18852 case LAYOUT_DIRECTION_RTL: 18853 mUserPaddingLeftInitial = padding.right; 18854 mUserPaddingRightInitial = padding.left; 18855 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18856 break; 18857 case LAYOUT_DIRECTION_LTR: 18858 default: 18859 mUserPaddingLeftInitial = padding.left; 18860 mUserPaddingRightInitial = padding.right; 18861 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18862 } 18863 mLeftPaddingDefined = false; 18864 mRightPaddingDefined = false; 18865 } 18866 18867 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18868 // if it has a different minimum size, we should layout again 18869 if (mBackground == null 18870 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18871 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18872 requestLayout = true; 18873 } 18874 18875 // Set mBackground before we set this as the callback and start making other 18876 // background drawable state change calls. In particular, the setVisible call below 18877 // can result in drawables attempting to start animations or otherwise invalidate, 18878 // which requires the view set as the callback (us) to recognize the drawable as 18879 // belonging to it as per verifyDrawable. 18880 mBackground = background; 18881 if (background.isStateful()) { 18882 background.setState(getDrawableState()); 18883 } 18884 if (isAttachedToWindow()) { 18885 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18886 } 18887 18888 applyBackgroundTint(); 18889 18890 // Set callback last, since the view may still be initializing. 18891 background.setCallback(this); 18892 18893 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18894 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18895 requestLayout = true; 18896 } 18897 } else { 18898 /* Remove the background */ 18899 mBackground = null; 18900 if ((mViewFlags & WILL_NOT_DRAW) != 0 18901 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18902 mPrivateFlags |= PFLAG_SKIP_DRAW; 18903 } 18904 18905 /* 18906 * When the background is set, we try to apply its padding to this 18907 * View. When the background is removed, we don't touch this View's 18908 * padding. This is noted in the Javadocs. Hence, we don't need to 18909 * requestLayout(), the invalidate() below is sufficient. 18910 */ 18911 18912 // The old background's minimum size could have affected this 18913 // View's layout, so let's requestLayout 18914 requestLayout = true; 18915 } 18916 18917 computeOpaqueFlags(); 18918 18919 if (requestLayout) { 18920 requestLayout(); 18921 } 18922 18923 mBackgroundSizeChanged = true; 18924 invalidate(true); 18925 invalidateOutline(); 18926 } 18927 18928 /** 18929 * Gets the background drawable 18930 * 18931 * @return The drawable used as the background for this view, if any. 18932 * 18933 * @see #setBackground(Drawable) 18934 * 18935 * @attr ref android.R.styleable#View_background 18936 */ 18937 public Drawable getBackground() { 18938 return mBackground; 18939 } 18940 18941 /** 18942 * Applies a tint to the background drawable. Does not modify the current tint 18943 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18944 * <p> 18945 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18946 * mutate the drawable and apply the specified tint and tint mode using 18947 * {@link Drawable#setTintList(ColorStateList)}. 18948 * 18949 * @param tint the tint to apply, may be {@code null} to clear tint 18950 * 18951 * @attr ref android.R.styleable#View_backgroundTint 18952 * @see #getBackgroundTintList() 18953 * @see Drawable#setTintList(ColorStateList) 18954 */ 18955 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18956 if (mBackgroundTint == null) { 18957 mBackgroundTint = new TintInfo(); 18958 } 18959 mBackgroundTint.mTintList = tint; 18960 mBackgroundTint.mHasTintList = true; 18961 18962 applyBackgroundTint(); 18963 } 18964 18965 /** 18966 * Return the tint applied to the background drawable, if specified. 18967 * 18968 * @return the tint applied to the background drawable 18969 * @attr ref android.R.styleable#View_backgroundTint 18970 * @see #setBackgroundTintList(ColorStateList) 18971 */ 18972 @Nullable 18973 public ColorStateList getBackgroundTintList() { 18974 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18975 } 18976 18977 /** 18978 * Specifies the blending mode used to apply the tint specified by 18979 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18980 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18981 * 18982 * @param tintMode the blending mode used to apply the tint, may be 18983 * {@code null} to clear tint 18984 * @attr ref android.R.styleable#View_backgroundTintMode 18985 * @see #getBackgroundTintMode() 18986 * @see Drawable#setTintMode(PorterDuff.Mode) 18987 */ 18988 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18989 if (mBackgroundTint == null) { 18990 mBackgroundTint = new TintInfo(); 18991 } 18992 mBackgroundTint.mTintMode = tintMode; 18993 mBackgroundTint.mHasTintMode = true; 18994 18995 applyBackgroundTint(); 18996 } 18997 18998 /** 18999 * Return the blending mode used to apply the tint to the background 19000 * drawable, if specified. 19001 * 19002 * @return the blending mode used to apply the tint to the background 19003 * drawable 19004 * @attr ref android.R.styleable#View_backgroundTintMode 19005 * @see #setBackgroundTintMode(PorterDuff.Mode) 19006 */ 19007 @Nullable 19008 public PorterDuff.Mode getBackgroundTintMode() { 19009 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 19010 } 19011 19012 private void applyBackgroundTint() { 19013 if (mBackground != null && mBackgroundTint != null) { 19014 final TintInfo tintInfo = mBackgroundTint; 19015 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 19016 mBackground = mBackground.mutate(); 19017 19018 if (tintInfo.mHasTintList) { 19019 mBackground.setTintList(tintInfo.mTintList); 19020 } 19021 19022 if (tintInfo.mHasTintMode) { 19023 mBackground.setTintMode(tintInfo.mTintMode); 19024 } 19025 19026 // The drawable (or one of its children) may not have been 19027 // stateful before applying the tint, so let's try again. 19028 if (mBackground.isStateful()) { 19029 mBackground.setState(getDrawableState()); 19030 } 19031 } 19032 } 19033 } 19034 19035 /** 19036 * Returns the drawable used as the foreground of this View. The 19037 * foreground drawable, if non-null, is always drawn on top of the view's content. 19038 * 19039 * @return a Drawable or null if no foreground was set 19040 * 19041 * @see #onDrawForeground(Canvas) 19042 */ 19043 public Drawable getForeground() { 19044 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19045 } 19046 19047 /** 19048 * Supply a Drawable that is to be rendered on top of all of the content in the view. 19049 * 19050 * @param foreground the Drawable to be drawn on top of the children 19051 * 19052 * @attr ref android.R.styleable#View_foreground 19053 */ 19054 public void setForeground(Drawable foreground) { 19055 if (mForegroundInfo == null) { 19056 if (foreground == null) { 19057 // Nothing to do. 19058 return; 19059 } 19060 mForegroundInfo = new ForegroundInfo(); 19061 } 19062 19063 if (foreground == mForegroundInfo.mDrawable) { 19064 // Nothing to do 19065 return; 19066 } 19067 19068 if (mForegroundInfo.mDrawable != null) { 19069 if (isAttachedToWindow()) { 19070 mForegroundInfo.mDrawable.setVisible(false, false); 19071 } 19072 mForegroundInfo.mDrawable.setCallback(null); 19073 unscheduleDrawable(mForegroundInfo.mDrawable); 19074 } 19075 19076 mForegroundInfo.mDrawable = foreground; 19077 mForegroundInfo.mBoundsChanged = true; 19078 if (foreground != null) { 19079 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 19080 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 19081 } 19082 foreground.setLayoutDirection(getLayoutDirection()); 19083 if (foreground.isStateful()) { 19084 foreground.setState(getDrawableState()); 19085 } 19086 applyForegroundTint(); 19087 if (isAttachedToWindow()) { 19088 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 19089 } 19090 // Set callback last, since the view may still be initializing. 19091 foreground.setCallback(this); 19092 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 19093 mPrivateFlags |= PFLAG_SKIP_DRAW; 19094 } 19095 requestLayout(); 19096 invalidate(); 19097 } 19098 19099 /** 19100 * Magic bit used to support features of framework-internal window decor implementation details. 19101 * This used to live exclusively in FrameLayout. 19102 * 19103 * @return true if the foreground should draw inside the padding region or false 19104 * if it should draw inset by the view's padding 19105 * @hide internal use only; only used by FrameLayout and internal screen layouts. 19106 */ 19107 public boolean isForegroundInsidePadding() { 19108 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 19109 } 19110 19111 /** 19112 * Describes how the foreground is positioned. 19113 * 19114 * @return foreground gravity. 19115 * 19116 * @see #setForegroundGravity(int) 19117 * 19118 * @attr ref android.R.styleable#View_foregroundGravity 19119 */ 19120 public int getForegroundGravity() { 19121 return mForegroundInfo != null ? mForegroundInfo.mGravity 19122 : Gravity.START | Gravity.TOP; 19123 } 19124 19125 /** 19126 * Describes how the foreground is positioned. Defaults to START and TOP. 19127 * 19128 * @param gravity see {@link android.view.Gravity} 19129 * 19130 * @see #getForegroundGravity() 19131 * 19132 * @attr ref android.R.styleable#View_foregroundGravity 19133 */ 19134 public void setForegroundGravity(int gravity) { 19135 if (mForegroundInfo == null) { 19136 mForegroundInfo = new ForegroundInfo(); 19137 } 19138 19139 if (mForegroundInfo.mGravity != gravity) { 19140 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 19141 gravity |= Gravity.START; 19142 } 19143 19144 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 19145 gravity |= Gravity.TOP; 19146 } 19147 19148 mForegroundInfo.mGravity = gravity; 19149 requestLayout(); 19150 } 19151 } 19152 19153 /** 19154 * Applies a tint to the foreground drawable. Does not modify the current tint 19155 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 19156 * <p> 19157 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 19158 * mutate the drawable and apply the specified tint and tint mode using 19159 * {@link Drawable#setTintList(ColorStateList)}. 19160 * 19161 * @param tint the tint to apply, may be {@code null} to clear tint 19162 * 19163 * @attr ref android.R.styleable#View_foregroundTint 19164 * @see #getForegroundTintList() 19165 * @see Drawable#setTintList(ColorStateList) 19166 */ 19167 public void setForegroundTintList(@Nullable ColorStateList tint) { 19168 if (mForegroundInfo == null) { 19169 mForegroundInfo = new ForegroundInfo(); 19170 } 19171 if (mForegroundInfo.mTintInfo == null) { 19172 mForegroundInfo.mTintInfo = new TintInfo(); 19173 } 19174 mForegroundInfo.mTintInfo.mTintList = tint; 19175 mForegroundInfo.mTintInfo.mHasTintList = true; 19176 19177 applyForegroundTint(); 19178 } 19179 19180 /** 19181 * Return the tint applied to the foreground drawable, if specified. 19182 * 19183 * @return the tint applied to the foreground drawable 19184 * @attr ref android.R.styleable#View_foregroundTint 19185 * @see #setForegroundTintList(ColorStateList) 19186 */ 19187 @Nullable 19188 public ColorStateList getForegroundTintList() { 19189 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 19190 ? mForegroundInfo.mTintInfo.mTintList : null; 19191 } 19192 19193 /** 19194 * Specifies the blending mode used to apply the tint specified by 19195 * {@link #setForegroundTintList(ColorStateList)}} to the background 19196 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 19197 * 19198 * @param tintMode the blending mode used to apply the tint, may be 19199 * {@code null} to clear tint 19200 * @attr ref android.R.styleable#View_foregroundTintMode 19201 * @see #getForegroundTintMode() 19202 * @see Drawable#setTintMode(PorterDuff.Mode) 19203 */ 19204 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 19205 if (mForegroundInfo == null) { 19206 mForegroundInfo = new ForegroundInfo(); 19207 } 19208 if (mForegroundInfo.mTintInfo == null) { 19209 mForegroundInfo.mTintInfo = new TintInfo(); 19210 } 19211 mForegroundInfo.mTintInfo.mTintMode = tintMode; 19212 mForegroundInfo.mTintInfo.mHasTintMode = true; 19213 19214 applyForegroundTint(); 19215 } 19216 19217 /** 19218 * Return the blending mode used to apply the tint to the foreground 19219 * drawable, if specified. 19220 * 19221 * @return the blending mode used to apply the tint to the foreground 19222 * drawable 19223 * @attr ref android.R.styleable#View_foregroundTintMode 19224 * @see #setForegroundTintMode(PorterDuff.Mode) 19225 */ 19226 @Nullable 19227 public PorterDuff.Mode getForegroundTintMode() { 19228 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 19229 ? mForegroundInfo.mTintInfo.mTintMode : null; 19230 } 19231 19232 private void applyForegroundTint() { 19233 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 19234 && mForegroundInfo.mTintInfo != null) { 19235 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 19236 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 19237 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 19238 19239 if (tintInfo.mHasTintList) { 19240 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 19241 } 19242 19243 if (tintInfo.mHasTintMode) { 19244 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 19245 } 19246 19247 // The drawable (or one of its children) may not have been 19248 // stateful before applying the tint, so let's try again. 19249 if (mForegroundInfo.mDrawable.isStateful()) { 19250 mForegroundInfo.mDrawable.setState(getDrawableState()); 19251 } 19252 } 19253 } 19254 } 19255 19256 /** 19257 * Draw any foreground content for this view. 19258 * 19259 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 19260 * drawable or other view-specific decorations. The foreground is drawn on top of the 19261 * primary view content.</p> 19262 * 19263 * @param canvas canvas to draw into 19264 */ 19265 public void onDrawForeground(Canvas canvas) { 19266 onDrawScrollIndicators(canvas); 19267 onDrawScrollBars(canvas); 19268 19269 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19270 if (foreground != null) { 19271 if (mForegroundInfo.mBoundsChanged) { 19272 mForegroundInfo.mBoundsChanged = false; 19273 final Rect selfBounds = mForegroundInfo.mSelfBounds; 19274 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 19275 19276 if (mForegroundInfo.mInsidePadding) { 19277 selfBounds.set(0, 0, getWidth(), getHeight()); 19278 } else { 19279 selfBounds.set(getPaddingLeft(), getPaddingTop(), 19280 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 19281 } 19282 19283 final int ld = getLayoutDirection(); 19284 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 19285 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 19286 foreground.setBounds(overlayBounds); 19287 } 19288 19289 foreground.draw(canvas); 19290 } 19291 } 19292 19293 /** 19294 * Sets the padding. The view may add on the space required to display 19295 * the scrollbars, depending on the style and visibility of the scrollbars. 19296 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 19297 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 19298 * from the values set in this call. 19299 * 19300 * @attr ref android.R.styleable#View_padding 19301 * @attr ref android.R.styleable#View_paddingBottom 19302 * @attr ref android.R.styleable#View_paddingLeft 19303 * @attr ref android.R.styleable#View_paddingRight 19304 * @attr ref android.R.styleable#View_paddingTop 19305 * @param left the left padding in pixels 19306 * @param top the top padding in pixels 19307 * @param right the right padding in pixels 19308 * @param bottom the bottom padding in pixels 19309 */ 19310 public void setPadding(int left, int top, int right, int bottom) { 19311 resetResolvedPaddingInternal(); 19312 19313 mUserPaddingStart = UNDEFINED_PADDING; 19314 mUserPaddingEnd = UNDEFINED_PADDING; 19315 19316 mUserPaddingLeftInitial = left; 19317 mUserPaddingRightInitial = right; 19318 19319 mLeftPaddingDefined = true; 19320 mRightPaddingDefined = true; 19321 19322 internalSetPadding(left, top, right, bottom); 19323 } 19324 19325 /** 19326 * @hide 19327 */ 19328 protected void internalSetPadding(int left, int top, int right, int bottom) { 19329 mUserPaddingLeft = left; 19330 mUserPaddingRight = right; 19331 mUserPaddingBottom = bottom; 19332 19333 final int viewFlags = mViewFlags; 19334 boolean changed = false; 19335 19336 // Common case is there are no scroll bars. 19337 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 19338 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 19339 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 19340 ? 0 : getVerticalScrollbarWidth(); 19341 switch (mVerticalScrollbarPosition) { 19342 case SCROLLBAR_POSITION_DEFAULT: 19343 if (isLayoutRtl()) { 19344 left += offset; 19345 } else { 19346 right += offset; 19347 } 19348 break; 19349 case SCROLLBAR_POSITION_RIGHT: 19350 right += offset; 19351 break; 19352 case SCROLLBAR_POSITION_LEFT: 19353 left += offset; 19354 break; 19355 } 19356 } 19357 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 19358 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 19359 ? 0 : getHorizontalScrollbarHeight(); 19360 } 19361 } 19362 19363 if (mPaddingLeft != left) { 19364 changed = true; 19365 mPaddingLeft = left; 19366 } 19367 if (mPaddingTop != top) { 19368 changed = true; 19369 mPaddingTop = top; 19370 } 19371 if (mPaddingRight != right) { 19372 changed = true; 19373 mPaddingRight = right; 19374 } 19375 if (mPaddingBottom != bottom) { 19376 changed = true; 19377 mPaddingBottom = bottom; 19378 } 19379 19380 if (changed) { 19381 requestLayout(); 19382 invalidateOutline(); 19383 } 19384 } 19385 19386 /** 19387 * Sets the relative padding. The view may add on the space required to display 19388 * the scrollbars, depending on the style and visibility of the scrollbars. 19389 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 19390 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 19391 * from the values set in this call. 19392 * 19393 * @attr ref android.R.styleable#View_padding 19394 * @attr ref android.R.styleable#View_paddingBottom 19395 * @attr ref android.R.styleable#View_paddingStart 19396 * @attr ref android.R.styleable#View_paddingEnd 19397 * @attr ref android.R.styleable#View_paddingTop 19398 * @param start the start padding in pixels 19399 * @param top the top padding in pixels 19400 * @param end the end padding in pixels 19401 * @param bottom the bottom padding in pixels 19402 */ 19403 public void setPaddingRelative(int start, int top, int end, int bottom) { 19404 resetResolvedPaddingInternal(); 19405 19406 mUserPaddingStart = start; 19407 mUserPaddingEnd = end; 19408 mLeftPaddingDefined = true; 19409 mRightPaddingDefined = true; 19410 19411 switch(getLayoutDirection()) { 19412 case LAYOUT_DIRECTION_RTL: 19413 mUserPaddingLeftInitial = end; 19414 mUserPaddingRightInitial = start; 19415 internalSetPadding(end, top, start, bottom); 19416 break; 19417 case LAYOUT_DIRECTION_LTR: 19418 default: 19419 mUserPaddingLeftInitial = start; 19420 mUserPaddingRightInitial = end; 19421 internalSetPadding(start, top, end, bottom); 19422 } 19423 } 19424 19425 /** 19426 * Returns the top padding of this view. 19427 * 19428 * @return the top padding in pixels 19429 */ 19430 public int getPaddingTop() { 19431 return mPaddingTop; 19432 } 19433 19434 /** 19435 * Returns the bottom padding of this view. If there are inset and enabled 19436 * scrollbars, this value may include the space required to display the 19437 * scrollbars as well. 19438 * 19439 * @return the bottom padding in pixels 19440 */ 19441 public int getPaddingBottom() { 19442 return mPaddingBottom; 19443 } 19444 19445 /** 19446 * Returns the left padding of this view. If there are inset and enabled 19447 * scrollbars, this value may include the space required to display the 19448 * scrollbars as well. 19449 * 19450 * @return the left padding in pixels 19451 */ 19452 public int getPaddingLeft() { 19453 if (!isPaddingResolved()) { 19454 resolvePadding(); 19455 } 19456 return mPaddingLeft; 19457 } 19458 19459 /** 19460 * Returns the start padding of this view depending on its resolved layout direction. 19461 * If there are inset and enabled scrollbars, this value may include the space 19462 * required to display the scrollbars as well. 19463 * 19464 * @return the start padding in pixels 19465 */ 19466 public int getPaddingStart() { 19467 if (!isPaddingResolved()) { 19468 resolvePadding(); 19469 } 19470 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 19471 mPaddingRight : mPaddingLeft; 19472 } 19473 19474 /** 19475 * Returns the right padding of this view. If there are inset and enabled 19476 * scrollbars, this value may include the space required to display the 19477 * scrollbars as well. 19478 * 19479 * @return the right padding in pixels 19480 */ 19481 public int getPaddingRight() { 19482 if (!isPaddingResolved()) { 19483 resolvePadding(); 19484 } 19485 return mPaddingRight; 19486 } 19487 19488 /** 19489 * Returns the end padding of this view depending on its resolved layout direction. 19490 * If there are inset and enabled scrollbars, this value may include the space 19491 * required to display the scrollbars as well. 19492 * 19493 * @return the end padding in pixels 19494 */ 19495 public int getPaddingEnd() { 19496 if (!isPaddingResolved()) { 19497 resolvePadding(); 19498 } 19499 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 19500 mPaddingLeft : mPaddingRight; 19501 } 19502 19503 /** 19504 * Return if the padding has been set through relative values 19505 * {@link #setPaddingRelative(int, int, int, int)} or through 19506 * @attr ref android.R.styleable#View_paddingStart or 19507 * @attr ref android.R.styleable#View_paddingEnd 19508 * 19509 * @return true if the padding is relative or false if it is not. 19510 */ 19511 public boolean isPaddingRelative() { 19512 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 19513 } 19514 19515 Insets computeOpticalInsets() { 19516 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 19517 } 19518 19519 /** 19520 * @hide 19521 */ 19522 public void resetPaddingToInitialValues() { 19523 if (isRtlCompatibilityMode()) { 19524 mPaddingLeft = mUserPaddingLeftInitial; 19525 mPaddingRight = mUserPaddingRightInitial; 19526 return; 19527 } 19528 if (isLayoutRtl()) { 19529 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 19530 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 19531 } else { 19532 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 19533 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 19534 } 19535 } 19536 19537 /** 19538 * @hide 19539 */ 19540 public Insets getOpticalInsets() { 19541 if (mLayoutInsets == null) { 19542 mLayoutInsets = computeOpticalInsets(); 19543 } 19544 return mLayoutInsets; 19545 } 19546 19547 /** 19548 * Set this view's optical insets. 19549 * 19550 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 19551 * property. Views that compute their own optical insets should call it as part of measurement. 19552 * This method does not request layout. If you are setting optical insets outside of 19553 * measure/layout itself you will want to call requestLayout() yourself. 19554 * </p> 19555 * @hide 19556 */ 19557 public void setOpticalInsets(Insets insets) { 19558 mLayoutInsets = insets; 19559 } 19560 19561 /** 19562 * Changes the selection state of this view. A view can be selected or not. 19563 * Note that selection is not the same as focus. Views are typically 19564 * selected in the context of an AdapterView like ListView or GridView; 19565 * the selected view is the view that is highlighted. 19566 * 19567 * @param selected true if the view must be selected, false otherwise 19568 */ 19569 public void setSelected(boolean selected) { 19570 //noinspection DoubleNegation 19571 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 19572 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 19573 if (!selected) resetPressedState(); 19574 invalidate(true); 19575 refreshDrawableState(); 19576 dispatchSetSelected(selected); 19577 if (selected) { 19578 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 19579 } else { 19580 notifyViewAccessibilityStateChangedIfNeeded( 19581 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 19582 } 19583 } 19584 } 19585 19586 /** 19587 * Dispatch setSelected to all of this View's children. 19588 * 19589 * @see #setSelected(boolean) 19590 * 19591 * @param selected The new selected state 19592 */ 19593 protected void dispatchSetSelected(boolean selected) { 19594 } 19595 19596 /** 19597 * Indicates the selection state of this view. 19598 * 19599 * @return true if the view is selected, false otherwise 19600 */ 19601 @ViewDebug.ExportedProperty 19602 public boolean isSelected() { 19603 return (mPrivateFlags & PFLAG_SELECTED) != 0; 19604 } 19605 19606 /** 19607 * Changes the activated state of this view. A view can be activated or not. 19608 * Note that activation is not the same as selection. Selection is 19609 * a transient property, representing the view (hierarchy) the user is 19610 * currently interacting with. Activation is a longer-term state that the 19611 * user can move views in and out of. For example, in a list view with 19612 * single or multiple selection enabled, the views in the current selection 19613 * set are activated. (Um, yeah, we are deeply sorry about the terminology 19614 * here.) The activated state is propagated down to children of the view it 19615 * is set on. 19616 * 19617 * @param activated true if the view must be activated, false otherwise 19618 */ 19619 public void setActivated(boolean activated) { 19620 //noinspection DoubleNegation 19621 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 19622 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 19623 invalidate(true); 19624 refreshDrawableState(); 19625 dispatchSetActivated(activated); 19626 } 19627 } 19628 19629 /** 19630 * Dispatch setActivated to all of this View's children. 19631 * 19632 * @see #setActivated(boolean) 19633 * 19634 * @param activated The new activated state 19635 */ 19636 protected void dispatchSetActivated(boolean activated) { 19637 } 19638 19639 /** 19640 * Indicates the activation state of this view. 19641 * 19642 * @return true if the view is activated, false otherwise 19643 */ 19644 @ViewDebug.ExportedProperty 19645 public boolean isActivated() { 19646 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 19647 } 19648 19649 /** 19650 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 19651 * observer can be used to get notifications when global events, like 19652 * layout, happen. 19653 * 19654 * The returned ViewTreeObserver observer is not guaranteed to remain 19655 * valid for the lifetime of this View. If the caller of this method keeps 19656 * a long-lived reference to ViewTreeObserver, it should always check for 19657 * the return value of {@link ViewTreeObserver#isAlive()}. 19658 * 19659 * @return The ViewTreeObserver for this view's hierarchy. 19660 */ 19661 public ViewTreeObserver getViewTreeObserver() { 19662 if (mAttachInfo != null) { 19663 return mAttachInfo.mTreeObserver; 19664 } 19665 if (mFloatingTreeObserver == null) { 19666 mFloatingTreeObserver = new ViewTreeObserver(mContext); 19667 } 19668 return mFloatingTreeObserver; 19669 } 19670 19671 /** 19672 * <p>Finds the topmost view in the current view hierarchy.</p> 19673 * 19674 * @return the topmost view containing this view 19675 */ 19676 public View getRootView() { 19677 if (mAttachInfo != null) { 19678 final View v = mAttachInfo.mRootView; 19679 if (v != null) { 19680 return v; 19681 } 19682 } 19683 19684 View parent = this; 19685 19686 while (parent.mParent != null && parent.mParent instanceof View) { 19687 parent = (View) parent.mParent; 19688 } 19689 19690 return parent; 19691 } 19692 19693 /** 19694 * Transforms a motion event from view-local coordinates to on-screen 19695 * coordinates. 19696 * 19697 * @param ev the view-local motion event 19698 * @return false if the transformation could not be applied 19699 * @hide 19700 */ 19701 public boolean toGlobalMotionEvent(MotionEvent ev) { 19702 final AttachInfo info = mAttachInfo; 19703 if (info == null) { 19704 return false; 19705 } 19706 19707 final Matrix m = info.mTmpMatrix; 19708 m.set(Matrix.IDENTITY_MATRIX); 19709 transformMatrixToGlobal(m); 19710 ev.transform(m); 19711 return true; 19712 } 19713 19714 /** 19715 * Transforms a motion event from on-screen coordinates to view-local 19716 * coordinates. 19717 * 19718 * @param ev the on-screen motion event 19719 * @return false if the transformation could not be applied 19720 * @hide 19721 */ 19722 public boolean toLocalMotionEvent(MotionEvent ev) { 19723 final AttachInfo info = mAttachInfo; 19724 if (info == null) { 19725 return false; 19726 } 19727 19728 final Matrix m = info.mTmpMatrix; 19729 m.set(Matrix.IDENTITY_MATRIX); 19730 transformMatrixToLocal(m); 19731 ev.transform(m); 19732 return true; 19733 } 19734 19735 /** 19736 * Modifies the input matrix such that it maps view-local coordinates to 19737 * on-screen coordinates. 19738 * 19739 * @param m input matrix to modify 19740 * @hide 19741 */ 19742 public void transformMatrixToGlobal(Matrix m) { 19743 final ViewParent parent = mParent; 19744 if (parent instanceof View) { 19745 final View vp = (View) parent; 19746 vp.transformMatrixToGlobal(m); 19747 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19748 } else if (parent instanceof ViewRootImpl) { 19749 final ViewRootImpl vr = (ViewRootImpl) parent; 19750 vr.transformMatrixToGlobal(m); 19751 m.preTranslate(0, -vr.mCurScrollY); 19752 } 19753 19754 m.preTranslate(mLeft, mTop); 19755 19756 if (!hasIdentityMatrix()) { 19757 m.preConcat(getMatrix()); 19758 } 19759 } 19760 19761 /** 19762 * Modifies the input matrix such that it maps on-screen coordinates to 19763 * view-local coordinates. 19764 * 19765 * @param m input matrix to modify 19766 * @hide 19767 */ 19768 public void transformMatrixToLocal(Matrix m) { 19769 final ViewParent parent = mParent; 19770 if (parent instanceof View) { 19771 final View vp = (View) parent; 19772 vp.transformMatrixToLocal(m); 19773 m.postTranslate(vp.mScrollX, vp.mScrollY); 19774 } else if (parent instanceof ViewRootImpl) { 19775 final ViewRootImpl vr = (ViewRootImpl) parent; 19776 vr.transformMatrixToLocal(m); 19777 m.postTranslate(0, vr.mCurScrollY); 19778 } 19779 19780 m.postTranslate(-mLeft, -mTop); 19781 19782 if (!hasIdentityMatrix()) { 19783 m.postConcat(getInverseMatrix()); 19784 } 19785 } 19786 19787 /** 19788 * @hide 19789 */ 19790 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19791 @ViewDebug.IntToString(from = 0, to = "x"), 19792 @ViewDebug.IntToString(from = 1, to = "y") 19793 }) 19794 public int[] getLocationOnScreen() { 19795 int[] location = new int[2]; 19796 getLocationOnScreen(location); 19797 return location; 19798 } 19799 19800 /** 19801 * <p>Computes the coordinates of this view on the screen. The argument 19802 * must be an array of two integers. After the method returns, the array 19803 * contains the x and y location in that order.</p> 19804 * 19805 * @param outLocation an array of two integers in which to hold the coordinates 19806 */ 19807 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19808 getLocationInWindow(outLocation); 19809 19810 final AttachInfo info = mAttachInfo; 19811 if (info != null) { 19812 outLocation[0] += info.mWindowLeft; 19813 outLocation[1] += info.mWindowTop; 19814 } 19815 } 19816 19817 /** 19818 * <p>Computes the coordinates of this view in its window. The argument 19819 * must be an array of two integers. After the method returns, the array 19820 * contains the x and y location in that order.</p> 19821 * 19822 * @param outLocation an array of two integers in which to hold the coordinates 19823 */ 19824 public void getLocationInWindow(@Size(2) int[] outLocation) { 19825 if (outLocation == null || outLocation.length < 2) { 19826 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19827 } 19828 19829 outLocation[0] = 0; 19830 outLocation[1] = 0; 19831 19832 transformFromViewToWindowSpace(outLocation); 19833 } 19834 19835 /** @hide */ 19836 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19837 if (inOutLocation == null || inOutLocation.length < 2) { 19838 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19839 } 19840 19841 if (mAttachInfo == null) { 19842 // When the view is not attached to a window, this method does not make sense 19843 inOutLocation[0] = inOutLocation[1] = 0; 19844 return; 19845 } 19846 19847 float position[] = mAttachInfo.mTmpTransformLocation; 19848 position[0] = inOutLocation[0]; 19849 position[1] = inOutLocation[1]; 19850 19851 if (!hasIdentityMatrix()) { 19852 getMatrix().mapPoints(position); 19853 } 19854 19855 position[0] += mLeft; 19856 position[1] += mTop; 19857 19858 ViewParent viewParent = mParent; 19859 while (viewParent instanceof View) { 19860 final View view = (View) viewParent; 19861 19862 position[0] -= view.mScrollX; 19863 position[1] -= view.mScrollY; 19864 19865 if (!view.hasIdentityMatrix()) { 19866 view.getMatrix().mapPoints(position); 19867 } 19868 19869 position[0] += view.mLeft; 19870 position[1] += view.mTop; 19871 19872 viewParent = view.mParent; 19873 } 19874 19875 if (viewParent instanceof ViewRootImpl) { 19876 // *cough* 19877 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19878 position[1] -= vr.mCurScrollY; 19879 } 19880 19881 inOutLocation[0] = Math.round(position[0]); 19882 inOutLocation[1] = Math.round(position[1]); 19883 } 19884 19885 /** 19886 * {@hide} 19887 * @param id the id of the view to be found 19888 * @return the view of the specified id, null if cannot be found 19889 */ 19890 protected View findViewTraversal(@IdRes int id) { 19891 if (id == mID) { 19892 return this; 19893 } 19894 return null; 19895 } 19896 19897 /** 19898 * {@hide} 19899 * @param tag the tag of the view to be found 19900 * @return the view of specified tag, null if cannot be found 19901 */ 19902 protected View findViewWithTagTraversal(Object tag) { 19903 if (tag != null && tag.equals(mTag)) { 19904 return this; 19905 } 19906 return null; 19907 } 19908 19909 /** 19910 * {@hide} 19911 * @param predicate The predicate to evaluate. 19912 * @param childToSkip If not null, ignores this child during the recursive traversal. 19913 * @return The first view that matches the predicate or null. 19914 */ 19915 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19916 if (predicate.apply(this)) { 19917 return this; 19918 } 19919 return null; 19920 } 19921 19922 /** 19923 * Look for a child view with the given id. If this view has the given 19924 * id, return this view. 19925 * 19926 * @param id The id to search for. 19927 * @return The view that has the given id in the hierarchy or null 19928 */ 19929 @Nullable 19930 public final View findViewById(@IdRes int id) { 19931 if (id < 0) { 19932 return null; 19933 } 19934 return findViewTraversal(id); 19935 } 19936 19937 /** 19938 * Finds a view by its unuque and stable accessibility id. 19939 * 19940 * @param accessibilityId The searched accessibility id. 19941 * @return The found view. 19942 */ 19943 final View findViewByAccessibilityId(int accessibilityId) { 19944 if (accessibilityId < 0) { 19945 return null; 19946 } 19947 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19948 if (view != null) { 19949 return view.includeForAccessibility() ? view : null; 19950 } 19951 return null; 19952 } 19953 19954 /** 19955 * Performs the traversal to find a view by its unuque and stable accessibility id. 19956 * 19957 * <strong>Note:</strong>This method does not stop at the root namespace 19958 * boundary since the user can touch the screen at an arbitrary location 19959 * potentially crossing the root namespace bounday which will send an 19960 * accessibility event to accessibility services and they should be able 19961 * to obtain the event source. Also accessibility ids are guaranteed to be 19962 * unique in the window. 19963 * 19964 * @param accessibilityId The accessibility id. 19965 * @return The found view. 19966 * 19967 * @hide 19968 */ 19969 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19970 if (getAccessibilityViewId() == accessibilityId) { 19971 return this; 19972 } 19973 return null; 19974 } 19975 19976 /** 19977 * Look for a child view with the given tag. If this view has the given 19978 * tag, return this view. 19979 * 19980 * @param tag The tag to search for, using "tag.equals(getTag())". 19981 * @return The View that has the given tag in the hierarchy or null 19982 */ 19983 public final View findViewWithTag(Object tag) { 19984 if (tag == null) { 19985 return null; 19986 } 19987 return findViewWithTagTraversal(tag); 19988 } 19989 19990 /** 19991 * {@hide} 19992 * Look for a child view that matches the specified predicate. 19993 * If this view matches the predicate, return this view. 19994 * 19995 * @param predicate The predicate to evaluate. 19996 * @return The first view that matches the predicate or null. 19997 */ 19998 public final View findViewByPredicate(Predicate<View> predicate) { 19999 return findViewByPredicateTraversal(predicate, null); 20000 } 20001 20002 /** 20003 * {@hide} 20004 * Look for a child view that matches the specified predicate, 20005 * starting with the specified view and its descendents and then 20006 * recusively searching the ancestors and siblings of that view 20007 * until this view is reached. 20008 * 20009 * This method is useful in cases where the predicate does not match 20010 * a single unique view (perhaps multiple views use the same id) 20011 * and we are trying to find the view that is "closest" in scope to the 20012 * starting view. 20013 * 20014 * @param start The view to start from. 20015 * @param predicate The predicate to evaluate. 20016 * @return The first view that matches the predicate or null. 20017 */ 20018 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 20019 View childToSkip = null; 20020 for (;;) { 20021 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 20022 if (view != null || start == this) { 20023 return view; 20024 } 20025 20026 ViewParent parent = start.getParent(); 20027 if (parent == null || !(parent instanceof View)) { 20028 return null; 20029 } 20030 20031 childToSkip = start; 20032 start = (View) parent; 20033 } 20034 } 20035 20036 /** 20037 * Sets the identifier for this view. The identifier does not have to be 20038 * unique in this view's hierarchy. The identifier should be a positive 20039 * number. 20040 * 20041 * @see #NO_ID 20042 * @see #getId() 20043 * @see #findViewById(int) 20044 * 20045 * @param id a number used to identify the view 20046 * 20047 * @attr ref android.R.styleable#View_id 20048 */ 20049 public void setId(@IdRes int id) { 20050 mID = id; 20051 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 20052 mID = generateViewId(); 20053 } 20054 } 20055 20056 /** 20057 * {@hide} 20058 * 20059 * @param isRoot true if the view belongs to the root namespace, false 20060 * otherwise 20061 */ 20062 public void setIsRootNamespace(boolean isRoot) { 20063 if (isRoot) { 20064 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 20065 } else { 20066 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 20067 } 20068 } 20069 20070 /** 20071 * {@hide} 20072 * 20073 * @return true if the view belongs to the root namespace, false otherwise 20074 */ 20075 public boolean isRootNamespace() { 20076 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 20077 } 20078 20079 /** 20080 * Returns this view's identifier. 20081 * 20082 * @return a positive integer used to identify the view or {@link #NO_ID} 20083 * if the view has no ID 20084 * 20085 * @see #setId(int) 20086 * @see #findViewById(int) 20087 * @attr ref android.R.styleable#View_id 20088 */ 20089 @IdRes 20090 @ViewDebug.CapturedViewProperty 20091 public int getId() { 20092 return mID; 20093 } 20094 20095 /** 20096 * Returns this view's tag. 20097 * 20098 * @return the Object stored in this view as a tag, or {@code null} if not 20099 * set 20100 * 20101 * @see #setTag(Object) 20102 * @see #getTag(int) 20103 */ 20104 @ViewDebug.ExportedProperty 20105 public Object getTag() { 20106 return mTag; 20107 } 20108 20109 /** 20110 * Sets the tag associated with this view. A tag can be used to mark 20111 * a view in its hierarchy and does not have to be unique within the 20112 * hierarchy. Tags can also be used to store data within a view without 20113 * resorting to another data structure. 20114 * 20115 * @param tag an Object to tag the view with 20116 * 20117 * @see #getTag() 20118 * @see #setTag(int, Object) 20119 */ 20120 public void setTag(final Object tag) { 20121 mTag = tag; 20122 } 20123 20124 /** 20125 * Returns the tag associated with this view and the specified key. 20126 * 20127 * @param key The key identifying the tag 20128 * 20129 * @return the Object stored in this view as a tag, or {@code null} if not 20130 * set 20131 * 20132 * @see #setTag(int, Object) 20133 * @see #getTag() 20134 */ 20135 public Object getTag(int key) { 20136 if (mKeyedTags != null) return mKeyedTags.get(key); 20137 return null; 20138 } 20139 20140 /** 20141 * Sets a tag associated with this view and a key. A tag can be used 20142 * to mark a view in its hierarchy and does not have to be unique within 20143 * the hierarchy. Tags can also be used to store data within a view 20144 * without resorting to another data structure. 20145 * 20146 * The specified key should be an id declared in the resources of the 20147 * application to ensure it is unique (see the <a 20148 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 20149 * Keys identified as belonging to 20150 * the Android framework or not associated with any package will cause 20151 * an {@link IllegalArgumentException} to be thrown. 20152 * 20153 * @param key The key identifying the tag 20154 * @param tag An Object to tag the view with 20155 * 20156 * @throws IllegalArgumentException If they specified key is not valid 20157 * 20158 * @see #setTag(Object) 20159 * @see #getTag(int) 20160 */ 20161 public void setTag(int key, final Object tag) { 20162 // If the package id is 0x00 or 0x01, it's either an undefined package 20163 // or a framework id 20164 if ((key >>> 24) < 2) { 20165 throw new IllegalArgumentException("The key must be an application-specific " 20166 + "resource id."); 20167 } 20168 20169 setKeyedTag(key, tag); 20170 } 20171 20172 /** 20173 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 20174 * framework id. 20175 * 20176 * @hide 20177 */ 20178 public void setTagInternal(int key, Object tag) { 20179 if ((key >>> 24) != 0x1) { 20180 throw new IllegalArgumentException("The key must be a framework-specific " 20181 + "resource id."); 20182 } 20183 20184 setKeyedTag(key, tag); 20185 } 20186 20187 private void setKeyedTag(int key, Object tag) { 20188 if (mKeyedTags == null) { 20189 mKeyedTags = new SparseArray<Object>(2); 20190 } 20191 20192 mKeyedTags.put(key, tag); 20193 } 20194 20195 /** 20196 * Prints information about this view in the log output, with the tag 20197 * {@link #VIEW_LOG_TAG}. 20198 * 20199 * @hide 20200 */ 20201 public void debug() { 20202 debug(0); 20203 } 20204 20205 /** 20206 * Prints information about this view in the log output, with the tag 20207 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 20208 * indentation defined by the <code>depth</code>. 20209 * 20210 * @param depth the indentation level 20211 * 20212 * @hide 20213 */ 20214 protected void debug(int depth) { 20215 String output = debugIndent(depth - 1); 20216 20217 output += "+ " + this; 20218 int id = getId(); 20219 if (id != -1) { 20220 output += " (id=" + id + ")"; 20221 } 20222 Object tag = getTag(); 20223 if (tag != null) { 20224 output += " (tag=" + tag + ")"; 20225 } 20226 Log.d(VIEW_LOG_TAG, output); 20227 20228 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 20229 output = debugIndent(depth) + " FOCUSED"; 20230 Log.d(VIEW_LOG_TAG, output); 20231 } 20232 20233 output = debugIndent(depth); 20234 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 20235 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 20236 + "} "; 20237 Log.d(VIEW_LOG_TAG, output); 20238 20239 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 20240 || mPaddingBottom != 0) { 20241 output = debugIndent(depth); 20242 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 20243 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 20244 Log.d(VIEW_LOG_TAG, output); 20245 } 20246 20247 output = debugIndent(depth); 20248 output += "mMeasureWidth=" + mMeasuredWidth + 20249 " mMeasureHeight=" + mMeasuredHeight; 20250 Log.d(VIEW_LOG_TAG, output); 20251 20252 output = debugIndent(depth); 20253 if (mLayoutParams == null) { 20254 output += "BAD! no layout params"; 20255 } else { 20256 output = mLayoutParams.debug(output); 20257 } 20258 Log.d(VIEW_LOG_TAG, output); 20259 20260 output = debugIndent(depth); 20261 output += "flags={"; 20262 output += View.printFlags(mViewFlags); 20263 output += "}"; 20264 Log.d(VIEW_LOG_TAG, output); 20265 20266 output = debugIndent(depth); 20267 output += "privateFlags={"; 20268 output += View.printPrivateFlags(mPrivateFlags); 20269 output += "}"; 20270 Log.d(VIEW_LOG_TAG, output); 20271 } 20272 20273 /** 20274 * Creates a string of whitespaces used for indentation. 20275 * 20276 * @param depth the indentation level 20277 * @return a String containing (depth * 2 + 3) * 2 white spaces 20278 * 20279 * @hide 20280 */ 20281 protected static String debugIndent(int depth) { 20282 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 20283 for (int i = 0; i < (depth * 2) + 3; i++) { 20284 spaces.append(' ').append(' '); 20285 } 20286 return spaces.toString(); 20287 } 20288 20289 /** 20290 * <p>Return the offset of the widget's text baseline from the widget's top 20291 * boundary. If this widget does not support baseline alignment, this 20292 * method returns -1. </p> 20293 * 20294 * @return the offset of the baseline within the widget's bounds or -1 20295 * if baseline alignment is not supported 20296 */ 20297 @ViewDebug.ExportedProperty(category = "layout") 20298 public int getBaseline() { 20299 return -1; 20300 } 20301 20302 /** 20303 * Returns whether the view hierarchy is currently undergoing a layout pass. This 20304 * information is useful to avoid situations such as calling {@link #requestLayout()} during 20305 * a layout pass. 20306 * 20307 * @return whether the view hierarchy is currently undergoing a layout pass 20308 */ 20309 public boolean isInLayout() { 20310 ViewRootImpl viewRoot = getViewRootImpl(); 20311 return (viewRoot != null && viewRoot.isInLayout()); 20312 } 20313 20314 /** 20315 * Call this when something has changed which has invalidated the 20316 * layout of this view. This will schedule a layout pass of the view 20317 * tree. This should not be called while the view hierarchy is currently in a layout 20318 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 20319 * end of the current layout pass (and then layout will run again) or after the current 20320 * frame is drawn and the next layout occurs. 20321 * 20322 * <p>Subclasses which override this method should call the superclass method to 20323 * handle possible request-during-layout errors correctly.</p> 20324 */ 20325 @CallSuper 20326 public void requestLayout() { 20327 if (mMeasureCache != null) mMeasureCache.clear(); 20328 20329 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 20330 // Only trigger request-during-layout logic if this is the view requesting it, 20331 // not the views in its parent hierarchy 20332 ViewRootImpl viewRoot = getViewRootImpl(); 20333 if (viewRoot != null && viewRoot.isInLayout()) { 20334 if (!viewRoot.requestLayoutDuringLayout(this)) { 20335 return; 20336 } 20337 } 20338 mAttachInfo.mViewRequestingLayout = this; 20339 } 20340 20341 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 20342 mPrivateFlags |= PFLAG_INVALIDATED; 20343 20344 if (mParent != null && !mParent.isLayoutRequested()) { 20345 mParent.requestLayout(); 20346 } 20347 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 20348 mAttachInfo.mViewRequestingLayout = null; 20349 } 20350 } 20351 20352 /** 20353 * Forces this view to be laid out during the next layout pass. 20354 * This method does not call requestLayout() or forceLayout() 20355 * on the parent. 20356 */ 20357 public void forceLayout() { 20358 if (mMeasureCache != null) mMeasureCache.clear(); 20359 20360 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 20361 mPrivateFlags |= PFLAG_INVALIDATED; 20362 } 20363 20364 /** 20365 * <p> 20366 * This is called to find out how big a view should be. The parent 20367 * supplies constraint information in the width and height parameters. 20368 * </p> 20369 * 20370 * <p> 20371 * The actual measurement work of a view is performed in 20372 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 20373 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 20374 * </p> 20375 * 20376 * 20377 * @param widthMeasureSpec Horizontal space requirements as imposed by the 20378 * parent 20379 * @param heightMeasureSpec Vertical space requirements as imposed by the 20380 * parent 20381 * 20382 * @see #onMeasure(int, int) 20383 */ 20384 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 20385 boolean optical = isLayoutModeOptical(this); 20386 if (optical != isLayoutModeOptical(mParent)) { 20387 Insets insets = getOpticalInsets(); 20388 int oWidth = insets.left + insets.right; 20389 int oHeight = insets.top + insets.bottom; 20390 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 20391 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 20392 } 20393 20394 // Suppress sign extension for the low bytes 20395 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 20396 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 20397 20398 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 20399 20400 // Optimize layout by avoiding an extra EXACTLY pass when the view is 20401 // already measured as the correct size. In API 23 and below, this 20402 // extra pass is required to make LinearLayout re-distribute weight. 20403 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 20404 || heightMeasureSpec != mOldHeightMeasureSpec; 20405 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 20406 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 20407 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 20408 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 20409 final boolean needsLayout = specChanged 20410 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 20411 20412 if (forceLayout || needsLayout) { 20413 // first clears the measured dimension flag 20414 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 20415 20416 resolveRtlPropertiesIfNeeded(); 20417 20418 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 20419 if (cacheIndex < 0 || sIgnoreMeasureCache) { 20420 // measure ourselves, this should set the measured dimension flag back 20421 onMeasure(widthMeasureSpec, heightMeasureSpec); 20422 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 20423 } else { 20424 long value = mMeasureCache.valueAt(cacheIndex); 20425 // Casting a long to int drops the high 32 bits, no mask needed 20426 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 20427 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 20428 } 20429 20430 // flag not set, setMeasuredDimension() was not invoked, we raise 20431 // an exception to warn the developer 20432 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 20433 throw new IllegalStateException("View with id " + getId() + ": " 20434 + getClass().getName() + "#onMeasure() did not set the" 20435 + " measured dimension by calling" 20436 + " setMeasuredDimension()"); 20437 } 20438 20439 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 20440 } 20441 20442 mOldWidthMeasureSpec = widthMeasureSpec; 20443 mOldHeightMeasureSpec = heightMeasureSpec; 20444 20445 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 20446 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 20447 } 20448 20449 /** 20450 * <p> 20451 * Measure the view and its content to determine the measured width and the 20452 * measured height. This method is invoked by {@link #measure(int, int)} and 20453 * should be overridden by subclasses to provide accurate and efficient 20454 * measurement of their contents. 20455 * </p> 20456 * 20457 * <p> 20458 * <strong>CONTRACT:</strong> When overriding this method, you 20459 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 20460 * measured width and height of this view. Failure to do so will trigger an 20461 * <code>IllegalStateException</code>, thrown by 20462 * {@link #measure(int, int)}. Calling the superclass' 20463 * {@link #onMeasure(int, int)} is a valid use. 20464 * </p> 20465 * 20466 * <p> 20467 * The base class implementation of measure defaults to the background size, 20468 * unless a larger size is allowed by the MeasureSpec. Subclasses should 20469 * override {@link #onMeasure(int, int)} to provide better measurements of 20470 * their content. 20471 * </p> 20472 * 20473 * <p> 20474 * If this method is overridden, it is the subclass's responsibility to make 20475 * sure the measured height and width are at least the view's minimum height 20476 * and width ({@link #getSuggestedMinimumHeight()} and 20477 * {@link #getSuggestedMinimumWidth()}). 20478 * </p> 20479 * 20480 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 20481 * The requirements are encoded with 20482 * {@link android.view.View.MeasureSpec}. 20483 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 20484 * The requirements are encoded with 20485 * {@link android.view.View.MeasureSpec}. 20486 * 20487 * @see #getMeasuredWidth() 20488 * @see #getMeasuredHeight() 20489 * @see #setMeasuredDimension(int, int) 20490 * @see #getSuggestedMinimumHeight() 20491 * @see #getSuggestedMinimumWidth() 20492 * @see android.view.View.MeasureSpec#getMode(int) 20493 * @see android.view.View.MeasureSpec#getSize(int) 20494 */ 20495 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 20496 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 20497 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 20498 } 20499 20500 /** 20501 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 20502 * measured width and measured height. Failing to do so will trigger an 20503 * exception at measurement time.</p> 20504 * 20505 * @param measuredWidth The measured width of this view. May be a complex 20506 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20507 * {@link #MEASURED_STATE_TOO_SMALL}. 20508 * @param measuredHeight The measured height of this view. May be a complex 20509 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20510 * {@link #MEASURED_STATE_TOO_SMALL}. 20511 */ 20512 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 20513 boolean optical = isLayoutModeOptical(this); 20514 if (optical != isLayoutModeOptical(mParent)) { 20515 Insets insets = getOpticalInsets(); 20516 int opticalWidth = insets.left + insets.right; 20517 int opticalHeight = insets.top + insets.bottom; 20518 20519 measuredWidth += optical ? opticalWidth : -opticalWidth; 20520 measuredHeight += optical ? opticalHeight : -opticalHeight; 20521 } 20522 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 20523 } 20524 20525 /** 20526 * Sets the measured dimension without extra processing for things like optical bounds. 20527 * Useful for reapplying consistent values that have already been cooked with adjustments 20528 * for optical bounds, etc. such as those from the measurement cache. 20529 * 20530 * @param measuredWidth The measured width of this view. May be a complex 20531 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20532 * {@link #MEASURED_STATE_TOO_SMALL}. 20533 * @param measuredHeight The measured height of this view. May be a complex 20534 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20535 * {@link #MEASURED_STATE_TOO_SMALL}. 20536 */ 20537 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 20538 mMeasuredWidth = measuredWidth; 20539 mMeasuredHeight = measuredHeight; 20540 20541 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 20542 } 20543 20544 /** 20545 * Merge two states as returned by {@link #getMeasuredState()}. 20546 * @param curState The current state as returned from a view or the result 20547 * of combining multiple views. 20548 * @param newState The new view state to combine. 20549 * @return Returns a new integer reflecting the combination of the two 20550 * states. 20551 */ 20552 public static int combineMeasuredStates(int curState, int newState) { 20553 return curState | newState; 20554 } 20555 20556 /** 20557 * Version of {@link #resolveSizeAndState(int, int, int)} 20558 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 20559 */ 20560 public static int resolveSize(int size, int measureSpec) { 20561 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 20562 } 20563 20564 /** 20565 * Utility to reconcile a desired size and state, with constraints imposed 20566 * by a MeasureSpec. Will take the desired size, unless a different size 20567 * is imposed by the constraints. The returned value is a compound integer, 20568 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 20569 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 20570 * resulting size is smaller than the size the view wants to be. 20571 * 20572 * @param size How big the view wants to be. 20573 * @param measureSpec Constraints imposed by the parent. 20574 * @param childMeasuredState Size information bit mask for the view's 20575 * children. 20576 * @return Size information bit mask as defined by 20577 * {@link #MEASURED_SIZE_MASK} and 20578 * {@link #MEASURED_STATE_TOO_SMALL}. 20579 */ 20580 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 20581 final int specMode = MeasureSpec.getMode(measureSpec); 20582 final int specSize = MeasureSpec.getSize(measureSpec); 20583 final int result; 20584 switch (specMode) { 20585 case MeasureSpec.AT_MOST: 20586 if (specSize < size) { 20587 result = specSize | MEASURED_STATE_TOO_SMALL; 20588 } else { 20589 result = size; 20590 } 20591 break; 20592 case MeasureSpec.EXACTLY: 20593 result = specSize; 20594 break; 20595 case MeasureSpec.UNSPECIFIED: 20596 default: 20597 result = size; 20598 } 20599 return result | (childMeasuredState & MEASURED_STATE_MASK); 20600 } 20601 20602 /** 20603 * Utility to return a default size. Uses the supplied size if the 20604 * MeasureSpec imposed no constraints. Will get larger if allowed 20605 * by the MeasureSpec. 20606 * 20607 * @param size Default size for this view 20608 * @param measureSpec Constraints imposed by the parent 20609 * @return The size this view should be. 20610 */ 20611 public static int getDefaultSize(int size, int measureSpec) { 20612 int result = size; 20613 int specMode = MeasureSpec.getMode(measureSpec); 20614 int specSize = MeasureSpec.getSize(measureSpec); 20615 20616 switch (specMode) { 20617 case MeasureSpec.UNSPECIFIED: 20618 result = size; 20619 break; 20620 case MeasureSpec.AT_MOST: 20621 case MeasureSpec.EXACTLY: 20622 result = specSize; 20623 break; 20624 } 20625 return result; 20626 } 20627 20628 /** 20629 * Returns the suggested minimum height that the view should use. This 20630 * returns the maximum of the view's minimum height 20631 * and the background's minimum height 20632 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 20633 * <p> 20634 * When being used in {@link #onMeasure(int, int)}, the caller should still 20635 * ensure the returned height is within the requirements of the parent. 20636 * 20637 * @return The suggested minimum height of the view. 20638 */ 20639 protected int getSuggestedMinimumHeight() { 20640 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 20641 20642 } 20643 20644 /** 20645 * Returns the suggested minimum width that the view should use. This 20646 * returns the maximum of the view's minimum width 20647 * and the background's minimum width 20648 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 20649 * <p> 20650 * When being used in {@link #onMeasure(int, int)}, the caller should still 20651 * ensure the returned width is within the requirements of the parent. 20652 * 20653 * @return The suggested minimum width of the view. 20654 */ 20655 protected int getSuggestedMinimumWidth() { 20656 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 20657 } 20658 20659 /** 20660 * Returns the minimum height of the view. 20661 * 20662 * @return the minimum height the view will try to be, in pixels 20663 * 20664 * @see #setMinimumHeight(int) 20665 * 20666 * @attr ref android.R.styleable#View_minHeight 20667 */ 20668 public int getMinimumHeight() { 20669 return mMinHeight; 20670 } 20671 20672 /** 20673 * Sets the minimum height of the view. It is not guaranteed the view will 20674 * be able to achieve this minimum height (for example, if its parent layout 20675 * constrains it with less available height). 20676 * 20677 * @param minHeight The minimum height the view will try to be, in pixels 20678 * 20679 * @see #getMinimumHeight() 20680 * 20681 * @attr ref android.R.styleable#View_minHeight 20682 */ 20683 @RemotableViewMethod 20684 public void setMinimumHeight(int minHeight) { 20685 mMinHeight = minHeight; 20686 requestLayout(); 20687 } 20688 20689 /** 20690 * Returns the minimum width of the view. 20691 * 20692 * @return the minimum width the view will try to be, in pixels 20693 * 20694 * @see #setMinimumWidth(int) 20695 * 20696 * @attr ref android.R.styleable#View_minWidth 20697 */ 20698 public int getMinimumWidth() { 20699 return mMinWidth; 20700 } 20701 20702 /** 20703 * Sets the minimum width of the view. It is not guaranteed the view will 20704 * be able to achieve this minimum width (for example, if its parent layout 20705 * constrains it with less available width). 20706 * 20707 * @param minWidth The minimum width the view will try to be, in pixels 20708 * 20709 * @see #getMinimumWidth() 20710 * 20711 * @attr ref android.R.styleable#View_minWidth 20712 */ 20713 public void setMinimumWidth(int minWidth) { 20714 mMinWidth = minWidth; 20715 requestLayout(); 20716 20717 } 20718 20719 /** 20720 * Get the animation currently associated with this view. 20721 * 20722 * @return The animation that is currently playing or 20723 * scheduled to play for this view. 20724 */ 20725 public Animation getAnimation() { 20726 return mCurrentAnimation; 20727 } 20728 20729 /** 20730 * Start the specified animation now. 20731 * 20732 * @param animation the animation to start now 20733 */ 20734 public void startAnimation(Animation animation) { 20735 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20736 setAnimation(animation); 20737 invalidateParentCaches(); 20738 invalidate(true); 20739 } 20740 20741 /** 20742 * Cancels any animations for this view. 20743 */ 20744 public void clearAnimation() { 20745 if (mCurrentAnimation != null) { 20746 mCurrentAnimation.detach(); 20747 } 20748 mCurrentAnimation = null; 20749 invalidateParentIfNeeded(); 20750 } 20751 20752 /** 20753 * Sets the next animation to play for this view. 20754 * If you want the animation to play immediately, use 20755 * {@link #startAnimation(android.view.animation.Animation)} instead. 20756 * This method provides allows fine-grained 20757 * control over the start time and invalidation, but you 20758 * must make sure that 1) the animation has a start time set, and 20759 * 2) the view's parent (which controls animations on its children) 20760 * will be invalidated when the animation is supposed to 20761 * start. 20762 * 20763 * @param animation The next animation, or null. 20764 */ 20765 public void setAnimation(Animation animation) { 20766 mCurrentAnimation = animation; 20767 20768 if (animation != null) { 20769 // If the screen is off assume the animation start time is now instead of 20770 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20771 // would cause the animation to start when the screen turns back on 20772 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20773 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20774 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20775 } 20776 animation.reset(); 20777 } 20778 } 20779 20780 /** 20781 * Invoked by a parent ViewGroup to notify the start of the animation 20782 * currently associated with this view. If you override this method, 20783 * always call super.onAnimationStart(); 20784 * 20785 * @see #setAnimation(android.view.animation.Animation) 20786 * @see #getAnimation() 20787 */ 20788 @CallSuper 20789 protected void onAnimationStart() { 20790 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20791 } 20792 20793 /** 20794 * Invoked by a parent ViewGroup to notify the end of the animation 20795 * currently associated with this view. If you override this method, 20796 * always call super.onAnimationEnd(); 20797 * 20798 * @see #setAnimation(android.view.animation.Animation) 20799 * @see #getAnimation() 20800 */ 20801 @CallSuper 20802 protected void onAnimationEnd() { 20803 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20804 } 20805 20806 /** 20807 * Invoked if there is a Transform that involves alpha. Subclass that can 20808 * draw themselves with the specified alpha should return true, and then 20809 * respect that alpha when their onDraw() is called. If this returns false 20810 * then the view may be redirected to draw into an offscreen buffer to 20811 * fulfill the request, which will look fine, but may be slower than if the 20812 * subclass handles it internally. The default implementation returns false. 20813 * 20814 * @param alpha The alpha (0..255) to apply to the view's drawing 20815 * @return true if the view can draw with the specified alpha. 20816 */ 20817 protected boolean onSetAlpha(int alpha) { 20818 return false; 20819 } 20820 20821 /** 20822 * This is used by the RootView to perform an optimization when 20823 * the view hierarchy contains one or several SurfaceView. 20824 * SurfaceView is always considered transparent, but its children are not, 20825 * therefore all View objects remove themselves from the global transparent 20826 * region (passed as a parameter to this function). 20827 * 20828 * @param region The transparent region for this ViewAncestor (window). 20829 * 20830 * @return Returns true if the effective visibility of the view at this 20831 * point is opaque, regardless of the transparent region; returns false 20832 * if it is possible for underlying windows to be seen behind the view. 20833 * 20834 * {@hide} 20835 */ 20836 public boolean gatherTransparentRegion(Region region) { 20837 final AttachInfo attachInfo = mAttachInfo; 20838 if (region != null && attachInfo != null) { 20839 final int pflags = mPrivateFlags; 20840 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20841 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20842 // remove it from the transparent region. 20843 final int[] location = attachInfo.mTransparentLocation; 20844 getLocationInWindow(location); 20845 // When a view has Z value, then it will be better to leave some area below the view 20846 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 20847 // the bottom part needs more offset than the left, top and right parts due to the 20848 // spot light effects. 20849 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 20850 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 20851 location[0] + mRight - mLeft + shadowOffset, 20852 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 20853 } else { 20854 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20855 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20856 // the background drawable's non-transparent parts from this transparent region. 20857 applyDrawableToTransparentRegion(mBackground, region); 20858 } 20859 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20860 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20861 // Similarly, we remove the foreground drawable's non-transparent parts. 20862 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20863 } 20864 } 20865 } 20866 return true; 20867 } 20868 20869 /** 20870 * Play a sound effect for this view. 20871 * 20872 * <p>The framework will play sound effects for some built in actions, such as 20873 * clicking, but you may wish to play these effects in your widget, 20874 * for instance, for internal navigation. 20875 * 20876 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20877 * {@link #isSoundEffectsEnabled()} is true. 20878 * 20879 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20880 */ 20881 public void playSoundEffect(int soundConstant) { 20882 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20883 return; 20884 } 20885 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20886 } 20887 20888 /** 20889 * BZZZTT!!1! 20890 * 20891 * <p>Provide haptic feedback to the user for this view. 20892 * 20893 * <p>The framework will provide haptic feedback for some built in actions, 20894 * such as long presses, but you may wish to provide feedback for your 20895 * own widget. 20896 * 20897 * <p>The feedback will only be performed if 20898 * {@link #isHapticFeedbackEnabled()} is true. 20899 * 20900 * @param feedbackConstant One of the constants defined in 20901 * {@link HapticFeedbackConstants} 20902 */ 20903 public boolean performHapticFeedback(int feedbackConstant) { 20904 return performHapticFeedback(feedbackConstant, 0); 20905 } 20906 20907 /** 20908 * BZZZTT!!1! 20909 * 20910 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20911 * 20912 * @param feedbackConstant One of the constants defined in 20913 * {@link HapticFeedbackConstants} 20914 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20915 */ 20916 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20917 if (mAttachInfo == null) { 20918 return false; 20919 } 20920 //noinspection SimplifiableIfStatement 20921 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20922 && !isHapticFeedbackEnabled()) { 20923 return false; 20924 } 20925 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20926 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20927 } 20928 20929 /** 20930 * Request that the visibility of the status bar or other screen/window 20931 * decorations be changed. 20932 * 20933 * <p>This method is used to put the over device UI into temporary modes 20934 * where the user's attention is focused more on the application content, 20935 * by dimming or hiding surrounding system affordances. This is typically 20936 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20937 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20938 * to be placed behind the action bar (and with these flags other system 20939 * affordances) so that smooth transitions between hiding and showing them 20940 * can be done. 20941 * 20942 * <p>Two representative examples of the use of system UI visibility is 20943 * implementing a content browsing application (like a magazine reader) 20944 * and a video playing application. 20945 * 20946 * <p>The first code shows a typical implementation of a View in a content 20947 * browsing application. In this implementation, the application goes 20948 * into a content-oriented mode by hiding the status bar and action bar, 20949 * and putting the navigation elements into lights out mode. The user can 20950 * then interact with content while in this mode. Such an application should 20951 * provide an easy way for the user to toggle out of the mode (such as to 20952 * check information in the status bar or access notifications). In the 20953 * implementation here, this is done simply by tapping on the content. 20954 * 20955 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20956 * content} 20957 * 20958 * <p>This second code sample shows a typical implementation of a View 20959 * in a video playing application. In this situation, while the video is 20960 * playing the application would like to go into a complete full-screen mode, 20961 * to use as much of the display as possible for the video. When in this state 20962 * the user can not interact with the application; the system intercepts 20963 * touching on the screen to pop the UI out of full screen mode. See 20964 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20965 * 20966 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20967 * content} 20968 * 20969 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20970 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20971 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20972 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20973 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20974 */ 20975 public void setSystemUiVisibility(int visibility) { 20976 if (visibility != mSystemUiVisibility) { 20977 mSystemUiVisibility = visibility; 20978 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20979 mParent.recomputeViewAttributes(this); 20980 } 20981 } 20982 } 20983 20984 /** 20985 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20986 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20987 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20988 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20989 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20990 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20991 */ 20992 public int getSystemUiVisibility() { 20993 return mSystemUiVisibility; 20994 } 20995 20996 /** 20997 * Returns the current system UI visibility that is currently set for 20998 * the entire window. This is the combination of the 20999 * {@link #setSystemUiVisibility(int)} values supplied by all of the 21000 * views in the window. 21001 */ 21002 public int getWindowSystemUiVisibility() { 21003 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 21004 } 21005 21006 /** 21007 * Override to find out when the window's requested system UI visibility 21008 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 21009 * This is different from the callbacks received through 21010 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 21011 * in that this is only telling you about the local request of the window, 21012 * not the actual values applied by the system. 21013 */ 21014 public void onWindowSystemUiVisibilityChanged(int visible) { 21015 } 21016 21017 /** 21018 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 21019 * the view hierarchy. 21020 */ 21021 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 21022 onWindowSystemUiVisibilityChanged(visible); 21023 } 21024 21025 /** 21026 * Set a listener to receive callbacks when the visibility of the system bar changes. 21027 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 21028 */ 21029 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 21030 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 21031 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 21032 mParent.recomputeViewAttributes(this); 21033 } 21034 } 21035 21036 /** 21037 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 21038 * the view hierarchy. 21039 */ 21040 public void dispatchSystemUiVisibilityChanged(int visibility) { 21041 ListenerInfo li = mListenerInfo; 21042 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 21043 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 21044 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 21045 } 21046 } 21047 21048 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 21049 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 21050 if (val != mSystemUiVisibility) { 21051 setSystemUiVisibility(val); 21052 return true; 21053 } 21054 return false; 21055 } 21056 21057 /** @hide */ 21058 public void setDisabledSystemUiVisibility(int flags) { 21059 if (mAttachInfo != null) { 21060 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 21061 mAttachInfo.mDisabledSystemUiVisibility = flags; 21062 if (mParent != null) { 21063 mParent.recomputeViewAttributes(this); 21064 } 21065 } 21066 } 21067 } 21068 21069 /** 21070 * Creates an image that the system displays during the drag and drop 21071 * operation. This is called a "drag shadow". The default implementation 21072 * for a DragShadowBuilder based on a View returns an image that has exactly the same 21073 * appearance as the given View. The default also positions the center of the drag shadow 21074 * directly under the touch point. If no View is provided (the constructor with no parameters 21075 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 21076 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 21077 * default is an invisible drag shadow. 21078 * <p> 21079 * You are not required to use the View you provide to the constructor as the basis of the 21080 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 21081 * anything you want as the drag shadow. 21082 * </p> 21083 * <p> 21084 * You pass a DragShadowBuilder object to the system when you start the drag. The system 21085 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 21086 * size and position of the drag shadow. It uses this data to construct a 21087 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 21088 * so that your application can draw the shadow image in the Canvas. 21089 * </p> 21090 * 21091 * <div class="special reference"> 21092 * <h3>Developer Guides</h3> 21093 * <p>For a guide to implementing drag and drop features, read the 21094 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 21095 * </div> 21096 */ 21097 public static class DragShadowBuilder { 21098 private final WeakReference<View> mView; 21099 21100 /** 21101 * Constructs a shadow image builder based on a View. By default, the resulting drag 21102 * shadow will have the same appearance and dimensions as the View, with the touch point 21103 * over the center of the View. 21104 * @param view A View. Any View in scope can be used. 21105 */ 21106 public DragShadowBuilder(View view) { 21107 mView = new WeakReference<View>(view); 21108 } 21109 21110 /** 21111 * Construct a shadow builder object with no associated View. This 21112 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 21113 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 21114 * to supply the drag shadow's dimensions and appearance without 21115 * reference to any View object. If they are not overridden, then the result is an 21116 * invisible drag shadow. 21117 */ 21118 public DragShadowBuilder() { 21119 mView = new WeakReference<View>(null); 21120 } 21121 21122 /** 21123 * Returns the View object that had been passed to the 21124 * {@link #View.DragShadowBuilder(View)} 21125 * constructor. If that View parameter was {@code null} or if the 21126 * {@link #View.DragShadowBuilder()} 21127 * constructor was used to instantiate the builder object, this method will return 21128 * null. 21129 * 21130 * @return The View object associate with this builder object. 21131 */ 21132 @SuppressWarnings({"JavadocReference"}) 21133 final public View getView() { 21134 return mView.get(); 21135 } 21136 21137 /** 21138 * Provides the metrics for the shadow image. These include the dimensions of 21139 * the shadow image, and the point within that shadow that should 21140 * be centered under the touch location while dragging. 21141 * <p> 21142 * The default implementation sets the dimensions of the shadow to be the 21143 * same as the dimensions of the View itself and centers the shadow under 21144 * the touch point. 21145 * </p> 21146 * 21147 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 21148 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 21149 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 21150 * image. 21151 * 21152 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 21153 * shadow image that should be underneath the touch point during the drag and drop 21154 * operation. Your application must set {@link android.graphics.Point#x} to the 21155 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 21156 */ 21157 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 21158 final View view = mView.get(); 21159 if (view != null) { 21160 outShadowSize.set(view.getWidth(), view.getHeight()); 21161 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 21162 } else { 21163 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 21164 } 21165 } 21166 21167 /** 21168 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 21169 * based on the dimensions it received from the 21170 * {@link #onProvideShadowMetrics(Point, Point)} callback. 21171 * 21172 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 21173 */ 21174 public void onDrawShadow(Canvas canvas) { 21175 final View view = mView.get(); 21176 if (view != null) { 21177 view.draw(canvas); 21178 } else { 21179 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 21180 } 21181 } 21182 } 21183 21184 /** 21185 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 21186 * startDragAndDrop()} for newer platform versions. 21187 */ 21188 @Deprecated 21189 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 21190 Object myLocalState, int flags) { 21191 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 21192 } 21193 21194 /** 21195 * Starts a drag and drop operation. When your application calls this method, it passes a 21196 * {@link android.view.View.DragShadowBuilder} object to the system. The 21197 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 21198 * to get metrics for the drag shadow, and then calls the object's 21199 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 21200 * <p> 21201 * Once the system has the drag shadow, it begins the drag and drop operation by sending 21202 * drag events to all the View objects in your application that are currently visible. It does 21203 * this either by calling the View object's drag listener (an implementation of 21204 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 21205 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 21206 * Both are passed a {@link android.view.DragEvent} object that has a 21207 * {@link android.view.DragEvent#getAction()} value of 21208 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 21209 * </p> 21210 * <p> 21211 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 21212 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 21213 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 21214 * to the View the user selected for dragging. 21215 * </p> 21216 * @param data A {@link android.content.ClipData} object pointing to the data to be 21217 * transferred by the drag and drop operation. 21218 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 21219 * drag shadow. 21220 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 21221 * drop operation. When dispatching drag events to views in the same activity this object 21222 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 21223 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 21224 * will return null). 21225 * <p> 21226 * myLocalState is a lightweight mechanism for the sending information from the dragged View 21227 * to the target Views. For example, it can contain flags that differentiate between a 21228 * a copy operation and a move operation. 21229 * </p> 21230 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 21231 * flags, or any combination of the following: 21232 * <ul> 21233 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 21234 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 21235 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 21236 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 21237 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 21238 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 21239 * </ul> 21240 * @return {@code true} if the method completes successfully, or 21241 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 21242 * do a drag, and so no drag operation is in progress. 21243 */ 21244 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 21245 Object myLocalState, int flags) { 21246 if (ViewDebug.DEBUG_DRAG) { 21247 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 21248 } 21249 if (mAttachInfo == null) { 21250 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 21251 return false; 21252 } 21253 21254 if (data != null) { 21255 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 21256 } 21257 21258 boolean okay = false; 21259 21260 Point shadowSize = new Point(); 21261 Point shadowTouchPoint = new Point(); 21262 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 21263 21264 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 21265 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 21266 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 21267 } 21268 21269 if (ViewDebug.DEBUG_DRAG) { 21270 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 21271 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 21272 } 21273 if (mAttachInfo.mDragSurface != null) { 21274 mAttachInfo.mDragSurface.release(); 21275 } 21276 mAttachInfo.mDragSurface = new Surface(); 21277 try { 21278 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 21279 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 21280 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 21281 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 21282 if (mAttachInfo.mDragToken != null) { 21283 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 21284 try { 21285 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 21286 shadowBuilder.onDrawShadow(canvas); 21287 } finally { 21288 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 21289 } 21290 21291 final ViewRootImpl root = getViewRootImpl(); 21292 21293 // Cache the local state object for delivery with DragEvents 21294 root.setLocalDragState(myLocalState); 21295 21296 // repurpose 'shadowSize' for the last touch point 21297 root.getLastTouchPoint(shadowSize); 21298 21299 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 21300 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 21301 shadowTouchPoint.x, shadowTouchPoint.y, data); 21302 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 21303 } 21304 } catch (Exception e) { 21305 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 21306 mAttachInfo.mDragSurface.destroy(); 21307 mAttachInfo.mDragSurface = null; 21308 } 21309 21310 return okay; 21311 } 21312 21313 /** 21314 * Cancels an ongoing drag and drop operation. 21315 * <p> 21316 * A {@link android.view.DragEvent} object with 21317 * {@link android.view.DragEvent#getAction()} value of 21318 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 21319 * {@link android.view.DragEvent#getResult()} value of {@code false} 21320 * will be sent to every 21321 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 21322 * even if they are not currently visible. 21323 * </p> 21324 * <p> 21325 * This method can be called on any View in the same window as the View on which 21326 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 21327 * was called. 21328 * </p> 21329 */ 21330 public final void cancelDragAndDrop() { 21331 if (ViewDebug.DEBUG_DRAG) { 21332 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 21333 } 21334 if (mAttachInfo == null) { 21335 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 21336 return; 21337 } 21338 if (mAttachInfo.mDragToken != null) { 21339 try { 21340 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 21341 } catch (Exception e) { 21342 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 21343 } 21344 mAttachInfo.mDragToken = null; 21345 } else { 21346 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 21347 } 21348 } 21349 21350 /** 21351 * Updates the drag shadow for the ongoing drag and drop operation. 21352 * 21353 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 21354 * new drag shadow. 21355 */ 21356 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 21357 if (ViewDebug.DEBUG_DRAG) { 21358 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 21359 } 21360 if (mAttachInfo == null) { 21361 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 21362 return; 21363 } 21364 if (mAttachInfo.mDragToken != null) { 21365 try { 21366 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 21367 try { 21368 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 21369 shadowBuilder.onDrawShadow(canvas); 21370 } finally { 21371 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 21372 } 21373 } catch (Exception e) { 21374 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 21375 } 21376 } else { 21377 Log.e(VIEW_LOG_TAG, "No active drag"); 21378 } 21379 } 21380 21381 /** 21382 * Starts a move from {startX, startY}, the amount of the movement will be the offset 21383 * between {startX, startY} and the new cursor positon. 21384 * @param startX horizontal coordinate where the move started. 21385 * @param startY vertical coordinate where the move started. 21386 * @return whether moving was started successfully. 21387 * @hide 21388 */ 21389 public final boolean startMovingTask(float startX, float startY) { 21390 if (ViewDebug.DEBUG_POSITIONING) { 21391 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 21392 } 21393 try { 21394 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 21395 } catch (RemoteException e) { 21396 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 21397 } 21398 return false; 21399 } 21400 21401 /** 21402 * Handles drag events sent by the system following a call to 21403 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 21404 * startDragAndDrop()}. 21405 *<p> 21406 * When the system calls this method, it passes a 21407 * {@link android.view.DragEvent} object. A call to 21408 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 21409 * in DragEvent. The method uses these to determine what is happening in the drag and drop 21410 * operation. 21411 * @param event The {@link android.view.DragEvent} sent by the system. 21412 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 21413 * in DragEvent, indicating the type of drag event represented by this object. 21414 * @return {@code true} if the method was successful, otherwise {@code false}. 21415 * <p> 21416 * The method should return {@code true} in response to an action type of 21417 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 21418 * operation. 21419 * </p> 21420 * <p> 21421 * The method should also return {@code true} in response to an action type of 21422 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 21423 * {@code false} if it didn't. 21424 * </p> 21425 * <p> 21426 * For all other events, the return value is ignored. 21427 * </p> 21428 */ 21429 public boolean onDragEvent(DragEvent event) { 21430 return false; 21431 } 21432 21433 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 21434 boolean dispatchDragEnterExitInPreN(DragEvent event) { 21435 return callDragEventHandler(event); 21436 } 21437 21438 /** 21439 * Detects if this View is enabled and has a drag event listener. 21440 * If both are true, then it calls the drag event listener with the 21441 * {@link android.view.DragEvent} it received. If the drag event listener returns 21442 * {@code true}, then dispatchDragEvent() returns {@code true}. 21443 * <p> 21444 * For all other cases, the method calls the 21445 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 21446 * method and returns its result. 21447 * </p> 21448 * <p> 21449 * This ensures that a drag event is always consumed, even if the View does not have a drag 21450 * event listener. However, if the View has a listener and the listener returns true, then 21451 * onDragEvent() is not called. 21452 * </p> 21453 */ 21454 public boolean dispatchDragEvent(DragEvent event) { 21455 event.mEventHandlerWasCalled = true; 21456 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 21457 event.mAction == DragEvent.ACTION_DROP) { 21458 // About to deliver an event with coordinates to this view. Notify that now this view 21459 // has drag focus. This will send exit/enter events as needed. 21460 getViewRootImpl().setDragFocus(this, event); 21461 } 21462 return callDragEventHandler(event); 21463 } 21464 21465 final boolean callDragEventHandler(DragEvent event) { 21466 final boolean result; 21467 21468 ListenerInfo li = mListenerInfo; 21469 //noinspection SimplifiableIfStatement 21470 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 21471 && li.mOnDragListener.onDrag(this, event)) { 21472 result = true; 21473 } else { 21474 result = onDragEvent(event); 21475 } 21476 21477 switch (event.mAction) { 21478 case DragEvent.ACTION_DRAG_ENTERED: { 21479 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 21480 refreshDrawableState(); 21481 } break; 21482 case DragEvent.ACTION_DRAG_EXITED: { 21483 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 21484 refreshDrawableState(); 21485 } break; 21486 case DragEvent.ACTION_DRAG_ENDED: { 21487 mPrivateFlags2 &= ~View.DRAG_MASK; 21488 refreshDrawableState(); 21489 } break; 21490 } 21491 21492 return result; 21493 } 21494 21495 boolean canAcceptDrag() { 21496 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 21497 } 21498 21499 /** 21500 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 21501 * it is ever exposed at all. 21502 * @hide 21503 */ 21504 public void onCloseSystemDialogs(String reason) { 21505 } 21506 21507 /** 21508 * Given a Drawable whose bounds have been set to draw into this view, 21509 * update a Region being computed for 21510 * {@link #gatherTransparentRegion(android.graphics.Region)} so 21511 * that any non-transparent parts of the Drawable are removed from the 21512 * given transparent region. 21513 * 21514 * @param dr The Drawable whose transparency is to be applied to the region. 21515 * @param region A Region holding the current transparency information, 21516 * where any parts of the region that are set are considered to be 21517 * transparent. On return, this region will be modified to have the 21518 * transparency information reduced by the corresponding parts of the 21519 * Drawable that are not transparent. 21520 * {@hide} 21521 */ 21522 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 21523 if (DBG) { 21524 Log.i("View", "Getting transparent region for: " + this); 21525 } 21526 final Region r = dr.getTransparentRegion(); 21527 final Rect db = dr.getBounds(); 21528 final AttachInfo attachInfo = mAttachInfo; 21529 if (r != null && attachInfo != null) { 21530 final int w = getRight()-getLeft(); 21531 final int h = getBottom()-getTop(); 21532 if (db.left > 0) { 21533 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 21534 r.op(0, 0, db.left, h, Region.Op.UNION); 21535 } 21536 if (db.right < w) { 21537 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 21538 r.op(db.right, 0, w, h, Region.Op.UNION); 21539 } 21540 if (db.top > 0) { 21541 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 21542 r.op(0, 0, w, db.top, Region.Op.UNION); 21543 } 21544 if (db.bottom < h) { 21545 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 21546 r.op(0, db.bottom, w, h, Region.Op.UNION); 21547 } 21548 final int[] location = attachInfo.mTransparentLocation; 21549 getLocationInWindow(location); 21550 r.translate(location[0], location[1]); 21551 region.op(r, Region.Op.INTERSECT); 21552 } else { 21553 region.op(db, Region.Op.DIFFERENCE); 21554 } 21555 } 21556 21557 private void checkForLongClick(int delayOffset, float x, float y) { 21558 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) { 21559 mHasPerformedLongPress = false; 21560 21561 if (mPendingCheckForLongPress == null) { 21562 mPendingCheckForLongPress = new CheckForLongPress(); 21563 } 21564 mPendingCheckForLongPress.setAnchor(x, y); 21565 mPendingCheckForLongPress.rememberWindowAttachCount(); 21566 mPendingCheckForLongPress.rememberPressedState(); 21567 postDelayed(mPendingCheckForLongPress, 21568 ViewConfiguration.getLongPressTimeout() - delayOffset); 21569 } 21570 } 21571 21572 /** 21573 * Inflate a view from an XML resource. This convenience method wraps the {@link 21574 * LayoutInflater} class, which provides a full range of options for view inflation. 21575 * 21576 * @param context The Context object for your activity or application. 21577 * @param resource The resource ID to inflate 21578 * @param root A view group that will be the parent. Used to properly inflate the 21579 * layout_* parameters. 21580 * @see LayoutInflater 21581 */ 21582 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 21583 LayoutInflater factory = LayoutInflater.from(context); 21584 return factory.inflate(resource, root); 21585 } 21586 21587 /** 21588 * Scroll the view with standard behavior for scrolling beyond the normal 21589 * content boundaries. Views that call this method should override 21590 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 21591 * results of an over-scroll operation. 21592 * 21593 * Views can use this method to handle any touch or fling-based scrolling. 21594 * 21595 * @param deltaX Change in X in pixels 21596 * @param deltaY Change in Y in pixels 21597 * @param scrollX Current X scroll value in pixels before applying deltaX 21598 * @param scrollY Current Y scroll value in pixels before applying deltaY 21599 * @param scrollRangeX Maximum content scroll range along the X axis 21600 * @param scrollRangeY Maximum content scroll range along the Y axis 21601 * @param maxOverScrollX Number of pixels to overscroll by in either direction 21602 * along the X axis. 21603 * @param maxOverScrollY Number of pixels to overscroll by in either direction 21604 * along the Y axis. 21605 * @param isTouchEvent true if this scroll operation is the result of a touch event. 21606 * @return true if scrolling was clamped to an over-scroll boundary along either 21607 * axis, false otherwise. 21608 */ 21609 @SuppressWarnings({"UnusedParameters"}) 21610 protected boolean overScrollBy(int deltaX, int deltaY, 21611 int scrollX, int scrollY, 21612 int scrollRangeX, int scrollRangeY, 21613 int maxOverScrollX, int maxOverScrollY, 21614 boolean isTouchEvent) { 21615 final int overScrollMode = mOverScrollMode; 21616 final boolean canScrollHorizontal = 21617 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 21618 final boolean canScrollVertical = 21619 computeVerticalScrollRange() > computeVerticalScrollExtent(); 21620 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 21621 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 21622 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 21623 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 21624 21625 int newScrollX = scrollX + deltaX; 21626 if (!overScrollHorizontal) { 21627 maxOverScrollX = 0; 21628 } 21629 21630 int newScrollY = scrollY + deltaY; 21631 if (!overScrollVertical) { 21632 maxOverScrollY = 0; 21633 } 21634 21635 // Clamp values if at the limits and record 21636 final int left = -maxOverScrollX; 21637 final int right = maxOverScrollX + scrollRangeX; 21638 final int top = -maxOverScrollY; 21639 final int bottom = maxOverScrollY + scrollRangeY; 21640 21641 boolean clampedX = false; 21642 if (newScrollX > right) { 21643 newScrollX = right; 21644 clampedX = true; 21645 } else if (newScrollX < left) { 21646 newScrollX = left; 21647 clampedX = true; 21648 } 21649 21650 boolean clampedY = false; 21651 if (newScrollY > bottom) { 21652 newScrollY = bottom; 21653 clampedY = true; 21654 } else if (newScrollY < top) { 21655 newScrollY = top; 21656 clampedY = true; 21657 } 21658 21659 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 21660 21661 return clampedX || clampedY; 21662 } 21663 21664 /** 21665 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 21666 * respond to the results of an over-scroll operation. 21667 * 21668 * @param scrollX New X scroll value in pixels 21669 * @param scrollY New Y scroll value in pixels 21670 * @param clampedX True if scrollX was clamped to an over-scroll boundary 21671 * @param clampedY True if scrollY was clamped to an over-scroll boundary 21672 */ 21673 protected void onOverScrolled(int scrollX, int scrollY, 21674 boolean clampedX, boolean clampedY) { 21675 // Intentionally empty. 21676 } 21677 21678 /** 21679 * Returns the over-scroll mode for this view. The result will be 21680 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21681 * (allow over-scrolling only if the view content is larger than the container), 21682 * or {@link #OVER_SCROLL_NEVER}. 21683 * 21684 * @return This view's over-scroll mode. 21685 */ 21686 public int getOverScrollMode() { 21687 return mOverScrollMode; 21688 } 21689 21690 /** 21691 * Set the over-scroll mode for this view. Valid over-scroll modes are 21692 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21693 * (allow over-scrolling only if the view content is larger than the container), 21694 * or {@link #OVER_SCROLL_NEVER}. 21695 * 21696 * Setting the over-scroll mode of a view will have an effect only if the 21697 * view is capable of scrolling. 21698 * 21699 * @param overScrollMode The new over-scroll mode for this view. 21700 */ 21701 public void setOverScrollMode(int overScrollMode) { 21702 if (overScrollMode != OVER_SCROLL_ALWAYS && 21703 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 21704 overScrollMode != OVER_SCROLL_NEVER) { 21705 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 21706 } 21707 mOverScrollMode = overScrollMode; 21708 } 21709 21710 /** 21711 * Enable or disable nested scrolling for this view. 21712 * 21713 * <p>If this property is set to true the view will be permitted to initiate nested 21714 * scrolling operations with a compatible parent view in the current hierarchy. If this 21715 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 21716 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 21717 * the nested scroll.</p> 21718 * 21719 * @param enabled true to enable nested scrolling, false to disable 21720 * 21721 * @see #isNestedScrollingEnabled() 21722 */ 21723 public void setNestedScrollingEnabled(boolean enabled) { 21724 if (enabled) { 21725 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 21726 } else { 21727 stopNestedScroll(); 21728 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 21729 } 21730 } 21731 21732 /** 21733 * Returns true if nested scrolling is enabled for this view. 21734 * 21735 * <p>If nested scrolling is enabled and this View class implementation supports it, 21736 * this view will act as a nested scrolling child view when applicable, forwarding data 21737 * about the scroll operation in progress to a compatible and cooperating nested scrolling 21738 * parent.</p> 21739 * 21740 * @return true if nested scrolling is enabled 21741 * 21742 * @see #setNestedScrollingEnabled(boolean) 21743 */ 21744 public boolean isNestedScrollingEnabled() { 21745 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 21746 PFLAG3_NESTED_SCROLLING_ENABLED; 21747 } 21748 21749 /** 21750 * Begin a nestable scroll operation along the given axes. 21751 * 21752 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 21753 * 21754 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 21755 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 21756 * In the case of touch scrolling the nested scroll will be terminated automatically in 21757 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 21758 * In the event of programmatic scrolling the caller must explicitly call 21759 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 21760 * 21761 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21762 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21763 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21764 * 21765 * <p>At each incremental step of the scroll the caller should invoke 21766 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21767 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21768 * parent at least partially consumed the scroll and the caller should adjust the amount it 21769 * scrolls by.</p> 21770 * 21771 * <p>After applying the remainder of the scroll delta the caller should invoke 21772 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21773 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21774 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21775 * </p> 21776 * 21777 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21778 * {@link #SCROLL_AXIS_VERTICAL}. 21779 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21780 * the current gesture. 21781 * 21782 * @see #stopNestedScroll() 21783 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21784 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21785 */ 21786 public boolean startNestedScroll(int axes) { 21787 if (hasNestedScrollingParent()) { 21788 // Already in progress 21789 return true; 21790 } 21791 if (isNestedScrollingEnabled()) { 21792 ViewParent p = getParent(); 21793 View child = this; 21794 while (p != null) { 21795 try { 21796 if (p.onStartNestedScroll(child, this, axes)) { 21797 mNestedScrollingParent = p; 21798 p.onNestedScrollAccepted(child, this, axes); 21799 return true; 21800 } 21801 } catch (AbstractMethodError e) { 21802 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21803 "method onStartNestedScroll", e); 21804 // Allow the search upward to continue 21805 } 21806 if (p instanceof View) { 21807 child = (View) p; 21808 } 21809 p = p.getParent(); 21810 } 21811 } 21812 return false; 21813 } 21814 21815 /** 21816 * Stop a nested scroll in progress. 21817 * 21818 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21819 * 21820 * @see #startNestedScroll(int) 21821 */ 21822 public void stopNestedScroll() { 21823 if (mNestedScrollingParent != null) { 21824 mNestedScrollingParent.onStopNestedScroll(this); 21825 mNestedScrollingParent = null; 21826 } 21827 } 21828 21829 /** 21830 * Returns true if this view has a nested scrolling parent. 21831 * 21832 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21833 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21834 * 21835 * @return whether this view has a nested scrolling parent 21836 */ 21837 public boolean hasNestedScrollingParent() { 21838 return mNestedScrollingParent != null; 21839 } 21840 21841 /** 21842 * Dispatch one step of a nested scroll in progress. 21843 * 21844 * <p>Implementations of views that support nested scrolling should call this to report 21845 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21846 * is not currently in progress or nested scrolling is not 21847 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21848 * 21849 * <p>Compatible View implementations should also call 21850 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21851 * consuming a component of the scroll event themselves.</p> 21852 * 21853 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21854 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21855 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21856 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21857 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21858 * in local view coordinates of this view from before this operation 21859 * to after it completes. View implementations may use this to adjust 21860 * expected input coordinate tracking. 21861 * @return true if the event was dispatched, false if it could not be dispatched. 21862 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21863 */ 21864 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21865 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21866 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21867 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21868 int startX = 0; 21869 int startY = 0; 21870 if (offsetInWindow != null) { 21871 getLocationInWindow(offsetInWindow); 21872 startX = offsetInWindow[0]; 21873 startY = offsetInWindow[1]; 21874 } 21875 21876 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21877 dxUnconsumed, dyUnconsumed); 21878 21879 if (offsetInWindow != null) { 21880 getLocationInWindow(offsetInWindow); 21881 offsetInWindow[0] -= startX; 21882 offsetInWindow[1] -= startY; 21883 } 21884 return true; 21885 } else if (offsetInWindow != null) { 21886 // No motion, no dispatch. Keep offsetInWindow up to date. 21887 offsetInWindow[0] = 0; 21888 offsetInWindow[1] = 0; 21889 } 21890 } 21891 return false; 21892 } 21893 21894 /** 21895 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21896 * 21897 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21898 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21899 * scrolling operation to consume some or all of the scroll operation before the child view 21900 * consumes it.</p> 21901 * 21902 * @param dx Horizontal scroll distance in pixels 21903 * @param dy Vertical scroll distance in pixels 21904 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21905 * and consumed[1] the consumed dy. 21906 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21907 * in local view coordinates of this view from before this operation 21908 * to after it completes. View implementations may use this to adjust 21909 * expected input coordinate tracking. 21910 * @return true if the parent consumed some or all of the scroll delta 21911 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21912 */ 21913 public boolean dispatchNestedPreScroll(int dx, int dy, 21914 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21915 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21916 if (dx != 0 || dy != 0) { 21917 int startX = 0; 21918 int startY = 0; 21919 if (offsetInWindow != null) { 21920 getLocationInWindow(offsetInWindow); 21921 startX = offsetInWindow[0]; 21922 startY = offsetInWindow[1]; 21923 } 21924 21925 if (consumed == null) { 21926 if (mTempNestedScrollConsumed == null) { 21927 mTempNestedScrollConsumed = new int[2]; 21928 } 21929 consumed = mTempNestedScrollConsumed; 21930 } 21931 consumed[0] = 0; 21932 consumed[1] = 0; 21933 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21934 21935 if (offsetInWindow != null) { 21936 getLocationInWindow(offsetInWindow); 21937 offsetInWindow[0] -= startX; 21938 offsetInWindow[1] -= startY; 21939 } 21940 return consumed[0] != 0 || consumed[1] != 0; 21941 } else if (offsetInWindow != null) { 21942 offsetInWindow[0] = 0; 21943 offsetInWindow[1] = 0; 21944 } 21945 } 21946 return false; 21947 } 21948 21949 /** 21950 * Dispatch a fling to a nested scrolling parent. 21951 * 21952 * <p>This method should be used to indicate that a nested scrolling child has detected 21953 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21954 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21955 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21956 * along a scrollable axis.</p> 21957 * 21958 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21959 * its own content, it can use this method to delegate the fling to its nested scrolling 21960 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21961 * 21962 * @param velocityX Horizontal fling velocity in pixels per second 21963 * @param velocityY Vertical fling velocity in pixels per second 21964 * @param consumed true if the child consumed the fling, false otherwise 21965 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21966 */ 21967 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21968 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21969 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21970 } 21971 return false; 21972 } 21973 21974 /** 21975 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21976 * 21977 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21978 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21979 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21980 * before the child view consumes it. If this method returns <code>true</code>, a nested 21981 * parent view consumed the fling and this view should not scroll as a result.</p> 21982 * 21983 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21984 * the fling at a time. If a parent view consumed the fling this method will return false. 21985 * Custom view implementations should account for this in two ways:</p> 21986 * 21987 * <ul> 21988 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21989 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21990 * position regardless.</li> 21991 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21992 * even to settle back to a valid idle position.</li> 21993 * </ul> 21994 * 21995 * <p>Views should also not offer fling velocities to nested parent views along an axis 21996 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21997 * should not offer a horizontal fling velocity to its parents since scrolling along that 21998 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21999 * 22000 * @param velocityX Horizontal fling velocity in pixels per second 22001 * @param velocityY Vertical fling velocity in pixels per second 22002 * @return true if a nested scrolling parent consumed the fling 22003 */ 22004 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 22005 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 22006 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 22007 } 22008 return false; 22009 } 22010 22011 /** 22012 * Gets a scale factor that determines the distance the view should scroll 22013 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 22014 * @return The vertical scroll scale factor. 22015 * @hide 22016 */ 22017 protected float getVerticalScrollFactor() { 22018 if (mVerticalScrollFactor == 0) { 22019 TypedValue outValue = new TypedValue(); 22020 if (!mContext.getTheme().resolveAttribute( 22021 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 22022 throw new IllegalStateException( 22023 "Expected theme to define listPreferredItemHeight."); 22024 } 22025 mVerticalScrollFactor = outValue.getDimension( 22026 mContext.getResources().getDisplayMetrics()); 22027 } 22028 return mVerticalScrollFactor; 22029 } 22030 22031 /** 22032 * Gets a scale factor that determines the distance the view should scroll 22033 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 22034 * @return The horizontal scroll scale factor. 22035 * @hide 22036 */ 22037 protected float getHorizontalScrollFactor() { 22038 // TODO: Should use something else. 22039 return getVerticalScrollFactor(); 22040 } 22041 22042 /** 22043 * Return the value specifying the text direction or policy that was set with 22044 * {@link #setTextDirection(int)}. 22045 * 22046 * @return the defined text direction. It can be one of: 22047 * 22048 * {@link #TEXT_DIRECTION_INHERIT}, 22049 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 22050 * {@link #TEXT_DIRECTION_ANY_RTL}, 22051 * {@link #TEXT_DIRECTION_LTR}, 22052 * {@link #TEXT_DIRECTION_RTL}, 22053 * {@link #TEXT_DIRECTION_LOCALE}, 22054 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 22055 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 22056 * 22057 * @attr ref android.R.styleable#View_textDirection 22058 * 22059 * @hide 22060 */ 22061 @ViewDebug.ExportedProperty(category = "text", mapping = { 22062 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 22063 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 22064 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 22065 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 22066 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 22067 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 22068 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 22069 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 22070 }) 22071 public int getRawTextDirection() { 22072 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 22073 } 22074 22075 /** 22076 * Set the text direction. 22077 * 22078 * @param textDirection the direction to set. Should be one of: 22079 * 22080 * {@link #TEXT_DIRECTION_INHERIT}, 22081 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 22082 * {@link #TEXT_DIRECTION_ANY_RTL}, 22083 * {@link #TEXT_DIRECTION_LTR}, 22084 * {@link #TEXT_DIRECTION_RTL}, 22085 * {@link #TEXT_DIRECTION_LOCALE} 22086 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 22087 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 22088 * 22089 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 22090 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 22091 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 22092 * 22093 * @attr ref android.R.styleable#View_textDirection 22094 */ 22095 public void setTextDirection(int textDirection) { 22096 if (getRawTextDirection() != textDirection) { 22097 // Reset the current text direction and the resolved one 22098 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 22099 resetResolvedTextDirection(); 22100 // Set the new text direction 22101 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 22102 // Do resolution 22103 resolveTextDirection(); 22104 // Notify change 22105 onRtlPropertiesChanged(getLayoutDirection()); 22106 // Refresh 22107 requestLayout(); 22108 invalidate(true); 22109 } 22110 } 22111 22112 /** 22113 * Return the resolved text direction. 22114 * 22115 * @return the resolved text direction. Returns one of: 22116 * 22117 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 22118 * {@link #TEXT_DIRECTION_ANY_RTL}, 22119 * {@link #TEXT_DIRECTION_LTR}, 22120 * {@link #TEXT_DIRECTION_RTL}, 22121 * {@link #TEXT_DIRECTION_LOCALE}, 22122 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 22123 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 22124 * 22125 * @attr ref android.R.styleable#View_textDirection 22126 */ 22127 @ViewDebug.ExportedProperty(category = "text", mapping = { 22128 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 22129 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 22130 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 22131 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 22132 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 22133 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 22134 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 22135 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 22136 }) 22137 public int getTextDirection() { 22138 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 22139 } 22140 22141 /** 22142 * Resolve the text direction. 22143 * 22144 * @return true if resolution has been done, false otherwise. 22145 * 22146 * @hide 22147 */ 22148 public boolean resolveTextDirection() { 22149 // Reset any previous text direction resolution 22150 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 22151 22152 if (hasRtlSupport()) { 22153 // Set resolved text direction flag depending on text direction flag 22154 final int textDirection = getRawTextDirection(); 22155 switch(textDirection) { 22156 case TEXT_DIRECTION_INHERIT: 22157 if (!canResolveTextDirection()) { 22158 // We cannot do the resolution if there is no parent, so use the default one 22159 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22160 // Resolution will need to happen again later 22161 return false; 22162 } 22163 22164 // Parent has not yet resolved, so we still return the default 22165 try { 22166 if (!mParent.isTextDirectionResolved()) { 22167 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22168 // Resolution will need to happen again later 22169 return false; 22170 } 22171 } catch (AbstractMethodError e) { 22172 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22173 " does not fully implement ViewParent", e); 22174 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 22175 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22176 return true; 22177 } 22178 22179 // Set current resolved direction to the same value as the parent's one 22180 int parentResolvedDirection; 22181 try { 22182 parentResolvedDirection = mParent.getTextDirection(); 22183 } catch (AbstractMethodError e) { 22184 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22185 " does not fully implement ViewParent", e); 22186 parentResolvedDirection = TEXT_DIRECTION_LTR; 22187 } 22188 switch (parentResolvedDirection) { 22189 case TEXT_DIRECTION_FIRST_STRONG: 22190 case TEXT_DIRECTION_ANY_RTL: 22191 case TEXT_DIRECTION_LTR: 22192 case TEXT_DIRECTION_RTL: 22193 case TEXT_DIRECTION_LOCALE: 22194 case TEXT_DIRECTION_FIRST_STRONG_LTR: 22195 case TEXT_DIRECTION_FIRST_STRONG_RTL: 22196 mPrivateFlags2 |= 22197 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 22198 break; 22199 default: 22200 // Default resolved direction is "first strong" heuristic 22201 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22202 } 22203 break; 22204 case TEXT_DIRECTION_FIRST_STRONG: 22205 case TEXT_DIRECTION_ANY_RTL: 22206 case TEXT_DIRECTION_LTR: 22207 case TEXT_DIRECTION_RTL: 22208 case TEXT_DIRECTION_LOCALE: 22209 case TEXT_DIRECTION_FIRST_STRONG_LTR: 22210 case TEXT_DIRECTION_FIRST_STRONG_RTL: 22211 // Resolved direction is the same as text direction 22212 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 22213 break; 22214 default: 22215 // Default resolved direction is "first strong" heuristic 22216 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22217 } 22218 } else { 22219 // Default resolved direction is "first strong" heuristic 22220 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22221 } 22222 22223 // Set to resolved 22224 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 22225 return true; 22226 } 22227 22228 /** 22229 * Check if text direction resolution can be done. 22230 * 22231 * @return true if text direction resolution can be done otherwise return false. 22232 */ 22233 public boolean canResolveTextDirection() { 22234 switch (getRawTextDirection()) { 22235 case TEXT_DIRECTION_INHERIT: 22236 if (mParent != null) { 22237 try { 22238 return mParent.canResolveTextDirection(); 22239 } catch (AbstractMethodError e) { 22240 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22241 " does not fully implement ViewParent", e); 22242 } 22243 } 22244 return false; 22245 22246 default: 22247 return true; 22248 } 22249 } 22250 22251 /** 22252 * Reset resolved text direction. Text direction will be resolved during a call to 22253 * {@link #onMeasure(int, int)}. 22254 * 22255 * @hide 22256 */ 22257 public void resetResolvedTextDirection() { 22258 // Reset any previous text direction resolution 22259 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 22260 // Set to default value 22261 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 22262 } 22263 22264 /** 22265 * @return true if text direction is inherited. 22266 * 22267 * @hide 22268 */ 22269 public boolean isTextDirectionInherited() { 22270 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 22271 } 22272 22273 /** 22274 * @return true if text direction is resolved. 22275 */ 22276 public boolean isTextDirectionResolved() { 22277 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 22278 } 22279 22280 /** 22281 * Return the value specifying the text alignment or policy that was set with 22282 * {@link #setTextAlignment(int)}. 22283 * 22284 * @return the defined text alignment. It can be one of: 22285 * 22286 * {@link #TEXT_ALIGNMENT_INHERIT}, 22287 * {@link #TEXT_ALIGNMENT_GRAVITY}, 22288 * {@link #TEXT_ALIGNMENT_CENTER}, 22289 * {@link #TEXT_ALIGNMENT_TEXT_START}, 22290 * {@link #TEXT_ALIGNMENT_TEXT_END}, 22291 * {@link #TEXT_ALIGNMENT_VIEW_START}, 22292 * {@link #TEXT_ALIGNMENT_VIEW_END} 22293 * 22294 * @attr ref android.R.styleable#View_textAlignment 22295 * 22296 * @hide 22297 */ 22298 @ViewDebug.ExportedProperty(category = "text", mapping = { 22299 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 22300 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 22301 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 22302 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 22303 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 22304 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 22305 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 22306 }) 22307 @TextAlignment 22308 public int getRawTextAlignment() { 22309 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 22310 } 22311 22312 /** 22313 * Set the text alignment. 22314 * 22315 * @param textAlignment The text alignment to set. Should be one of 22316 * 22317 * {@link #TEXT_ALIGNMENT_INHERIT}, 22318 * {@link #TEXT_ALIGNMENT_GRAVITY}, 22319 * {@link #TEXT_ALIGNMENT_CENTER}, 22320 * {@link #TEXT_ALIGNMENT_TEXT_START}, 22321 * {@link #TEXT_ALIGNMENT_TEXT_END}, 22322 * {@link #TEXT_ALIGNMENT_VIEW_START}, 22323 * {@link #TEXT_ALIGNMENT_VIEW_END} 22324 * 22325 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 22326 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 22327 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 22328 * 22329 * @attr ref android.R.styleable#View_textAlignment 22330 */ 22331 public void setTextAlignment(@TextAlignment int textAlignment) { 22332 if (textAlignment != getRawTextAlignment()) { 22333 // Reset the current and resolved text alignment 22334 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 22335 resetResolvedTextAlignment(); 22336 // Set the new text alignment 22337 mPrivateFlags2 |= 22338 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 22339 // Do resolution 22340 resolveTextAlignment(); 22341 // Notify change 22342 onRtlPropertiesChanged(getLayoutDirection()); 22343 // Refresh 22344 requestLayout(); 22345 invalidate(true); 22346 } 22347 } 22348 22349 /** 22350 * Return the resolved text alignment. 22351 * 22352 * @return the resolved text alignment. Returns one of: 22353 * 22354 * {@link #TEXT_ALIGNMENT_GRAVITY}, 22355 * {@link #TEXT_ALIGNMENT_CENTER}, 22356 * {@link #TEXT_ALIGNMENT_TEXT_START}, 22357 * {@link #TEXT_ALIGNMENT_TEXT_END}, 22358 * {@link #TEXT_ALIGNMENT_VIEW_START}, 22359 * {@link #TEXT_ALIGNMENT_VIEW_END} 22360 * 22361 * @attr ref android.R.styleable#View_textAlignment 22362 */ 22363 @ViewDebug.ExportedProperty(category = "text", mapping = { 22364 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 22365 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 22366 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 22367 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 22368 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 22369 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 22370 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 22371 }) 22372 @TextAlignment 22373 public int getTextAlignment() { 22374 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 22375 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 22376 } 22377 22378 /** 22379 * Resolve the text alignment. 22380 * 22381 * @return true if resolution has been done, false otherwise. 22382 * 22383 * @hide 22384 */ 22385 public boolean resolveTextAlignment() { 22386 // Reset any previous text alignment resolution 22387 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 22388 22389 if (hasRtlSupport()) { 22390 // Set resolved text alignment flag depending on text alignment flag 22391 final int textAlignment = getRawTextAlignment(); 22392 switch (textAlignment) { 22393 case TEXT_ALIGNMENT_INHERIT: 22394 // Check if we can resolve the text alignment 22395 if (!canResolveTextAlignment()) { 22396 // We cannot do the resolution if there is no parent so use the default 22397 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22398 // Resolution will need to happen again later 22399 return false; 22400 } 22401 22402 // Parent has not yet resolved, so we still return the default 22403 try { 22404 if (!mParent.isTextAlignmentResolved()) { 22405 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22406 // Resolution will need to happen again later 22407 return false; 22408 } 22409 } catch (AbstractMethodError e) { 22410 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22411 " does not fully implement ViewParent", e); 22412 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 22413 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22414 return true; 22415 } 22416 22417 int parentResolvedTextAlignment; 22418 try { 22419 parentResolvedTextAlignment = mParent.getTextAlignment(); 22420 } catch (AbstractMethodError e) { 22421 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22422 " does not fully implement ViewParent", e); 22423 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 22424 } 22425 switch (parentResolvedTextAlignment) { 22426 case TEXT_ALIGNMENT_GRAVITY: 22427 case TEXT_ALIGNMENT_TEXT_START: 22428 case TEXT_ALIGNMENT_TEXT_END: 22429 case TEXT_ALIGNMENT_CENTER: 22430 case TEXT_ALIGNMENT_VIEW_START: 22431 case TEXT_ALIGNMENT_VIEW_END: 22432 // Resolved text alignment is the same as the parent resolved 22433 // text alignment 22434 mPrivateFlags2 |= 22435 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 22436 break; 22437 default: 22438 // Use default resolved text alignment 22439 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22440 } 22441 break; 22442 case TEXT_ALIGNMENT_GRAVITY: 22443 case TEXT_ALIGNMENT_TEXT_START: 22444 case TEXT_ALIGNMENT_TEXT_END: 22445 case TEXT_ALIGNMENT_CENTER: 22446 case TEXT_ALIGNMENT_VIEW_START: 22447 case TEXT_ALIGNMENT_VIEW_END: 22448 // Resolved text alignment is the same as text alignment 22449 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 22450 break; 22451 default: 22452 // Use default resolved text alignment 22453 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22454 } 22455 } else { 22456 // Use default resolved text alignment 22457 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22458 } 22459 22460 // Set the resolved 22461 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 22462 return true; 22463 } 22464 22465 /** 22466 * Check if text alignment resolution can be done. 22467 * 22468 * @return true if text alignment resolution can be done otherwise return false. 22469 */ 22470 public boolean canResolveTextAlignment() { 22471 switch (getRawTextAlignment()) { 22472 case TEXT_DIRECTION_INHERIT: 22473 if (mParent != null) { 22474 try { 22475 return mParent.canResolveTextAlignment(); 22476 } catch (AbstractMethodError e) { 22477 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 22478 " does not fully implement ViewParent", e); 22479 } 22480 } 22481 return false; 22482 22483 default: 22484 return true; 22485 } 22486 } 22487 22488 /** 22489 * Reset resolved text alignment. Text alignment will be resolved during a call to 22490 * {@link #onMeasure(int, int)}. 22491 * 22492 * @hide 22493 */ 22494 public void resetResolvedTextAlignment() { 22495 // Reset any previous text alignment resolution 22496 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 22497 // Set to default 22498 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 22499 } 22500 22501 /** 22502 * @return true if text alignment is inherited. 22503 * 22504 * @hide 22505 */ 22506 public boolean isTextAlignmentInherited() { 22507 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 22508 } 22509 22510 /** 22511 * @return true if text alignment is resolved. 22512 */ 22513 public boolean isTextAlignmentResolved() { 22514 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 22515 } 22516 22517 /** 22518 * Generate a value suitable for use in {@link #setId(int)}. 22519 * This value will not collide with ID values generated at build time by aapt for R.id. 22520 * 22521 * @return a generated ID value 22522 */ 22523 public static int generateViewId() { 22524 for (;;) { 22525 final int result = sNextGeneratedId.get(); 22526 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 22527 int newValue = result + 1; 22528 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 22529 if (sNextGeneratedId.compareAndSet(result, newValue)) { 22530 return result; 22531 } 22532 } 22533 } 22534 22535 private static boolean isViewIdGenerated(int id) { 22536 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0; 22537 } 22538 22539 /** 22540 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 22541 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 22542 * a normal View or a ViewGroup with 22543 * {@link android.view.ViewGroup#isTransitionGroup()} true. 22544 * @hide 22545 */ 22546 public void captureTransitioningViews(List<View> transitioningViews) { 22547 if (getVisibility() == View.VISIBLE) { 22548 transitioningViews.add(this); 22549 } 22550 } 22551 22552 /** 22553 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 22554 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 22555 * @hide 22556 */ 22557 public void findNamedViews(Map<String, View> namedElements) { 22558 if (getVisibility() == VISIBLE || mGhostView != null) { 22559 String transitionName = getTransitionName(); 22560 if (transitionName != null) { 22561 namedElements.put(transitionName, this); 22562 } 22563 } 22564 } 22565 22566 /** 22567 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 22568 * The default implementation does not care the location or event types, but some subclasses 22569 * may use it (such as WebViews). 22570 * @param event The MotionEvent from a mouse 22571 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 22572 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 22573 * @see PointerIcon 22574 */ 22575 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 22576 final float x = event.getX(pointerIndex); 22577 final float y = event.getY(pointerIndex); 22578 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 22579 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 22580 } 22581 return mPointerIcon; 22582 } 22583 22584 /** 22585 * Set the pointer icon for the current view. 22586 * Passing {@code null} will restore the pointer icon to its default value. 22587 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 22588 */ 22589 public void setPointerIcon(PointerIcon pointerIcon) { 22590 mPointerIcon = pointerIcon; 22591 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 22592 return; 22593 } 22594 try { 22595 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 22596 } catch (RemoteException e) { 22597 } 22598 } 22599 22600 /** 22601 * Gets the pointer icon for the current view. 22602 */ 22603 public PointerIcon getPointerIcon() { 22604 return mPointerIcon; 22605 } 22606 22607 // 22608 // Properties 22609 // 22610 /** 22611 * A Property wrapper around the <code>alpha</code> functionality handled by the 22612 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 22613 */ 22614 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 22615 @Override 22616 public void setValue(View object, float value) { 22617 object.setAlpha(value); 22618 } 22619 22620 @Override 22621 public Float get(View object) { 22622 return object.getAlpha(); 22623 } 22624 }; 22625 22626 /** 22627 * A Property wrapper around the <code>translationX</code> functionality handled by the 22628 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 22629 */ 22630 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 22631 @Override 22632 public void setValue(View object, float value) { 22633 object.setTranslationX(value); 22634 } 22635 22636 @Override 22637 public Float get(View object) { 22638 return object.getTranslationX(); 22639 } 22640 }; 22641 22642 /** 22643 * A Property wrapper around the <code>translationY</code> functionality handled by the 22644 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 22645 */ 22646 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 22647 @Override 22648 public void setValue(View object, float value) { 22649 object.setTranslationY(value); 22650 } 22651 22652 @Override 22653 public Float get(View object) { 22654 return object.getTranslationY(); 22655 } 22656 }; 22657 22658 /** 22659 * A Property wrapper around the <code>translationZ</code> functionality handled by the 22660 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 22661 */ 22662 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 22663 @Override 22664 public void setValue(View object, float value) { 22665 object.setTranslationZ(value); 22666 } 22667 22668 @Override 22669 public Float get(View object) { 22670 return object.getTranslationZ(); 22671 } 22672 }; 22673 22674 /** 22675 * A Property wrapper around the <code>x</code> functionality handled by the 22676 * {@link View#setX(float)} and {@link View#getX()} methods. 22677 */ 22678 public static final Property<View, Float> X = new FloatProperty<View>("x") { 22679 @Override 22680 public void setValue(View object, float value) { 22681 object.setX(value); 22682 } 22683 22684 @Override 22685 public Float get(View object) { 22686 return object.getX(); 22687 } 22688 }; 22689 22690 /** 22691 * A Property wrapper around the <code>y</code> functionality handled by the 22692 * {@link View#setY(float)} and {@link View#getY()} methods. 22693 */ 22694 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 22695 @Override 22696 public void setValue(View object, float value) { 22697 object.setY(value); 22698 } 22699 22700 @Override 22701 public Float get(View object) { 22702 return object.getY(); 22703 } 22704 }; 22705 22706 /** 22707 * A Property wrapper around the <code>z</code> functionality handled by the 22708 * {@link View#setZ(float)} and {@link View#getZ()} methods. 22709 */ 22710 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 22711 @Override 22712 public void setValue(View object, float value) { 22713 object.setZ(value); 22714 } 22715 22716 @Override 22717 public Float get(View object) { 22718 return object.getZ(); 22719 } 22720 }; 22721 22722 /** 22723 * A Property wrapper around the <code>rotation</code> functionality handled by the 22724 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22725 */ 22726 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22727 @Override 22728 public void setValue(View object, float value) { 22729 object.setRotation(value); 22730 } 22731 22732 @Override 22733 public Float get(View object) { 22734 return object.getRotation(); 22735 } 22736 }; 22737 22738 /** 22739 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22740 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22741 */ 22742 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22743 @Override 22744 public void setValue(View object, float value) { 22745 object.setRotationX(value); 22746 } 22747 22748 @Override 22749 public Float get(View object) { 22750 return object.getRotationX(); 22751 } 22752 }; 22753 22754 /** 22755 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22756 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22757 */ 22758 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22759 @Override 22760 public void setValue(View object, float value) { 22761 object.setRotationY(value); 22762 } 22763 22764 @Override 22765 public Float get(View object) { 22766 return object.getRotationY(); 22767 } 22768 }; 22769 22770 /** 22771 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22772 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22773 */ 22774 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22775 @Override 22776 public void setValue(View object, float value) { 22777 object.setScaleX(value); 22778 } 22779 22780 @Override 22781 public Float get(View object) { 22782 return object.getScaleX(); 22783 } 22784 }; 22785 22786 /** 22787 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22788 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22789 */ 22790 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22791 @Override 22792 public void setValue(View object, float value) { 22793 object.setScaleY(value); 22794 } 22795 22796 @Override 22797 public Float get(View object) { 22798 return object.getScaleY(); 22799 } 22800 }; 22801 22802 /** 22803 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22804 * Each MeasureSpec represents a requirement for either the width or the height. 22805 * A MeasureSpec is comprised of a size and a mode. There are three possible 22806 * modes: 22807 * <dl> 22808 * <dt>UNSPECIFIED</dt> 22809 * <dd> 22810 * The parent has not imposed any constraint on the child. It can be whatever size 22811 * it wants. 22812 * </dd> 22813 * 22814 * <dt>EXACTLY</dt> 22815 * <dd> 22816 * The parent has determined an exact size for the child. The child is going to be 22817 * given those bounds regardless of how big it wants to be. 22818 * </dd> 22819 * 22820 * <dt>AT_MOST</dt> 22821 * <dd> 22822 * The child can be as large as it wants up to the specified size. 22823 * </dd> 22824 * </dl> 22825 * 22826 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22827 * is provided to pack and unpack the <size, mode> tuple into the int. 22828 */ 22829 public static class MeasureSpec { 22830 private static final int MODE_SHIFT = 30; 22831 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22832 22833 /** @hide */ 22834 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22835 @Retention(RetentionPolicy.SOURCE) 22836 public @interface MeasureSpecMode {} 22837 22838 /** 22839 * Measure specification mode: The parent has not imposed any constraint 22840 * on the child. It can be whatever size it wants. 22841 */ 22842 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22843 22844 /** 22845 * Measure specification mode: The parent has determined an exact size 22846 * for the child. The child is going to be given those bounds regardless 22847 * of how big it wants to be. 22848 */ 22849 public static final int EXACTLY = 1 << MODE_SHIFT; 22850 22851 /** 22852 * Measure specification mode: The child can be as large as it wants up 22853 * to the specified size. 22854 */ 22855 public static final int AT_MOST = 2 << MODE_SHIFT; 22856 22857 /** 22858 * Creates a measure specification based on the supplied size and mode. 22859 * 22860 * The mode must always be one of the following: 22861 * <ul> 22862 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22863 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22864 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22865 * </ul> 22866 * 22867 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22868 * implementation was such that the order of arguments did not matter 22869 * and overflow in either value could impact the resulting MeasureSpec. 22870 * {@link android.widget.RelativeLayout} was affected by this bug. 22871 * Apps targeting API levels greater than 17 will get the fixed, more strict 22872 * behavior.</p> 22873 * 22874 * @param size the size of the measure specification 22875 * @param mode the mode of the measure specification 22876 * @return the measure specification based on size and mode 22877 */ 22878 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22879 @MeasureSpecMode int mode) { 22880 if (sUseBrokenMakeMeasureSpec) { 22881 return size + mode; 22882 } else { 22883 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22884 } 22885 } 22886 22887 /** 22888 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22889 * will automatically get a size of 0. Older apps expect this. 22890 * 22891 * @hide internal use only for compatibility with system widgets and older apps 22892 */ 22893 public static int makeSafeMeasureSpec(int size, int mode) { 22894 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22895 return 0; 22896 } 22897 return makeMeasureSpec(size, mode); 22898 } 22899 22900 /** 22901 * Extracts the mode from the supplied measure specification. 22902 * 22903 * @param measureSpec the measure specification to extract the mode from 22904 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22905 * {@link android.view.View.MeasureSpec#AT_MOST} or 22906 * {@link android.view.View.MeasureSpec#EXACTLY} 22907 */ 22908 @MeasureSpecMode 22909 public static int getMode(int measureSpec) { 22910 //noinspection ResourceType 22911 return (measureSpec & MODE_MASK); 22912 } 22913 22914 /** 22915 * Extracts the size from the supplied measure specification. 22916 * 22917 * @param measureSpec the measure specification to extract the size from 22918 * @return the size in pixels defined in the supplied measure specification 22919 */ 22920 public static int getSize(int measureSpec) { 22921 return (measureSpec & ~MODE_MASK); 22922 } 22923 22924 static int adjust(int measureSpec, int delta) { 22925 final int mode = getMode(measureSpec); 22926 int size = getSize(measureSpec); 22927 if (mode == UNSPECIFIED) { 22928 // No need to adjust size for UNSPECIFIED mode. 22929 return makeMeasureSpec(size, UNSPECIFIED); 22930 } 22931 size += delta; 22932 if (size < 0) { 22933 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22934 ") spec: " + toString(measureSpec) + " delta: " + delta); 22935 size = 0; 22936 } 22937 return makeMeasureSpec(size, mode); 22938 } 22939 22940 /** 22941 * Returns a String representation of the specified measure 22942 * specification. 22943 * 22944 * @param measureSpec the measure specification to convert to a String 22945 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22946 */ 22947 public static String toString(int measureSpec) { 22948 int mode = getMode(measureSpec); 22949 int size = getSize(measureSpec); 22950 22951 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22952 22953 if (mode == UNSPECIFIED) 22954 sb.append("UNSPECIFIED "); 22955 else if (mode == EXACTLY) 22956 sb.append("EXACTLY "); 22957 else if (mode == AT_MOST) 22958 sb.append("AT_MOST "); 22959 else 22960 sb.append(mode).append(" "); 22961 22962 sb.append(size); 22963 return sb.toString(); 22964 } 22965 } 22966 22967 private final class CheckForLongPress implements Runnable { 22968 private int mOriginalWindowAttachCount; 22969 private float mX; 22970 private float mY; 22971 private boolean mOriginalPressedState; 22972 22973 @Override 22974 public void run() { 22975 if ((mOriginalPressedState == isPressed()) && (mParent != null) 22976 && mOriginalWindowAttachCount == mWindowAttachCount) { 22977 if (performLongClick(mX, mY)) { 22978 mHasPerformedLongPress = true; 22979 } 22980 } 22981 } 22982 22983 public void setAnchor(float x, float y) { 22984 mX = x; 22985 mY = y; 22986 } 22987 22988 public void rememberWindowAttachCount() { 22989 mOriginalWindowAttachCount = mWindowAttachCount; 22990 } 22991 22992 public void rememberPressedState() { 22993 mOriginalPressedState = isPressed(); 22994 } 22995 } 22996 22997 private final class CheckForTap implements Runnable { 22998 public float x; 22999 public float y; 23000 23001 @Override 23002 public void run() { 23003 mPrivateFlags &= ~PFLAG_PREPRESSED; 23004 setPressed(true, x, y); 23005 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 23006 } 23007 } 23008 23009 private final class PerformClick implements Runnable { 23010 @Override 23011 public void run() { 23012 performClick(); 23013 } 23014 } 23015 23016 /** 23017 * This method returns a ViewPropertyAnimator object, which can be used to animate 23018 * specific properties on this View. 23019 * 23020 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 23021 */ 23022 public ViewPropertyAnimator animate() { 23023 if (mAnimator == null) { 23024 mAnimator = new ViewPropertyAnimator(this); 23025 } 23026 return mAnimator; 23027 } 23028 23029 /** 23030 * Sets the name of the View to be used to identify Views in Transitions. 23031 * Names should be unique in the View hierarchy. 23032 * 23033 * @param transitionName The name of the View to uniquely identify it for Transitions. 23034 */ 23035 public final void setTransitionName(String transitionName) { 23036 mTransitionName = transitionName; 23037 } 23038 23039 /** 23040 * Returns the name of the View to be used to identify Views in Transitions. 23041 * Names should be unique in the View hierarchy. 23042 * 23043 * <p>This returns null if the View has not been given a name.</p> 23044 * 23045 * @return The name used of the View to be used to identify Views in Transitions or null 23046 * if no name has been given. 23047 */ 23048 @ViewDebug.ExportedProperty 23049 public String getTransitionName() { 23050 return mTransitionName; 23051 } 23052 23053 /** 23054 * @hide 23055 */ 23056 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 23057 // Do nothing. 23058 } 23059 23060 /** 23061 * Interface definition for a callback to be invoked when a hardware key event is 23062 * dispatched to this view. The callback will be invoked before the key event is 23063 * given to the view. This is only useful for hardware keyboards; a software input 23064 * method has no obligation to trigger this listener. 23065 */ 23066 public interface OnKeyListener { 23067 /** 23068 * Called when a hardware key is dispatched to a view. This allows listeners to 23069 * get a chance to respond before the target view. 23070 * <p>Key presses in software keyboards will generally NOT trigger this method, 23071 * although some may elect to do so in some situations. Do not assume a 23072 * software input method has to be key-based; even if it is, it may use key presses 23073 * in a different way than you expect, so there is no way to reliably catch soft 23074 * input key presses. 23075 * 23076 * @param v The view the key has been dispatched to. 23077 * @param keyCode The code for the physical key that was pressed 23078 * @param event The KeyEvent object containing full information about 23079 * the event. 23080 * @return True if the listener has consumed the event, false otherwise. 23081 */ 23082 boolean onKey(View v, int keyCode, KeyEvent event); 23083 } 23084 23085 /** 23086 * Interface definition for a callback to be invoked when a touch event is 23087 * dispatched to this view. The callback will be invoked before the touch 23088 * event is given to the view. 23089 */ 23090 public interface OnTouchListener { 23091 /** 23092 * Called when a touch event is dispatched to a view. This allows listeners to 23093 * get a chance to respond before the target view. 23094 * 23095 * @param v The view the touch event has been dispatched to. 23096 * @param event The MotionEvent object containing full information about 23097 * the event. 23098 * @return True if the listener has consumed the event, false otherwise. 23099 */ 23100 boolean onTouch(View v, MotionEvent event); 23101 } 23102 23103 /** 23104 * Interface definition for a callback to be invoked when a hover event is 23105 * dispatched to this view. The callback will be invoked before the hover 23106 * event is given to the view. 23107 */ 23108 public interface OnHoverListener { 23109 /** 23110 * Called when a hover event is dispatched to a view. This allows listeners to 23111 * get a chance to respond before the target view. 23112 * 23113 * @param v The view the hover event has been dispatched to. 23114 * @param event The MotionEvent object containing full information about 23115 * the event. 23116 * @return True if the listener has consumed the event, false otherwise. 23117 */ 23118 boolean onHover(View v, MotionEvent event); 23119 } 23120 23121 /** 23122 * Interface definition for a callback to be invoked when a generic motion event is 23123 * dispatched to this view. The callback will be invoked before the generic motion 23124 * event is given to the view. 23125 */ 23126 public interface OnGenericMotionListener { 23127 /** 23128 * Called when a generic motion event is dispatched to a view. This allows listeners to 23129 * get a chance to respond before the target view. 23130 * 23131 * @param v The view the generic motion event has been dispatched to. 23132 * @param event The MotionEvent object containing full information about 23133 * the event. 23134 * @return True if the listener has consumed the event, false otherwise. 23135 */ 23136 boolean onGenericMotion(View v, MotionEvent event); 23137 } 23138 23139 /** 23140 * Interface definition for a callback to be invoked when a view has been clicked and held. 23141 */ 23142 public interface OnLongClickListener { 23143 /** 23144 * Called when a view has been clicked and held. 23145 * 23146 * @param v The view that was clicked and held. 23147 * 23148 * @return true if the callback consumed the long click, false otherwise. 23149 */ 23150 boolean onLongClick(View v); 23151 } 23152 23153 /** 23154 * Interface definition for a callback to be invoked when a drag is being dispatched 23155 * to this view. The callback will be invoked before the hosting view's own 23156 * onDrag(event) method. If the listener wants to fall back to the hosting view's 23157 * onDrag(event) behavior, it should return 'false' from this callback. 23158 * 23159 * <div class="special reference"> 23160 * <h3>Developer Guides</h3> 23161 * <p>For a guide to implementing drag and drop features, read the 23162 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 23163 * </div> 23164 */ 23165 public interface OnDragListener { 23166 /** 23167 * Called when a drag event is dispatched to a view. This allows listeners 23168 * to get a chance to override base View behavior. 23169 * 23170 * @param v The View that received the drag event. 23171 * @param event The {@link android.view.DragEvent} object for the drag event. 23172 * @return {@code true} if the drag event was handled successfully, or {@code false} 23173 * if the drag event was not handled. Note that {@code false} will trigger the View 23174 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 23175 */ 23176 boolean onDrag(View v, DragEvent event); 23177 } 23178 23179 /** 23180 * Interface definition for a callback to be invoked when the focus state of 23181 * a view changed. 23182 */ 23183 public interface OnFocusChangeListener { 23184 /** 23185 * Called when the focus state of a view has changed. 23186 * 23187 * @param v The view whose state has changed. 23188 * @param hasFocus The new focus state of v. 23189 */ 23190 void onFocusChange(View v, boolean hasFocus); 23191 } 23192 23193 /** 23194 * Interface definition for a callback to be invoked when a view is clicked. 23195 */ 23196 public interface OnClickListener { 23197 /** 23198 * Called when a view has been clicked. 23199 * 23200 * @param v The view that was clicked. 23201 */ 23202 void onClick(View v); 23203 } 23204 23205 /** 23206 * Interface definition for a callback to be invoked when a view is context clicked. 23207 */ 23208 public interface OnContextClickListener { 23209 /** 23210 * Called when a view is context clicked. 23211 * 23212 * @param v The view that has been context clicked. 23213 * @return true if the callback consumed the context click, false otherwise. 23214 */ 23215 boolean onContextClick(View v); 23216 } 23217 23218 /** 23219 * Interface definition for a callback to be invoked when the context menu 23220 * for this view is being built. 23221 */ 23222 public interface OnCreateContextMenuListener { 23223 /** 23224 * Called when the context menu for this view is being built. It is not 23225 * safe to hold onto the menu after this method returns. 23226 * 23227 * @param menu The context menu that is being built 23228 * @param v The view for which the context menu is being built 23229 * @param menuInfo Extra information about the item for which the 23230 * context menu should be shown. This information will vary 23231 * depending on the class of v. 23232 */ 23233 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 23234 } 23235 23236 /** 23237 * Interface definition for a callback to be invoked when the status bar changes 23238 * visibility. This reports <strong>global</strong> changes to the system UI 23239 * state, not what the application is requesting. 23240 * 23241 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 23242 */ 23243 public interface OnSystemUiVisibilityChangeListener { 23244 /** 23245 * Called when the status bar changes visibility because of a call to 23246 * {@link View#setSystemUiVisibility(int)}. 23247 * 23248 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 23249 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 23250 * This tells you the <strong>global</strong> state of these UI visibility 23251 * flags, not what your app is currently applying. 23252 */ 23253 public void onSystemUiVisibilityChange(int visibility); 23254 } 23255 23256 /** 23257 * Interface definition for a callback to be invoked when this view is attached 23258 * or detached from its window. 23259 */ 23260 public interface OnAttachStateChangeListener { 23261 /** 23262 * Called when the view is attached to a window. 23263 * @param v The view that was attached 23264 */ 23265 public void onViewAttachedToWindow(View v); 23266 /** 23267 * Called when the view is detached from a window. 23268 * @param v The view that was detached 23269 */ 23270 public void onViewDetachedFromWindow(View v); 23271 } 23272 23273 /** 23274 * Listener for applying window insets on a view in a custom way. 23275 * 23276 * <p>Apps may choose to implement this interface if they want to apply custom policy 23277 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 23278 * is set, its 23279 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 23280 * method will be called instead of the View's own 23281 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 23282 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 23283 * the View's normal behavior as part of its own.</p> 23284 */ 23285 public interface OnApplyWindowInsetsListener { 23286 /** 23287 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 23288 * on a View, this listener method will be called instead of the view's own 23289 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 23290 * 23291 * @param v The view applying window insets 23292 * @param insets The insets to apply 23293 * @return The insets supplied, minus any insets that were consumed 23294 */ 23295 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 23296 } 23297 23298 private final class UnsetPressedState implements Runnable { 23299 @Override 23300 public void run() { 23301 setPressed(false); 23302 } 23303 } 23304 23305 /** 23306 * Base class for derived classes that want to save and restore their own 23307 * state in {@link android.view.View#onSaveInstanceState()}. 23308 */ 23309 public static class BaseSavedState extends AbsSavedState { 23310 String mStartActivityRequestWhoSaved; 23311 23312 /** 23313 * Constructor used when reading from a parcel. Reads the state of the superclass. 23314 * 23315 * @param source parcel to read from 23316 */ 23317 public BaseSavedState(Parcel source) { 23318 this(source, null); 23319 } 23320 23321 /** 23322 * Constructor used when reading from a parcel using a given class loader. 23323 * Reads the state of the superclass. 23324 * 23325 * @param source parcel to read from 23326 * @param loader ClassLoader to use for reading 23327 */ 23328 public BaseSavedState(Parcel source, ClassLoader loader) { 23329 super(source, loader); 23330 mStartActivityRequestWhoSaved = source.readString(); 23331 } 23332 23333 /** 23334 * Constructor called by derived classes when creating their SavedState objects 23335 * 23336 * @param superState The state of the superclass of this view 23337 */ 23338 public BaseSavedState(Parcelable superState) { 23339 super(superState); 23340 } 23341 23342 @Override 23343 public void writeToParcel(Parcel out, int flags) { 23344 super.writeToParcel(out, flags); 23345 out.writeString(mStartActivityRequestWhoSaved); 23346 } 23347 23348 public static final Parcelable.Creator<BaseSavedState> CREATOR 23349 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 23350 @Override 23351 public BaseSavedState createFromParcel(Parcel in) { 23352 return new BaseSavedState(in); 23353 } 23354 23355 @Override 23356 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 23357 return new BaseSavedState(in, loader); 23358 } 23359 23360 @Override 23361 public BaseSavedState[] newArray(int size) { 23362 return new BaseSavedState[size]; 23363 } 23364 }; 23365 } 23366 23367 /** 23368 * A set of information given to a view when it is attached to its parent 23369 * window. 23370 */ 23371 final static class AttachInfo { 23372 interface Callbacks { 23373 void playSoundEffect(int effectId); 23374 boolean performHapticFeedback(int effectId, boolean always); 23375 } 23376 23377 /** 23378 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 23379 * to a Handler. This class contains the target (View) to invalidate and 23380 * the coordinates of the dirty rectangle. 23381 * 23382 * For performance purposes, this class also implements a pool of up to 23383 * POOL_LIMIT objects that get reused. This reduces memory allocations 23384 * whenever possible. 23385 */ 23386 static class InvalidateInfo { 23387 private static final int POOL_LIMIT = 10; 23388 23389 private static final SynchronizedPool<InvalidateInfo> sPool = 23390 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 23391 23392 View target; 23393 23394 int left; 23395 int top; 23396 int right; 23397 int bottom; 23398 23399 public static InvalidateInfo obtain() { 23400 InvalidateInfo instance = sPool.acquire(); 23401 return (instance != null) ? instance : new InvalidateInfo(); 23402 } 23403 23404 public void recycle() { 23405 target = null; 23406 sPool.release(this); 23407 } 23408 } 23409 23410 final IWindowSession mSession; 23411 23412 final IWindow mWindow; 23413 23414 final IBinder mWindowToken; 23415 23416 final Display mDisplay; 23417 23418 final Callbacks mRootCallbacks; 23419 23420 IWindowId mIWindowId; 23421 WindowId mWindowId; 23422 23423 /** 23424 * The top view of the hierarchy. 23425 */ 23426 View mRootView; 23427 23428 IBinder mPanelParentWindowToken; 23429 23430 boolean mHardwareAccelerated; 23431 boolean mHardwareAccelerationRequested; 23432 ThreadedRenderer mThreadedRenderer; 23433 List<RenderNode> mPendingAnimatingRenderNodes; 23434 23435 /** 23436 * The state of the display to which the window is attached, as reported 23437 * by {@link Display#getState()}. Note that the display state constants 23438 * declared by {@link Display} do not exactly line up with the screen state 23439 * constants declared by {@link View} (there are more display states than 23440 * screen states). 23441 */ 23442 int mDisplayState = Display.STATE_UNKNOWN; 23443 23444 /** 23445 * Scale factor used by the compatibility mode 23446 */ 23447 float mApplicationScale; 23448 23449 /** 23450 * Indicates whether the application is in compatibility mode 23451 */ 23452 boolean mScalingRequired; 23453 23454 /** 23455 * Left position of this view's window 23456 */ 23457 int mWindowLeft; 23458 23459 /** 23460 * Top position of this view's window 23461 */ 23462 int mWindowTop; 23463 23464 /** 23465 * Indicates whether views need to use 32-bit drawing caches 23466 */ 23467 boolean mUse32BitDrawingCache; 23468 23469 /** 23470 * For windows that are full-screen but using insets to layout inside 23471 * of the screen areas, these are the current insets to appear inside 23472 * the overscan area of the display. 23473 */ 23474 final Rect mOverscanInsets = new Rect(); 23475 23476 /** 23477 * For windows that are full-screen but using insets to layout inside 23478 * of the screen decorations, these are the current insets for the 23479 * content of the window. 23480 */ 23481 final Rect mContentInsets = new Rect(); 23482 23483 /** 23484 * For windows that are full-screen but using insets to layout inside 23485 * of the screen decorations, these are the current insets for the 23486 * actual visible parts of the window. 23487 */ 23488 final Rect mVisibleInsets = new Rect(); 23489 23490 /** 23491 * For windows that are full-screen but using insets to layout inside 23492 * of the screen decorations, these are the current insets for the 23493 * stable system windows. 23494 */ 23495 final Rect mStableInsets = new Rect(); 23496 23497 /** 23498 * For windows that include areas that are not covered by real surface these are the outsets 23499 * for real surface. 23500 */ 23501 final Rect mOutsets = new Rect(); 23502 23503 /** 23504 * In multi-window we force show the navigation bar. Because we don't want that the surface 23505 * size changes in this mode, we instead have a flag whether the navigation bar size should 23506 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 23507 */ 23508 boolean mAlwaysConsumeNavBar; 23509 23510 /** 23511 * The internal insets given by this window. This value is 23512 * supplied by the client (through 23513 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 23514 * be given to the window manager when changed to be used in laying 23515 * out windows behind it. 23516 */ 23517 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 23518 = new ViewTreeObserver.InternalInsetsInfo(); 23519 23520 /** 23521 * Set to true when mGivenInternalInsets is non-empty. 23522 */ 23523 boolean mHasNonEmptyGivenInternalInsets; 23524 23525 /** 23526 * All views in the window's hierarchy that serve as scroll containers, 23527 * used to determine if the window can be resized or must be panned 23528 * to adjust for a soft input area. 23529 */ 23530 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 23531 23532 final KeyEvent.DispatcherState mKeyDispatchState 23533 = new KeyEvent.DispatcherState(); 23534 23535 /** 23536 * Indicates whether the view's window currently has the focus. 23537 */ 23538 boolean mHasWindowFocus; 23539 23540 /** 23541 * The current visibility of the window. 23542 */ 23543 int mWindowVisibility; 23544 23545 /** 23546 * Indicates the time at which drawing started to occur. 23547 */ 23548 long mDrawingTime; 23549 23550 /** 23551 * Indicates whether or not ignoring the DIRTY_MASK flags. 23552 */ 23553 boolean mIgnoreDirtyState; 23554 23555 /** 23556 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 23557 * to avoid clearing that flag prematurely. 23558 */ 23559 boolean mSetIgnoreDirtyState = false; 23560 23561 /** 23562 * Indicates whether the view's window is currently in touch mode. 23563 */ 23564 boolean mInTouchMode; 23565 23566 /** 23567 * Indicates whether the view has requested unbuffered input dispatching for the current 23568 * event stream. 23569 */ 23570 boolean mUnbufferedDispatchRequested; 23571 23572 /** 23573 * Indicates that ViewAncestor should trigger a global layout change 23574 * the next time it performs a traversal 23575 */ 23576 boolean mRecomputeGlobalAttributes; 23577 23578 /** 23579 * Always report new attributes at next traversal. 23580 */ 23581 boolean mForceReportNewAttributes; 23582 23583 /** 23584 * Set during a traveral if any views want to keep the screen on. 23585 */ 23586 boolean mKeepScreenOn; 23587 23588 /** 23589 * Set during a traveral if the light center needs to be updated. 23590 */ 23591 boolean mNeedsUpdateLightCenter; 23592 23593 /** 23594 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 23595 */ 23596 int mSystemUiVisibility; 23597 23598 /** 23599 * Hack to force certain system UI visibility flags to be cleared. 23600 */ 23601 int mDisabledSystemUiVisibility; 23602 23603 /** 23604 * Last global system UI visibility reported by the window manager. 23605 */ 23606 int mGlobalSystemUiVisibility = -1; 23607 23608 /** 23609 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 23610 * attached. 23611 */ 23612 boolean mHasSystemUiListeners; 23613 23614 /** 23615 * Set if the window has requested to extend into the overscan region 23616 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 23617 */ 23618 boolean mOverscanRequested; 23619 23620 /** 23621 * Set if the visibility of any views has changed. 23622 */ 23623 boolean mViewVisibilityChanged; 23624 23625 /** 23626 * Set to true if a view has been scrolled. 23627 */ 23628 boolean mViewScrollChanged; 23629 23630 /** 23631 * Set to true if high contrast mode enabled 23632 */ 23633 boolean mHighContrastText; 23634 23635 /** 23636 * Set to true if a pointer event is currently being handled. 23637 */ 23638 boolean mHandlingPointerEvent; 23639 23640 /** 23641 * Global to the view hierarchy used as a temporary for dealing with 23642 * x/y points in the transparent region computations. 23643 */ 23644 final int[] mTransparentLocation = new int[2]; 23645 23646 /** 23647 * Global to the view hierarchy used as a temporary for dealing with 23648 * x/y points in the ViewGroup.invalidateChild implementation. 23649 */ 23650 final int[] mInvalidateChildLocation = new int[2]; 23651 23652 /** 23653 * Global to the view hierarchy used as a temporary for dealing with 23654 * computing absolute on-screen location. 23655 */ 23656 final int[] mTmpLocation = new int[2]; 23657 23658 /** 23659 * Global to the view hierarchy used as a temporary for dealing with 23660 * x/y location when view is transformed. 23661 */ 23662 final float[] mTmpTransformLocation = new float[2]; 23663 23664 /** 23665 * The view tree observer used to dispatch global events like 23666 * layout, pre-draw, touch mode change, etc. 23667 */ 23668 final ViewTreeObserver mTreeObserver; 23669 23670 /** 23671 * A Canvas used by the view hierarchy to perform bitmap caching. 23672 */ 23673 Canvas mCanvas; 23674 23675 /** 23676 * The view root impl. 23677 */ 23678 final ViewRootImpl mViewRootImpl; 23679 23680 /** 23681 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 23682 * handler can be used to pump events in the UI events queue. 23683 */ 23684 final Handler mHandler; 23685 23686 /** 23687 * Temporary for use in computing invalidate rectangles while 23688 * calling up the hierarchy. 23689 */ 23690 final Rect mTmpInvalRect = new Rect(); 23691 23692 /** 23693 * Temporary for use in computing hit areas with transformed views 23694 */ 23695 final RectF mTmpTransformRect = new RectF(); 23696 23697 /** 23698 * Temporary for use in computing hit areas with transformed views 23699 */ 23700 final RectF mTmpTransformRect1 = new RectF(); 23701 23702 /** 23703 * Temporary list of rectanges. 23704 */ 23705 final List<RectF> mTmpRectList = new ArrayList<>(); 23706 23707 /** 23708 * Temporary for use in transforming invalidation rect 23709 */ 23710 final Matrix mTmpMatrix = new Matrix(); 23711 23712 /** 23713 * Temporary for use in transforming invalidation rect 23714 */ 23715 final Transformation mTmpTransformation = new Transformation(); 23716 23717 /** 23718 * Temporary for use in querying outlines from OutlineProviders 23719 */ 23720 final Outline mTmpOutline = new Outline(); 23721 23722 /** 23723 * Temporary list for use in collecting focusable descendents of a view. 23724 */ 23725 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 23726 23727 /** 23728 * The id of the window for accessibility purposes. 23729 */ 23730 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 23731 23732 /** 23733 * Flags related to accessibility processing. 23734 * 23735 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23736 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23737 */ 23738 int mAccessibilityFetchFlags; 23739 23740 /** 23741 * The drawable for highlighting accessibility focus. 23742 */ 23743 Drawable mAccessibilityFocusDrawable; 23744 23745 /** 23746 * Show where the margins, bounds and layout bounds are for each view. 23747 */ 23748 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23749 23750 /** 23751 * Point used to compute visible regions. 23752 */ 23753 final Point mPoint = new Point(); 23754 23755 /** 23756 * Used to track which View originated a requestLayout() call, used when 23757 * requestLayout() is called during layout. 23758 */ 23759 View mViewRequestingLayout; 23760 23761 /** 23762 * Used to track views that need (at least) a partial relayout at their current size 23763 * during the next traversal. 23764 */ 23765 List<View> mPartialLayoutViews = new ArrayList<>(); 23766 23767 /** 23768 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23769 * modification. Lazily assigned during ViewRootImpl layout. 23770 */ 23771 List<View> mEmptyPartialLayoutViews; 23772 23773 /** 23774 * Used to track the identity of the current drag operation. 23775 */ 23776 IBinder mDragToken; 23777 23778 /** 23779 * The drag shadow surface for the current drag operation. 23780 */ 23781 public Surface mDragSurface; 23782 23783 23784 /** 23785 * The view that currently has a tooltip displayed. 23786 */ 23787 View mTooltipHost; 23788 23789 /** 23790 * Creates a new set of attachment information with the specified 23791 * events handler and thread. 23792 * 23793 * @param handler the events handler the view must use 23794 */ 23795 AttachInfo(IWindowSession session, IWindow window, Display display, 23796 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 23797 Context context) { 23798 mSession = session; 23799 mWindow = window; 23800 mWindowToken = window.asBinder(); 23801 mDisplay = display; 23802 mViewRootImpl = viewRootImpl; 23803 mHandler = handler; 23804 mRootCallbacks = effectPlayer; 23805 mTreeObserver = new ViewTreeObserver(context); 23806 } 23807 } 23808 23809 /** 23810 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23811 * is supported. This avoids keeping too many unused fields in most 23812 * instances of View.</p> 23813 */ 23814 private static class ScrollabilityCache implements Runnable { 23815 23816 /** 23817 * Scrollbars are not visible 23818 */ 23819 public static final int OFF = 0; 23820 23821 /** 23822 * Scrollbars are visible 23823 */ 23824 public static final int ON = 1; 23825 23826 /** 23827 * Scrollbars are fading away 23828 */ 23829 public static final int FADING = 2; 23830 23831 public boolean fadeScrollBars; 23832 23833 public int fadingEdgeLength; 23834 public int scrollBarDefaultDelayBeforeFade; 23835 public int scrollBarFadeDuration; 23836 23837 public int scrollBarSize; 23838 public ScrollBarDrawable scrollBar; 23839 public float[] interpolatorValues; 23840 public View host; 23841 23842 public final Paint paint; 23843 public final Matrix matrix; 23844 public Shader shader; 23845 23846 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23847 23848 private static final float[] OPAQUE = { 255 }; 23849 private static final float[] TRANSPARENT = { 0.0f }; 23850 23851 /** 23852 * When fading should start. This time moves into the future every time 23853 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23854 */ 23855 public long fadeStartTime; 23856 23857 23858 /** 23859 * The current state of the scrollbars: ON, OFF, or FADING 23860 */ 23861 public int state = OFF; 23862 23863 private int mLastColor; 23864 23865 public final Rect mScrollBarBounds = new Rect(); 23866 23867 public static final int NOT_DRAGGING = 0; 23868 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23869 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23870 public int mScrollBarDraggingState = NOT_DRAGGING; 23871 23872 public float mScrollBarDraggingPos = 0; 23873 23874 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23875 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23876 scrollBarSize = configuration.getScaledScrollBarSize(); 23877 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23878 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23879 23880 paint = new Paint(); 23881 matrix = new Matrix(); 23882 // use use a height of 1, and then wack the matrix each time we 23883 // actually use it. 23884 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23885 paint.setShader(shader); 23886 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23887 23888 this.host = host; 23889 } 23890 23891 public void setFadeColor(int color) { 23892 if (color != mLastColor) { 23893 mLastColor = color; 23894 23895 if (color != 0) { 23896 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23897 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23898 paint.setShader(shader); 23899 // Restore the default transfer mode (src_over) 23900 paint.setXfermode(null); 23901 } else { 23902 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23903 paint.setShader(shader); 23904 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23905 } 23906 } 23907 } 23908 23909 public void run() { 23910 long now = AnimationUtils.currentAnimationTimeMillis(); 23911 if (now >= fadeStartTime) { 23912 23913 // the animation fades the scrollbars out by changing 23914 // the opacity (alpha) from fully opaque to fully 23915 // transparent 23916 int nextFrame = (int) now; 23917 int framesCount = 0; 23918 23919 Interpolator interpolator = scrollBarInterpolator; 23920 23921 // Start opaque 23922 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23923 23924 // End transparent 23925 nextFrame += scrollBarFadeDuration; 23926 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23927 23928 state = FADING; 23929 23930 // Kick off the fade animation 23931 host.invalidate(true); 23932 } 23933 } 23934 } 23935 23936 /** 23937 * Resuable callback for sending 23938 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23939 */ 23940 private class SendViewScrolledAccessibilityEvent implements Runnable { 23941 public volatile boolean mIsPending; 23942 23943 public void run() { 23944 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23945 mIsPending = false; 23946 } 23947 } 23948 23949 /** 23950 * <p> 23951 * This class represents a delegate that can be registered in a {@link View} 23952 * to enhance accessibility support via composition rather via inheritance. 23953 * It is specifically targeted to widget developers that extend basic View 23954 * classes i.e. classes in package android.view, that would like their 23955 * applications to be backwards compatible. 23956 * </p> 23957 * <div class="special reference"> 23958 * <h3>Developer Guides</h3> 23959 * <p>For more information about making applications accessible, read the 23960 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23961 * developer guide.</p> 23962 * </div> 23963 * <p> 23964 * A scenario in which a developer would like to use an accessibility delegate 23965 * is overriding a method introduced in a later API version than the minimal API 23966 * version supported by the application. For example, the method 23967 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23968 * in API version 4 when the accessibility APIs were first introduced. If a 23969 * developer would like his application to run on API version 4 devices (assuming 23970 * all other APIs used by the application are version 4 or lower) and take advantage 23971 * of this method, instead of overriding the method which would break the application's 23972 * backwards compatibility, he can override the corresponding method in this 23973 * delegate and register the delegate in the target View if the API version of 23974 * the system is high enough, i.e. the API version is the same as or higher than the API 23975 * version that introduced 23976 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23977 * </p> 23978 * <p> 23979 * Here is an example implementation: 23980 * </p> 23981 * <code><pre><p> 23982 * if (Build.VERSION.SDK_INT >= 14) { 23983 * // If the API version is equal of higher than the version in 23984 * // which onInitializeAccessibilityNodeInfo was introduced we 23985 * // register a delegate with a customized implementation. 23986 * View view = findViewById(R.id.view_id); 23987 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23988 * public void onInitializeAccessibilityNodeInfo(View host, 23989 * AccessibilityNodeInfo info) { 23990 * // Let the default implementation populate the info. 23991 * super.onInitializeAccessibilityNodeInfo(host, info); 23992 * // Set some other information. 23993 * info.setEnabled(host.isEnabled()); 23994 * } 23995 * }); 23996 * } 23997 * </code></pre></p> 23998 * <p> 23999 * This delegate contains methods that correspond to the accessibility methods 24000 * in View. If a delegate has been specified the implementation in View hands 24001 * off handling to the corresponding method in this delegate. The default 24002 * implementation the delegate methods behaves exactly as the corresponding 24003 * method in View for the case of no accessibility delegate been set. Hence, 24004 * to customize the behavior of a View method, clients can override only the 24005 * corresponding delegate method without altering the behavior of the rest 24006 * accessibility related methods of the host view. 24007 * </p> 24008 * <p> 24009 * <strong>Note:</strong> On platform versions prior to 24010 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 24011 * views in the {@code android.widget.*} package are called <i>before</i> 24012 * host methods. This prevents certain properties such as class name from 24013 * being modified by overriding 24014 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 24015 * as any changes will be overwritten by the host class. 24016 * <p> 24017 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 24018 * methods are called <i>after</i> host methods, which all properties to be 24019 * modified without being overwritten by the host class. 24020 */ 24021 public static class AccessibilityDelegate { 24022 24023 /** 24024 * Sends an accessibility event of the given type. If accessibility is not 24025 * enabled this method has no effect. 24026 * <p> 24027 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 24028 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 24029 * been set. 24030 * </p> 24031 * 24032 * @param host The View hosting the delegate. 24033 * @param eventType The type of the event to send. 24034 * 24035 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 24036 */ 24037 public void sendAccessibilityEvent(View host, int eventType) { 24038 host.sendAccessibilityEventInternal(eventType); 24039 } 24040 24041 /** 24042 * Performs the specified accessibility action on the view. For 24043 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 24044 * <p> 24045 * The default implementation behaves as 24046 * {@link View#performAccessibilityAction(int, Bundle) 24047 * View#performAccessibilityAction(int, Bundle)} for the case of 24048 * no accessibility delegate been set. 24049 * </p> 24050 * 24051 * @param action The action to perform. 24052 * @return Whether the action was performed. 24053 * 24054 * @see View#performAccessibilityAction(int, Bundle) 24055 * View#performAccessibilityAction(int, Bundle) 24056 */ 24057 public boolean performAccessibilityAction(View host, int action, Bundle args) { 24058 return host.performAccessibilityActionInternal(action, args); 24059 } 24060 24061 /** 24062 * Sends an accessibility event. This method behaves exactly as 24063 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 24064 * empty {@link AccessibilityEvent} and does not perform a check whether 24065 * accessibility is enabled. 24066 * <p> 24067 * The default implementation behaves as 24068 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 24069 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 24070 * the case of no accessibility delegate been set. 24071 * </p> 24072 * 24073 * @param host The View hosting the delegate. 24074 * @param event The event to send. 24075 * 24076 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 24077 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 24078 */ 24079 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 24080 host.sendAccessibilityEventUncheckedInternal(event); 24081 } 24082 24083 /** 24084 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 24085 * to its children for adding their text content to the event. 24086 * <p> 24087 * The default implementation behaves as 24088 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 24089 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 24090 * the case of no accessibility delegate been set. 24091 * </p> 24092 * 24093 * @param host The View hosting the delegate. 24094 * @param event The event. 24095 * @return True if the event population was completed. 24096 * 24097 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 24098 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 24099 */ 24100 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 24101 return host.dispatchPopulateAccessibilityEventInternal(event); 24102 } 24103 24104 /** 24105 * Gives a chance to the host View to populate the accessibility event with its 24106 * text content. 24107 * <p> 24108 * The default implementation behaves as 24109 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 24110 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 24111 * the case of no accessibility delegate been set. 24112 * </p> 24113 * 24114 * @param host The View hosting the delegate. 24115 * @param event The accessibility event which to populate. 24116 * 24117 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 24118 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 24119 */ 24120 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 24121 host.onPopulateAccessibilityEventInternal(event); 24122 } 24123 24124 /** 24125 * Initializes an {@link AccessibilityEvent} with information about the 24126 * the host View which is the event source. 24127 * <p> 24128 * The default implementation behaves as 24129 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 24130 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 24131 * the case of no accessibility delegate been set. 24132 * </p> 24133 * 24134 * @param host The View hosting the delegate. 24135 * @param event The event to initialize. 24136 * 24137 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 24138 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 24139 */ 24140 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 24141 host.onInitializeAccessibilityEventInternal(event); 24142 } 24143 24144 /** 24145 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 24146 * <p> 24147 * The default implementation behaves as 24148 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 24149 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 24150 * the case of no accessibility delegate been set. 24151 * </p> 24152 * 24153 * @param host The View hosting the delegate. 24154 * @param info The instance to initialize. 24155 * 24156 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 24157 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 24158 */ 24159 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 24160 host.onInitializeAccessibilityNodeInfoInternal(info); 24161 } 24162 24163 /** 24164 * Called when a child of the host View has requested sending an 24165 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 24166 * to augment the event. 24167 * <p> 24168 * The default implementation behaves as 24169 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 24170 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 24171 * the case of no accessibility delegate been set. 24172 * </p> 24173 * 24174 * @param host The View hosting the delegate. 24175 * @param child The child which requests sending the event. 24176 * @param event The event to be sent. 24177 * @return True if the event should be sent 24178 * 24179 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 24180 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 24181 */ 24182 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 24183 AccessibilityEvent event) { 24184 return host.onRequestSendAccessibilityEventInternal(child, event); 24185 } 24186 24187 /** 24188 * Gets the provider for managing a virtual view hierarchy rooted at this View 24189 * and reported to {@link android.accessibilityservice.AccessibilityService}s 24190 * that explore the window content. 24191 * <p> 24192 * The default implementation behaves as 24193 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 24194 * the case of no accessibility delegate been set. 24195 * </p> 24196 * 24197 * @return The provider. 24198 * 24199 * @see AccessibilityNodeProvider 24200 */ 24201 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 24202 return null; 24203 } 24204 24205 /** 24206 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 24207 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 24208 * This method is responsible for obtaining an accessibility node info from a 24209 * pool of reusable instances and calling 24210 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 24211 * view to initialize the former. 24212 * <p> 24213 * <strong>Note:</strong> The client is responsible for recycling the obtained 24214 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 24215 * creation. 24216 * </p> 24217 * <p> 24218 * The default implementation behaves as 24219 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 24220 * the case of no accessibility delegate been set. 24221 * </p> 24222 * @return A populated {@link AccessibilityNodeInfo}. 24223 * 24224 * @see AccessibilityNodeInfo 24225 * 24226 * @hide 24227 */ 24228 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 24229 return host.createAccessibilityNodeInfoInternal(); 24230 } 24231 } 24232 24233 private class MatchIdPredicate implements Predicate<View> { 24234 public int mId; 24235 24236 @Override 24237 public boolean apply(View view) { 24238 return (view.mID == mId); 24239 } 24240 } 24241 24242 private class MatchLabelForPredicate implements Predicate<View> { 24243 private int mLabeledId; 24244 24245 @Override 24246 public boolean apply(View view) { 24247 return (view.mLabelForId == mLabeledId); 24248 } 24249 } 24250 24251 private class SendViewStateChangedAccessibilityEvent implements Runnable { 24252 private int mChangeTypes = 0; 24253 private boolean mPosted; 24254 private boolean mPostedWithDelay; 24255 private long mLastEventTimeMillis; 24256 24257 @Override 24258 public void run() { 24259 mPosted = false; 24260 mPostedWithDelay = false; 24261 mLastEventTimeMillis = SystemClock.uptimeMillis(); 24262 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 24263 final AccessibilityEvent event = AccessibilityEvent.obtain(); 24264 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 24265 event.setContentChangeTypes(mChangeTypes); 24266 sendAccessibilityEventUnchecked(event); 24267 } 24268 mChangeTypes = 0; 24269 } 24270 24271 public void runOrPost(int changeType) { 24272 mChangeTypes |= changeType; 24273 24274 // If this is a live region or the child of a live region, collect 24275 // all events from this frame and send them on the next frame. 24276 if (inLiveRegion()) { 24277 // If we're already posted with a delay, remove that. 24278 if (mPostedWithDelay) { 24279 removeCallbacks(this); 24280 mPostedWithDelay = false; 24281 } 24282 // Only post if we're not already posted. 24283 if (!mPosted) { 24284 post(this); 24285 mPosted = true; 24286 } 24287 return; 24288 } 24289 24290 if (mPosted) { 24291 return; 24292 } 24293 24294 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 24295 final long minEventIntevalMillis = 24296 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 24297 if (timeSinceLastMillis >= minEventIntevalMillis) { 24298 removeCallbacks(this); 24299 run(); 24300 } else { 24301 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 24302 mPostedWithDelay = true; 24303 } 24304 } 24305 } 24306 24307 private boolean inLiveRegion() { 24308 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 24309 return true; 24310 } 24311 24312 ViewParent parent = getParent(); 24313 while (parent instanceof View) { 24314 if (((View) parent).getAccessibilityLiveRegion() 24315 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 24316 return true; 24317 } 24318 parent = parent.getParent(); 24319 } 24320 24321 return false; 24322 } 24323 24324 /** 24325 * Dump all private flags in readable format, useful for documentation and 24326 * sanity checking. 24327 */ 24328 private static void dumpFlags() { 24329 final HashMap<String, String> found = Maps.newHashMap(); 24330 try { 24331 for (Field field : View.class.getDeclaredFields()) { 24332 final int modifiers = field.getModifiers(); 24333 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 24334 if (field.getType().equals(int.class)) { 24335 final int value = field.getInt(null); 24336 dumpFlag(found, field.getName(), value); 24337 } else if (field.getType().equals(int[].class)) { 24338 final int[] values = (int[]) field.get(null); 24339 for (int i = 0; i < values.length; i++) { 24340 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 24341 } 24342 } 24343 } 24344 } 24345 } catch (IllegalAccessException e) { 24346 throw new RuntimeException(e); 24347 } 24348 24349 final ArrayList<String> keys = Lists.newArrayList(); 24350 keys.addAll(found.keySet()); 24351 Collections.sort(keys); 24352 for (String key : keys) { 24353 Log.d(VIEW_LOG_TAG, found.get(key)); 24354 } 24355 } 24356 24357 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 24358 // Sort flags by prefix, then by bits, always keeping unique keys 24359 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 24360 final int prefix = name.indexOf('_'); 24361 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 24362 final String output = bits + " " + name; 24363 found.put(key, output); 24364 } 24365 24366 /** {@hide} */ 24367 public void encode(@NonNull ViewHierarchyEncoder stream) { 24368 stream.beginObject(this); 24369 encodeProperties(stream); 24370 stream.endObject(); 24371 } 24372 24373 /** {@hide} */ 24374 @CallSuper 24375 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 24376 Object resolveId = ViewDebug.resolveId(getContext(), mID); 24377 if (resolveId instanceof String) { 24378 stream.addProperty("id", (String) resolveId); 24379 } else { 24380 stream.addProperty("id", mID); 24381 } 24382 24383 stream.addProperty("misc:transformation.alpha", 24384 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 24385 stream.addProperty("misc:transitionName", getTransitionName()); 24386 24387 // layout 24388 stream.addProperty("layout:left", mLeft); 24389 stream.addProperty("layout:right", mRight); 24390 stream.addProperty("layout:top", mTop); 24391 stream.addProperty("layout:bottom", mBottom); 24392 stream.addProperty("layout:width", getWidth()); 24393 stream.addProperty("layout:height", getHeight()); 24394 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 24395 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 24396 stream.addProperty("layout:hasTransientState", hasTransientState()); 24397 stream.addProperty("layout:baseline", getBaseline()); 24398 24399 // layout params 24400 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 24401 if (layoutParams != null) { 24402 stream.addPropertyKey("layoutParams"); 24403 layoutParams.encode(stream); 24404 } 24405 24406 // scrolling 24407 stream.addProperty("scrolling:scrollX", mScrollX); 24408 stream.addProperty("scrolling:scrollY", mScrollY); 24409 24410 // padding 24411 stream.addProperty("padding:paddingLeft", mPaddingLeft); 24412 stream.addProperty("padding:paddingRight", mPaddingRight); 24413 stream.addProperty("padding:paddingTop", mPaddingTop); 24414 stream.addProperty("padding:paddingBottom", mPaddingBottom); 24415 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 24416 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 24417 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 24418 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 24419 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 24420 24421 // measurement 24422 stream.addProperty("measurement:minHeight", mMinHeight); 24423 stream.addProperty("measurement:minWidth", mMinWidth); 24424 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 24425 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 24426 24427 // drawing 24428 stream.addProperty("drawing:elevation", getElevation()); 24429 stream.addProperty("drawing:translationX", getTranslationX()); 24430 stream.addProperty("drawing:translationY", getTranslationY()); 24431 stream.addProperty("drawing:translationZ", getTranslationZ()); 24432 stream.addProperty("drawing:rotation", getRotation()); 24433 stream.addProperty("drawing:rotationX", getRotationX()); 24434 stream.addProperty("drawing:rotationY", getRotationY()); 24435 stream.addProperty("drawing:scaleX", getScaleX()); 24436 stream.addProperty("drawing:scaleY", getScaleY()); 24437 stream.addProperty("drawing:pivotX", getPivotX()); 24438 stream.addProperty("drawing:pivotY", getPivotY()); 24439 stream.addProperty("drawing:opaque", isOpaque()); 24440 stream.addProperty("drawing:alpha", getAlpha()); 24441 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 24442 stream.addProperty("drawing:shadow", hasShadow()); 24443 stream.addProperty("drawing:solidColor", getSolidColor()); 24444 stream.addProperty("drawing:layerType", mLayerType); 24445 stream.addProperty("drawing:willNotDraw", willNotDraw()); 24446 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 24447 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 24448 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 24449 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 24450 24451 // focus 24452 stream.addProperty("focus:hasFocus", hasFocus()); 24453 stream.addProperty("focus:isFocused", isFocused()); 24454 stream.addProperty("focus:isFocusable", isFocusable()); 24455 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 24456 24457 stream.addProperty("misc:clickable", isClickable()); 24458 stream.addProperty("misc:pressed", isPressed()); 24459 stream.addProperty("misc:selected", isSelected()); 24460 stream.addProperty("misc:touchMode", isInTouchMode()); 24461 stream.addProperty("misc:hovered", isHovered()); 24462 stream.addProperty("misc:activated", isActivated()); 24463 24464 stream.addProperty("misc:visibility", getVisibility()); 24465 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 24466 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 24467 24468 stream.addProperty("misc:enabled", isEnabled()); 24469 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 24470 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 24471 24472 // theme attributes 24473 Resources.Theme theme = getContext().getTheme(); 24474 if (theme != null) { 24475 stream.addPropertyKey("theme"); 24476 theme.encode(stream); 24477 } 24478 24479 // view attribute information 24480 int n = mAttributes != null ? mAttributes.length : 0; 24481 stream.addProperty("meta:__attrCount__", n/2); 24482 for (int i = 0; i < n; i += 2) { 24483 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 24484 } 24485 24486 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 24487 24488 // text 24489 stream.addProperty("text:textDirection", getTextDirection()); 24490 stream.addProperty("text:textAlignment", getTextAlignment()); 24491 24492 // accessibility 24493 CharSequence contentDescription = getContentDescription(); 24494 stream.addProperty("accessibility:contentDescription", 24495 contentDescription == null ? "" : contentDescription.toString()); 24496 stream.addProperty("accessibility:labelFor", getLabelFor()); 24497 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 24498 } 24499 24500 /** 24501 * Determine if this view is rendered on a round wearable device and is the main view 24502 * on the screen. 24503 */ 24504 private boolean shouldDrawRoundScrollbar() { 24505 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 24506 return false; 24507 } 24508 24509 final View rootView = getRootView(); 24510 final WindowInsets insets = getRootWindowInsets(); 24511 24512 int height = getHeight(); 24513 int width = getWidth(); 24514 int displayHeight = rootView.getHeight(); 24515 int displayWidth = rootView.getWidth(); 24516 24517 if (height != displayHeight || width != displayWidth) { 24518 return false; 24519 } 24520 24521 getLocationOnScreen(mAttachInfo.mTmpLocation); 24522 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 24523 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 24524 } 24525 24526 /** 24527 * Sets the tooltip text which will be displayed in a small popup next to the view. 24528 * <p> 24529 * The tooltip will be displayed: 24530 * <li>On long click, unless is not handled otherwise (by OnLongClickListener or a context 24531 * menu). </li> 24532 * <li>On hover, after a brief delay since the pointer has stopped moving </li> 24533 * 24534 * @param tooltipText the tooltip text, or null if no tooltip is required 24535 */ 24536 public final void setTooltipText(@Nullable CharSequence tooltipText) { 24537 if (TextUtils.isEmpty(tooltipText)) { 24538 setFlags(0, TOOLTIP); 24539 hideTooltip(); 24540 mTooltipInfo = null; 24541 } else { 24542 setFlags(TOOLTIP, TOOLTIP); 24543 if (mTooltipInfo == null) { 24544 mTooltipInfo = new TooltipInfo(); 24545 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip; 24546 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip; 24547 } 24548 mTooltipInfo.mTooltipText = tooltipText; 24549 if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) { 24550 mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText); 24551 } 24552 } 24553 } 24554 24555 /** 24556 * To be removed once the support library has stopped using it. 24557 * 24558 * @deprecated use {@link #setTooltipText} instead 24559 */ 24560 @Deprecated 24561 public final void setTooltip(@Nullable CharSequence tooltipText) { 24562 setTooltipText(tooltipText); 24563 } 24564 24565 /** 24566 * Returns the view's tooltip text. 24567 * 24568 * @return the tooltip text 24569 */ 24570 @Nullable 24571 public final CharSequence getTooltipText() { 24572 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null; 24573 } 24574 24575 /** 24576 * To be removed once the support library has stopped using it. 24577 * 24578 * @deprecated use {@link #getTooltipText} instead 24579 */ 24580 @Deprecated 24581 @Nullable 24582 public final CharSequence getTooltip() { 24583 return getTooltipText(); 24584 } 24585 24586 private boolean showTooltip(int x, int y, boolean fromLongClick) { 24587 if (mAttachInfo == null) { 24588 return false; 24589 } 24590 if ((mViewFlags & ENABLED_MASK) != ENABLED) { 24591 return false; 24592 } 24593 final CharSequence tooltipText = getTooltipText(); 24594 if (TextUtils.isEmpty(tooltipText)) { 24595 return false; 24596 } 24597 hideTooltip(); 24598 mTooltipInfo.mTooltipFromLongClick = fromLongClick; 24599 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext()); 24600 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN; 24601 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, tooltipText); 24602 mAttachInfo.mTooltipHost = this; 24603 return true; 24604 } 24605 24606 void hideTooltip() { 24607 if (mTooltipInfo == null) { 24608 return; 24609 } 24610 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 24611 if (mTooltipInfo.mTooltipPopup == null) { 24612 return; 24613 } 24614 mTooltipInfo.mTooltipPopup.hide(); 24615 mTooltipInfo.mTooltipPopup = null; 24616 mTooltipInfo.mTooltipFromLongClick = false; 24617 if (mAttachInfo != null) { 24618 mAttachInfo.mTooltipHost = null; 24619 } 24620 } 24621 24622 private boolean showLongClickTooltip(int x, int y) { 24623 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 24624 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 24625 return showTooltip(x, y, true); 24626 } 24627 24628 private void showHoverTooltip() { 24629 showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false); 24630 } 24631 24632 boolean dispatchTooltipHoverEvent(MotionEvent event) { 24633 if (mTooltipInfo == null) { 24634 return false; 24635 } 24636 switch(event.getAction()) { 24637 case MotionEvent.ACTION_HOVER_MOVE: 24638 if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) { 24639 break; 24640 } 24641 if (!mTooltipInfo.mTooltipFromLongClick) { 24642 if (mTooltipInfo.mTooltipPopup == null) { 24643 // Schedule showing the tooltip after a timeout. 24644 mTooltipInfo.mAnchorX = (int) event.getX(); 24645 mTooltipInfo.mAnchorY = (int) event.getY(); 24646 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 24647 postDelayed(mTooltipInfo.mShowTooltipRunnable, 24648 ViewConfiguration.getHoverTooltipShowTimeout()); 24649 } 24650 24651 // Hide hover-triggered tooltip after a period of inactivity. 24652 // Match the timeout used by NativeInputManager to hide the mouse pointer 24653 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set). 24654 final int timeout; 24655 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE) 24656 == SYSTEM_UI_FLAG_LOW_PROFILE) { 24657 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout(); 24658 } else { 24659 timeout = ViewConfiguration.getHoverTooltipHideTimeout(); 24660 } 24661 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 24662 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout); 24663 } 24664 return true; 24665 24666 case MotionEvent.ACTION_HOVER_EXIT: 24667 if (!mTooltipInfo.mTooltipFromLongClick) { 24668 hideTooltip(); 24669 } 24670 break; 24671 } 24672 return false; 24673 } 24674 24675 void handleTooltipKey(KeyEvent event) { 24676 switch (event.getAction()) { 24677 case KeyEvent.ACTION_DOWN: 24678 if (event.getRepeatCount() == 0) { 24679 hideTooltip(); 24680 } 24681 break; 24682 24683 case KeyEvent.ACTION_UP: 24684 handleTooltipUp(); 24685 break; 24686 } 24687 } 24688 24689 private void handleTooltipUp() { 24690 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 24691 return; 24692 } 24693 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 24694 postDelayed(mTooltipInfo.mHideTooltipRunnable, 24695 ViewConfiguration.getLongPressTooltipHideTimeout()); 24696 } 24697 24698 /** 24699 * @return The content view of the tooltip popup currently being shown, or null if the tooltip 24700 * is not showing. 24701 * @hide 24702 */ 24703 @TestApi 24704 public View getTooltipView() { 24705 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 24706 return null; 24707 } 24708 return mTooltipInfo.mTooltipPopup.getContentView(); 24709 } 24710} 24711