View.java revision 838277059f15386fe6375f36b3b7c89760ffeae3
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.CallSuper; 22import android.annotation.ColorInt; 23import android.annotation.DrawableRes; 24import android.annotation.FloatRange; 25import android.annotation.IdRes; 26import android.annotation.IntDef; 27import android.annotation.IntRange; 28import android.annotation.LayoutRes; 29import android.annotation.NonNull; 30import android.annotation.Nullable; 31import android.annotation.Size; 32import android.annotation.UiThread; 33import android.content.ClipData; 34import android.content.Context; 35import android.content.ContextWrapper; 36import android.content.Intent; 37import android.content.res.ColorStateList; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.content.res.TypedArray; 41import android.graphics.Bitmap; 42import android.graphics.Canvas; 43import android.graphics.Insets; 44import android.graphics.Interpolator; 45import android.graphics.LinearGradient; 46import android.graphics.Matrix; 47import android.graphics.Outline; 48import android.graphics.Paint; 49import android.graphics.PixelFormat; 50import android.graphics.Point; 51import android.graphics.PorterDuff; 52import android.graphics.PorterDuffXfermode; 53import android.graphics.Rect; 54import android.graphics.RectF; 55import android.graphics.Region; 56import android.graphics.Shader; 57import android.graphics.drawable.ColorDrawable; 58import android.graphics.drawable.Drawable; 59import android.hardware.display.DisplayManagerGlobal; 60import android.os.Build.VERSION_CODES; 61import android.os.Bundle; 62import android.os.Handler; 63import android.os.IBinder; 64import android.os.Parcel; 65import android.os.Parcelable; 66import android.os.RemoteException; 67import android.os.SystemClock; 68import android.os.SystemProperties; 69import android.os.Trace; 70import android.text.TextUtils; 71import android.util.AttributeSet; 72import android.util.FloatProperty; 73import android.util.LayoutDirection; 74import android.util.Log; 75import android.util.LongSparseLongArray; 76import android.util.Pools.SynchronizedPool; 77import android.util.Property; 78import android.util.SparseArray; 79import android.util.StateSet; 80import android.util.SuperNotCalledException; 81import android.util.TypedValue; 82import android.view.ContextMenu.ContextMenuInfo; 83import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 85import android.view.AccessibilityIterators.TextSegmentIterator; 86import android.view.AccessibilityIterators.WordTextSegmentIterator; 87import android.view.accessibility.AccessibilityEvent; 88import android.view.accessibility.AccessibilityEventSource; 89import android.view.accessibility.AccessibilityManager; 90import android.view.accessibility.AccessibilityNodeInfo; 91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 92import android.view.accessibility.AccessibilityNodeProvider; 93import android.view.animation.Animation; 94import android.view.animation.AnimationUtils; 95import android.view.animation.Transformation; 96import android.view.inputmethod.EditorInfo; 97import android.view.inputmethod.InputConnection; 98import android.view.inputmethod.InputMethodManager; 99import android.widget.Checkable; 100import android.widget.FrameLayout; 101import android.widget.ScrollBarDrawable; 102import static android.os.Build.VERSION_CODES.*; 103import static java.lang.Math.max; 104 105import com.android.internal.R; 106import com.android.internal.util.Predicate; 107import com.android.internal.view.menu.MenuBuilder; 108import com.android.internal.widget.ScrollBarUtils; 109import com.google.android.collect.Lists; 110import com.google.android.collect.Maps; 111 112import java.lang.NullPointerException; 113import java.lang.annotation.Retention; 114import java.lang.annotation.RetentionPolicy; 115import java.lang.ref.WeakReference; 116import java.lang.reflect.Field; 117import java.lang.reflect.InvocationTargetException; 118import java.lang.reflect.Method; 119import java.lang.reflect.Modifier; 120import java.util.ArrayList; 121import java.util.Arrays; 122import java.util.Collections; 123import java.util.HashMap; 124import java.util.List; 125import java.util.Locale; 126import java.util.Map; 127import java.util.concurrent.CopyOnWriteArrayList; 128import java.util.concurrent.atomic.AtomicInteger; 129 130/** 131 * <p> 132 * This class represents the basic building block for user interface components. A View 133 * occupies a rectangular area on the screen and is responsible for drawing and 134 * event handling. View is the base class for <em>widgets</em>, which are 135 * used to create interactive UI components (buttons, text fields, etc.). The 136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 137 * are invisible containers that hold other Views (or other ViewGroups) and define 138 * their layout properties. 139 * </p> 140 * 141 * <div class="special reference"> 142 * <h3>Developer Guides</h3> 143 * <p>For information about using this class to develop your application's user interface, 144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 145 * </div> 146 * 147 * <a name="Using"></a> 148 * <h3>Using Views</h3> 149 * <p> 150 * All of the views in a window are arranged in a single tree. You can add views 151 * either from code or by specifying a tree of views in one or more XML layout 152 * files. There are many specialized subclasses of views that act as controls or 153 * are capable of displaying text, images, or other content. 154 * </p> 155 * <p> 156 * Once you have created a tree of views, there are typically a few types of 157 * common operations you may wish to perform: 158 * <ul> 159 * <li><strong>Set properties:</strong> for example setting the text of a 160 * {@link android.widget.TextView}. The available properties and the methods 161 * that set them will vary among the different subclasses of views. Note that 162 * properties that are known at build time can be set in the XML layout 163 * files.</li> 164 * <li><strong>Set focus:</strong> The framework will handle moving focus in 165 * response to user input. To force focus to a specific view, call 166 * {@link #requestFocus}.</li> 167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 168 * that will be notified when something interesting happens to the view. For 169 * example, all views will let you set a listener to be notified when the view 170 * gains or loses focus. You can register such a listener using 171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 172 * Other view subclasses offer more specialized listeners. For example, a Button 173 * exposes a listener to notify clients when the button is clicked.</li> 174 * <li><strong>Set visibility:</strong> You can hide or show views using 175 * {@link #setVisibility(int)}.</li> 176 * </ul> 177 * </p> 178 * <p><em> 179 * Note: The Android framework is responsible for measuring, laying out and 180 * drawing views. You should not call methods that perform these actions on 181 * views yourself unless you are actually implementing a 182 * {@link android.view.ViewGroup}. 183 * </em></p> 184 * 185 * <a name="Lifecycle"></a> 186 * <h3>Implementing a Custom View</h3> 187 * 188 * <p> 189 * To implement a custom view, you will usually begin by providing overrides for 190 * some of the standard methods that the framework calls on all views. You do 191 * not need to override all of these methods. In fact, you can start by just 192 * overriding {@link #onDraw(android.graphics.Canvas)}. 193 * <table border="2" width="85%" align="center" cellpadding="5"> 194 * <thead> 195 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 196 * </thead> 197 * 198 * <tbody> 199 * <tr> 200 * <td rowspan="2">Creation</td> 201 * <td>Constructors</td> 202 * <td>There is a form of the constructor that are called when the view 203 * is created from code and a form that is called when the view is 204 * inflated from a layout file. The second form should parse and apply 205 * any attributes defined in the layout file. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onFinishInflate()}</code></td> 210 * <td>Called after a view and all of its children has been inflated 211 * from XML.</td> 212 * </tr> 213 * 214 * <tr> 215 * <td rowspan="3">Layout</td> 216 * <td><code>{@link #onMeasure(int, int)}</code></td> 217 * <td>Called to determine the size requirements for this view and all 218 * of its children. 219 * </td> 220 * </tr> 221 * <tr> 222 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 223 * <td>Called when this view should assign a size and position to all 224 * of its children. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 229 * <td>Called when the size of this view has changed. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td>Drawing</td> 235 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 236 * <td>Called when the view should render its content. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td rowspan="4">Event processing</td> 242 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 243 * <td>Called when a new hardware key event occurs. 244 * </td> 245 * </tr> 246 * <tr> 247 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 248 * <td>Called when a hardware key up event occurs. 249 * </td> 250 * </tr> 251 * <tr> 252 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 253 * <td>Called when a trackball motion event occurs. 254 * </td> 255 * </tr> 256 * <tr> 257 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 258 * <td>Called when a touch screen motion event occurs. 259 * </td> 260 * </tr> 261 * 262 * <tr> 263 * <td rowspan="2">Focus</td> 264 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 265 * <td>Called when the view gains or loses focus. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 271 * <td>Called when the window containing the view gains or loses focus. 272 * </td> 273 * </tr> 274 * 275 * <tr> 276 * <td rowspan="3">Attaching</td> 277 * <td><code>{@link #onAttachedToWindow()}</code></td> 278 * <td>Called when the view is attached to a window. 279 * </td> 280 * </tr> 281 * 282 * <tr> 283 * <td><code>{@link #onDetachedFromWindow}</code></td> 284 * <td>Called when the view is detached from its window. 285 * </td> 286 * </tr> 287 * 288 * <tr> 289 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 290 * <td>Called when the visibility of the window containing the view 291 * has changed. 292 * </td> 293 * </tr> 294 * </tbody> 295 * 296 * </table> 297 * </p> 298 * 299 * <a name="IDs"></a> 300 * <h3>IDs</h3> 301 * Views may have an integer id associated with them. These ids are typically 302 * assigned in the layout XML files, and are used to find specific views within 303 * the view tree. A common pattern is to: 304 * <ul> 305 * <li>Define a Button in the layout file and assign it a unique ID. 306 * <pre> 307 * <Button 308 * android:id="@+id/my_button" 309 * android:layout_width="wrap_content" 310 * android:layout_height="wrap_content" 311 * android:text="@string/my_button_text"/> 312 * </pre></li> 313 * <li>From the onCreate method of an Activity, find the Button 314 * <pre class="prettyprint"> 315 * Button myButton = (Button) findViewById(R.id.my_button); 316 * </pre></li> 317 * </ul> 318 * <p> 319 * View IDs need not be unique throughout the tree, but it is good practice to 320 * ensure that they are at least unique within the part of the tree you are 321 * searching. 322 * </p> 323 * 324 * <a name="Position"></a> 325 * <h3>Position</h3> 326 * <p> 327 * The geometry of a view is that of a rectangle. A view has a location, 328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 329 * two dimensions, expressed as a width and a height. The unit for location 330 * and dimensions is the pixel. 331 * </p> 332 * 333 * <p> 334 * It is possible to retrieve the location of a view by invoking the methods 335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 336 * coordinate of the rectangle representing the view. The latter returns the 337 * top, or Y, coordinate of the rectangle representing the view. These methods 338 * both return the location of the view relative to its parent. For instance, 339 * when getLeft() returns 20, that means the view is located 20 pixels to the 340 * right of the left edge of its direct parent. 341 * </p> 342 * 343 * <p> 344 * In addition, several convenience methods are offered to avoid unnecessary 345 * computations, namely {@link #getRight()} and {@link #getBottom()}. 346 * These methods return the coordinates of the right and bottom edges of the 347 * rectangle representing the view. For instance, calling {@link #getRight()} 348 * is similar to the following computation: <code>getLeft() + getWidth()</code> 349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 350 * </p> 351 * 352 * <a name="SizePaddingMargins"></a> 353 * <h3>Size, padding and margins</h3> 354 * <p> 355 * The size of a view is expressed with a width and a height. A view actually 356 * possess two pairs of width and height values. 357 * </p> 358 * 359 * <p> 360 * The first pair is known as <em>measured width</em> and 361 * <em>measured height</em>. These dimensions define how big a view wants to be 362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 364 * and {@link #getMeasuredHeight()}. 365 * </p> 366 * 367 * <p> 368 * The second pair is simply known as <em>width</em> and <em>height</em>, or 369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 370 * dimensions define the actual size of the view on screen, at drawing time and 371 * after layout. These values may, but do not have to, be different from the 372 * measured width and height. The width and height can be obtained by calling 373 * {@link #getWidth()} and {@link #getHeight()}. 374 * </p> 375 * 376 * <p> 377 * To measure its dimensions, a view takes into account its padding. The padding 378 * is expressed in pixels for the left, top, right and bottom parts of the view. 379 * Padding can be used to offset the content of the view by a specific amount of 380 * pixels. For instance, a left padding of 2 will push the view's content by 381 * 2 pixels to the right of the left edge. Padding can be set using the 382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 385 * {@link #getPaddingEnd()}. 386 * </p> 387 * 388 * <p> 389 * Even though a view can define a padding, it does not provide any support for 390 * margins. However, view groups provide such a support. Refer to 391 * {@link android.view.ViewGroup} and 392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 393 * </p> 394 * 395 * <a name="Layout"></a> 396 * <h3>Layout</h3> 397 * <p> 398 * Layout is a two pass process: a measure pass and a layout pass. The measuring 399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 400 * of the view tree. Each view pushes dimension specifications down the tree 401 * during the recursion. At the end of the measure pass, every view has stored 402 * its measurements. The second pass happens in 403 * {@link #layout(int,int,int,int)} and is also top-down. During 404 * this pass each parent is responsible for positioning all of its children 405 * using the sizes computed in the measure pass. 406 * </p> 407 * 408 * <p> 409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 410 * {@link #getMeasuredHeight()} values must be set, along with those for all of 411 * that view's descendants. A view's measured width and measured height values 412 * must respect the constraints imposed by the view's parents. This guarantees 413 * that at the end of the measure pass, all parents accept all of their 414 * children's measurements. A parent view may call measure() more than once on 415 * its children. For example, the parent may measure each child once with 416 * unspecified dimensions to find out how big they want to be, then call 417 * measure() on them again with actual numbers if the sum of all the children's 418 * unconstrained sizes is too big or too small. 419 * </p> 420 * 421 * <p> 422 * The measure pass uses two classes to communicate dimensions. The 423 * {@link MeasureSpec} class is used by views to tell their parents how they 424 * want to be measured and positioned. The base LayoutParams class just 425 * describes how big the view wants to be for both width and height. For each 426 * dimension, it can specify one of: 427 * <ul> 428 * <li> an exact number 429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 430 * (minus padding) 431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 432 * enclose its content (plus padding). 433 * </ul> 434 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 436 * an X and Y value. 437 * </p> 438 * 439 * <p> 440 * MeasureSpecs are used to push requirements down the tree from parent to 441 * child. A MeasureSpec can be in one of three modes: 442 * <ul> 443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 444 * of a child view. For example, a LinearLayout may call measure() on its child 445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 446 * tall the child view wants to be given a width of 240 pixels. 447 * <li>EXACTLY: This is used by the parent to impose an exact size on the 448 * child. The child must use this size, and guarantee that all of its 449 * descendants will fit within this size. 450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 451 * child. The child must guarantee that it and all of its descendants will fit 452 * within this size. 453 * </ul> 454 * </p> 455 * 456 * <p> 457 * To initiate a layout, call {@link #requestLayout}. This method is typically 458 * called by a view on itself when it believes that is can no longer fit within 459 * its current bounds. 460 * </p> 461 * 462 * <a name="Drawing"></a> 463 * <h3>Drawing</h3> 464 * <p> 465 * Drawing is handled by walking the tree and recording the drawing commands of 466 * any View that needs to update. After this, the drawing commands of the 467 * entire tree are issued to screen, clipped to the newly damaged area. 468 * </p> 469 * 470 * <p> 471 * The tree is largely recorded and drawn in order, with parents drawn before 472 * (i.e., behind) their children, with siblings drawn in the order they appear 473 * in the tree. If you set a background drawable for a View, then the View will 474 * draw it before calling back to its <code>onDraw()</code> method. The child 475 * drawing order can be overridden with 476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 478 * </p> 479 * 480 * <p> 481 * To force a view to draw, call {@link #invalidate()}. 482 * </p> 483 * 484 * <a name="EventHandlingThreading"></a> 485 * <h3>Event Handling and Threading</h3> 486 * <p> 487 * The basic cycle of a view is as follows: 488 * <ol> 489 * <li>An event comes in and is dispatched to the appropriate view. The view 490 * handles the event and notifies any listeners.</li> 491 * <li>If in the course of processing the event, the view's bounds may need 492 * to be changed, the view will call {@link #requestLayout()}.</li> 493 * <li>Similarly, if in the course of processing the event the view's appearance 494 * may need to be changed, the view will call {@link #invalidate()}.</li> 495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 496 * the framework will take care of measuring, laying out, and drawing the tree 497 * as appropriate.</li> 498 * </ol> 499 * </p> 500 * 501 * <p><em>Note: The entire view tree is single threaded. You must always be on 502 * the UI thread when calling any method on any view.</em> 503 * If you are doing work on other threads and want to update the state of a view 504 * from that thread, you should use a {@link Handler}. 505 * </p> 506 * 507 * <a name="FocusHandling"></a> 508 * <h3>Focus Handling</h3> 509 * <p> 510 * The framework will handle routine focus movement in response to user input. 511 * This includes changing the focus as views are removed or hidden, or as new 512 * views become available. Views indicate their willingness to take focus 513 * through the {@link #isFocusable} method. To change whether a view can take 514 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 516 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 517 * </p> 518 * <p> 519 * Focus movement is based on an algorithm which finds the nearest neighbor in a 520 * given direction. In rare cases, the default algorithm may not match the 521 * intended behavior of the developer. In these situations, you can provide 522 * explicit overrides by using these XML attributes in the layout file: 523 * <pre> 524 * nextFocusDown 525 * nextFocusLeft 526 * nextFocusRight 527 * nextFocusUp 528 * </pre> 529 * </p> 530 * 531 * 532 * <p> 533 * To get a particular view to take focus, call {@link #requestFocus()}. 534 * </p> 535 * 536 * <a name="TouchMode"></a> 537 * <h3>Touch Mode</h3> 538 * <p> 539 * When a user is navigating a user interface via directional keys such as a D-pad, it is 540 * necessary to give focus to actionable items such as buttons so the user can see 541 * what will take input. If the device has touch capabilities, however, and the user 542 * begins interacting with the interface by touching it, it is no longer necessary to 543 * always highlight, or give focus to, a particular view. This motivates a mode 544 * for interaction named 'touch mode'. 545 * </p> 546 * <p> 547 * For a touch capable device, once the user touches the screen, the device 548 * will enter touch mode. From this point onward, only views for which 549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 550 * Other views that are touchable, like buttons, will not take focus when touched; they will 551 * only fire the on click listeners. 552 * </p> 553 * <p> 554 * Any time a user hits a directional key, such as a D-pad direction, the view device will 555 * exit touch mode, and find a view to take focus, so that the user may resume interacting 556 * with the user interface without touching the screen again. 557 * </p> 558 * <p> 559 * The touch mode state is maintained across {@link android.app.Activity}s. Call 560 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 561 * </p> 562 * 563 * <a name="Scrolling"></a> 564 * <h3>Scrolling</h3> 565 * <p> 566 * The framework provides basic support for views that wish to internally 567 * scroll their content. This includes keeping track of the X and Y scroll 568 * offset as well as mechanisms for drawing scrollbars. See 569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 570 * {@link #awakenScrollBars()} for more details. 571 * </p> 572 * 573 * <a name="Tags"></a> 574 * <h3>Tags</h3> 575 * <p> 576 * Unlike IDs, tags are not used to identify views. Tags are essentially an 577 * extra piece of information that can be associated with a view. They are most 578 * often used as a convenience to store data related to views in the views 579 * themselves rather than by putting them in a separate structure. 580 * </p> 581 * <p> 582 * Tags may be specified with character sequence values in layout XML as either 583 * a single tag using the {@link android.R.styleable#View_tag android:tag} 584 * attribute or multiple tags using the {@code <tag>} child element: 585 * <pre> 586 * <View ... 587 * android:tag="@string/mytag_value" /> 588 * <View ...> 589 * <tag android:id="@+id/mytag" 590 * android:value="@string/mytag_value" /> 591 * </View> 592 * </pre> 593 * </p> 594 * <p> 595 * Tags may also be specified with arbitrary objects from code using 596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 597 * </p> 598 * 599 * <a name="Themes"></a> 600 * <h3>Themes</h3> 601 * <p> 602 * By default, Views are created using the theme of the Context object supplied 603 * to their constructor; however, a different theme may be specified by using 604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 606 * code. 607 * </p> 608 * <p> 609 * When the {@link android.R.styleable#View_theme android:theme} attribute is 610 * used in XML, the specified theme is applied on top of the inflation 611 * context's theme (see {@link LayoutInflater}) and used for the view itself as 612 * well as any child elements. 613 * </p> 614 * <p> 615 * In the following example, both views will be created using the Material dark 616 * color scheme; however, because an overlay theme is used which only defines a 617 * subset of attributes, the value of 618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 619 * the inflation context's theme (e.g. the Activity theme) will be preserved. 620 * <pre> 621 * <LinearLayout 622 * ... 623 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 624 * <View ...> 625 * </LinearLayout> 626 * </pre> 627 * </p> 628 * 629 * <a name="Properties"></a> 630 * <h3>Properties</h3> 631 * <p> 632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 634 * available both in the {@link Property} form as well as in similarly-named setter/getter 635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 636 * be used to set persistent state associated with these rendering-related properties on the view. 637 * The properties and methods can also be used in conjunction with 638 * {@link android.animation.Animator Animator}-based animations, described more in the 639 * <a href="#Animation">Animation</a> section. 640 * </p> 641 * 642 * <a name="Animation"></a> 643 * <h3>Animation</h3> 644 * <p> 645 * Starting with Android 3.0, the preferred way of animating views is to use the 646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 651 * makes animating these View properties particularly easy and efficient. 652 * </p> 653 * <p> 654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 655 * You can attach an {@link Animation} object to a view using 656 * {@link #setAnimation(Animation)} or 657 * {@link #startAnimation(Animation)}. The animation can alter the scale, 658 * rotation, translation and alpha of a view over time. If the animation is 659 * attached to a view that has children, the animation will affect the entire 660 * subtree rooted by that node. When an animation is started, the framework will 661 * take care of redrawing the appropriate views until the animation completes. 662 * </p> 663 * 664 * <a name="Security"></a> 665 * <h3>Security</h3> 666 * <p> 667 * Sometimes it is essential that an application be able to verify that an action 668 * is being performed with the full knowledge and consent of the user, such as 669 * granting a permission request, making a purchase or clicking on an advertisement. 670 * Unfortunately, a malicious application could try to spoof the user into 671 * performing these actions, unaware, by concealing the intended purpose of the view. 672 * As a remedy, the framework offers a touch filtering mechanism that can be used to 673 * improve the security of views that provide access to sensitive functionality. 674 * </p><p> 675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 676 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 677 * will discard touches that are received whenever the view's window is obscured by 678 * another visible window. As a result, the view will not receive touches whenever a 679 * toast, dialog or other window appears above the view's window. 680 * </p><p> 681 * For more fine-grained control over security, consider overriding the 682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 684 * </p> 685 * 686 * @attr ref android.R.styleable#View_alpha 687 * @attr ref android.R.styleable#View_background 688 * @attr ref android.R.styleable#View_clickable 689 * @attr ref android.R.styleable#View_contentDescription 690 * @attr ref android.R.styleable#View_drawingCacheQuality 691 * @attr ref android.R.styleable#View_duplicateParentState 692 * @attr ref android.R.styleable#View_id 693 * @attr ref android.R.styleable#View_requiresFadingEdge 694 * @attr ref android.R.styleable#View_fadeScrollbars 695 * @attr ref android.R.styleable#View_fadingEdgeLength 696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 697 * @attr ref android.R.styleable#View_fitsSystemWindows 698 * @attr ref android.R.styleable#View_isScrollContainer 699 * @attr ref android.R.styleable#View_focusable 700 * @attr ref android.R.styleable#View_focusableInTouchMode 701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 702 * @attr ref android.R.styleable#View_keepScreenOn 703 * @attr ref android.R.styleable#View_layerType 704 * @attr ref android.R.styleable#View_layoutDirection 705 * @attr ref android.R.styleable#View_longClickable 706 * @attr ref android.R.styleable#View_minHeight 707 * @attr ref android.R.styleable#View_minWidth 708 * @attr ref android.R.styleable#View_nextFocusDown 709 * @attr ref android.R.styleable#View_nextFocusLeft 710 * @attr ref android.R.styleable#View_nextFocusRight 711 * @attr ref android.R.styleable#View_nextFocusUp 712 * @attr ref android.R.styleable#View_onClick 713 * @attr ref android.R.styleable#View_padding 714 * @attr ref android.R.styleable#View_paddingBottom 715 * @attr ref android.R.styleable#View_paddingLeft 716 * @attr ref android.R.styleable#View_paddingRight 717 * @attr ref android.R.styleable#View_paddingTop 718 * @attr ref android.R.styleable#View_paddingStart 719 * @attr ref android.R.styleable#View_paddingEnd 720 * @attr ref android.R.styleable#View_saveEnabled 721 * @attr ref android.R.styleable#View_rotation 722 * @attr ref android.R.styleable#View_rotationX 723 * @attr ref android.R.styleable#View_rotationY 724 * @attr ref android.R.styleable#View_scaleX 725 * @attr ref android.R.styleable#View_scaleY 726 * @attr ref android.R.styleable#View_scrollX 727 * @attr ref android.R.styleable#View_scrollY 728 * @attr ref android.R.styleable#View_scrollbarSize 729 * @attr ref android.R.styleable#View_scrollbarStyle 730 * @attr ref android.R.styleable#View_scrollbars 731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 732 * @attr ref android.R.styleable#View_scrollbarFadeDuration 733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 735 * @attr ref android.R.styleable#View_scrollbarThumbVertical 736 * @attr ref android.R.styleable#View_scrollbarTrackVertical 737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 739 * @attr ref android.R.styleable#View_stateListAnimator 740 * @attr ref android.R.styleable#View_transitionName 741 * @attr ref android.R.styleable#View_soundEffectsEnabled 742 * @attr ref android.R.styleable#View_tag 743 * @attr ref android.R.styleable#View_textAlignment 744 * @attr ref android.R.styleable#View_textDirection 745 * @attr ref android.R.styleable#View_transformPivotX 746 * @attr ref android.R.styleable#View_transformPivotY 747 * @attr ref android.R.styleable#View_translationX 748 * @attr ref android.R.styleable#View_translationY 749 * @attr ref android.R.styleable#View_translationZ 750 * @attr ref android.R.styleable#View_visibility 751 * @attr ref android.R.styleable#View_theme 752 * 753 * @see android.view.ViewGroup 754 */ 755@UiThread 756public class View implements Drawable.Callback, KeyEvent.Callback, 757 AccessibilityEventSource { 758 private static final boolean DBG = false; 759 760 /** 761 * The logging tag used by this class with android.util.Log. 762 */ 763 protected static final String VIEW_LOG_TAG = "View"; 764 765 /** 766 * When set to true, apps will draw debugging information about their layouts. 767 * 768 * @hide 769 */ 770 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 771 772 /** 773 * When set to true, this view will save its attribute data. 774 * 775 * @hide 776 */ 777 public static boolean mDebugViewAttributes = false; 778 779 /** 780 * Used to mark a View that has no ID. 781 */ 782 public static final int NO_ID = -1; 783 784 /** 785 * Signals that compatibility booleans have been initialized according to 786 * target SDK versions. 787 */ 788 private static boolean sCompatibilityDone = false; 789 790 /** 791 * Use the old (broken) way of building MeasureSpecs. 792 */ 793 private static boolean sUseBrokenMakeMeasureSpec = false; 794 795 /** 796 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 797 */ 798 static boolean sUseZeroUnspecifiedMeasureSpec = false; 799 800 /** 801 * Ignore any optimizations using the measure cache. 802 */ 803 private static boolean sIgnoreMeasureCache = false; 804 805 /** 806 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 807 */ 808 private static boolean sAlwaysRemeasureExactly = false; 809 810 /** 811 * Relax constraints around whether setLayoutParams() must be called after 812 * modifying the layout params. 813 */ 814 private static boolean sLayoutParamsAlwaysChanged = false; 815 816 /** 817 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 818 * without throwing 819 */ 820 static boolean sTextureViewIgnoresDrawableSetters = false; 821 822 /** 823 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 824 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 825 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 826 * check is implemented for backwards compatibility. 827 * 828 * {@hide} 829 */ 830 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 831 832 /** 833 * Prior to N, when drag enters into child of a view that has already received an 834 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 835 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 836 * false from its event handler for these events. 837 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 838 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 839 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 840 */ 841 static boolean sCascadedDragDrop; 842 843 /** 844 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 845 * calling setFlags. 846 */ 847 private static final int NOT_FOCUSABLE = 0x00000000; 848 849 /** 850 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 851 * setFlags. 852 */ 853 private static final int FOCUSABLE = 0x00000001; 854 855 /** 856 * Mask for use with setFlags indicating bits used for focus. 857 */ 858 private static final int FOCUSABLE_MASK = 0x00000001; 859 860 /** 861 * This view will adjust its padding to fit sytem windows (e.g. status bar) 862 */ 863 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 864 865 /** @hide */ 866 @IntDef({VISIBLE, INVISIBLE, GONE}) 867 @Retention(RetentionPolicy.SOURCE) 868 public @interface Visibility {} 869 870 /** 871 * This view is visible. 872 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 873 * android:visibility}. 874 */ 875 public static final int VISIBLE = 0x00000000; 876 877 /** 878 * This view is invisible, but it still takes up space for layout purposes. 879 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 880 * android:visibility}. 881 */ 882 public static final int INVISIBLE = 0x00000004; 883 884 /** 885 * This view is invisible, and it doesn't take any space for layout 886 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 887 * android:visibility}. 888 */ 889 public static final int GONE = 0x00000008; 890 891 /** 892 * Mask for use with setFlags indicating bits used for visibility. 893 * {@hide} 894 */ 895 static final int VISIBILITY_MASK = 0x0000000C; 896 897 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 898 899 /** 900 * This view is enabled. Interpretation varies by subclass. 901 * Use with ENABLED_MASK when calling setFlags. 902 * {@hide} 903 */ 904 static final int ENABLED = 0x00000000; 905 906 /** 907 * This view is disabled. Interpretation varies by subclass. 908 * Use with ENABLED_MASK when calling setFlags. 909 * {@hide} 910 */ 911 static final int DISABLED = 0x00000020; 912 913 /** 914 * Mask for use with setFlags indicating bits used for indicating whether 915 * this view is enabled 916 * {@hide} 917 */ 918 static final int ENABLED_MASK = 0x00000020; 919 920 /** 921 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 922 * called and further optimizations will be performed. It is okay to have 923 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 924 * {@hide} 925 */ 926 static final int WILL_NOT_DRAW = 0x00000080; 927 928 /** 929 * Mask for use with setFlags indicating bits used for indicating whether 930 * this view is will draw 931 * {@hide} 932 */ 933 static final int DRAW_MASK = 0x00000080; 934 935 /** 936 * <p>This view doesn't show scrollbars.</p> 937 * {@hide} 938 */ 939 static final int SCROLLBARS_NONE = 0x00000000; 940 941 /** 942 * <p>This view shows horizontal scrollbars.</p> 943 * {@hide} 944 */ 945 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 946 947 /** 948 * <p>This view shows vertical scrollbars.</p> 949 * {@hide} 950 */ 951 static final int SCROLLBARS_VERTICAL = 0x00000200; 952 953 /** 954 * <p>Mask for use with setFlags indicating bits used for indicating which 955 * scrollbars are enabled.</p> 956 * {@hide} 957 */ 958 static final int SCROLLBARS_MASK = 0x00000300; 959 960 /** 961 * Indicates that the view should filter touches when its window is obscured. 962 * Refer to the class comments for more information about this security feature. 963 * {@hide} 964 */ 965 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 966 967 /** 968 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 969 * that they are optional and should be skipped if the window has 970 * requested system UI flags that ignore those insets for layout. 971 */ 972 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 973 974 /** 975 * <p>This view doesn't show fading edges.</p> 976 * {@hide} 977 */ 978 static final int FADING_EDGE_NONE = 0x00000000; 979 980 /** 981 * <p>This view shows horizontal fading edges.</p> 982 * {@hide} 983 */ 984 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 985 986 /** 987 * <p>This view shows vertical fading edges.</p> 988 * {@hide} 989 */ 990 static final int FADING_EDGE_VERTICAL = 0x00002000; 991 992 /** 993 * <p>Mask for use with setFlags indicating bits used for indicating which 994 * fading edges are enabled.</p> 995 * {@hide} 996 */ 997 static final int FADING_EDGE_MASK = 0x00003000; 998 999 /** 1000 * <p>Indicates this view can be clicked. When clickable, a View reacts 1001 * to clicks by notifying the OnClickListener.<p> 1002 * {@hide} 1003 */ 1004 static final int CLICKABLE = 0x00004000; 1005 1006 /** 1007 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1008 * {@hide} 1009 */ 1010 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1011 1012 /** 1013 * <p>Indicates that no icicle should be saved for this view.<p> 1014 * {@hide} 1015 */ 1016 static final int SAVE_DISABLED = 0x000010000; 1017 1018 /** 1019 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1020 * property.</p> 1021 * {@hide} 1022 */ 1023 static final int SAVE_DISABLED_MASK = 0x000010000; 1024 1025 /** 1026 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1027 * {@hide} 1028 */ 1029 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1030 1031 /** 1032 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1033 * {@hide} 1034 */ 1035 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1036 1037 /** @hide */ 1038 @Retention(RetentionPolicy.SOURCE) 1039 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1040 public @interface DrawingCacheQuality {} 1041 1042 /** 1043 * <p>Enables low quality mode for the drawing cache.</p> 1044 */ 1045 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1046 1047 /** 1048 * <p>Enables high quality mode for the drawing cache.</p> 1049 */ 1050 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1051 1052 /** 1053 * <p>Enables automatic quality mode for the drawing cache.</p> 1054 */ 1055 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1056 1057 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1058 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1059 }; 1060 1061 /** 1062 * <p>Mask for use with setFlags indicating bits used for the cache 1063 * quality property.</p> 1064 * {@hide} 1065 */ 1066 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1067 1068 /** 1069 * <p> 1070 * Indicates this view can be long clicked. When long clickable, a View 1071 * reacts to long clicks by notifying the OnLongClickListener or showing a 1072 * context menu. 1073 * </p> 1074 * {@hide} 1075 */ 1076 static final int LONG_CLICKABLE = 0x00200000; 1077 1078 /** 1079 * <p>Indicates that this view gets its drawable states from its direct parent 1080 * and ignores its original internal states.</p> 1081 * 1082 * @hide 1083 */ 1084 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1085 1086 /** 1087 * <p> 1088 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1089 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1090 * OnContextClickListener. 1091 * </p> 1092 * {@hide} 1093 */ 1094 static final int CONTEXT_CLICKABLE = 0x00800000; 1095 1096 1097 /** @hide */ 1098 @IntDef({ 1099 SCROLLBARS_INSIDE_OVERLAY, 1100 SCROLLBARS_INSIDE_INSET, 1101 SCROLLBARS_OUTSIDE_OVERLAY, 1102 SCROLLBARS_OUTSIDE_INSET 1103 }) 1104 @Retention(RetentionPolicy.SOURCE) 1105 public @interface ScrollBarStyle {} 1106 1107 /** 1108 * The scrollbar style to display the scrollbars inside the content area, 1109 * without increasing the padding. The scrollbars will be overlaid with 1110 * translucency on the view's content. 1111 */ 1112 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1113 1114 /** 1115 * The scrollbar style to display the scrollbars inside the padded area, 1116 * increasing the padding of the view. The scrollbars will not overlap the 1117 * content area of the view. 1118 */ 1119 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1120 1121 /** 1122 * The scrollbar style to display the scrollbars at the edge of the view, 1123 * without increasing the padding. The scrollbars will be overlaid with 1124 * translucency. 1125 */ 1126 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1127 1128 /** 1129 * The scrollbar style to display the scrollbars at the edge of the view, 1130 * increasing the padding of the view. The scrollbars will only overlap the 1131 * background, if any. 1132 */ 1133 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1134 1135 /** 1136 * Mask to check if the scrollbar style is overlay or inset. 1137 * {@hide} 1138 */ 1139 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1140 1141 /** 1142 * Mask to check if the scrollbar style is inside or outside. 1143 * {@hide} 1144 */ 1145 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1146 1147 /** 1148 * Mask for scrollbar style. 1149 * {@hide} 1150 */ 1151 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1152 1153 /** 1154 * View flag indicating that the screen should remain on while the 1155 * window containing this view is visible to the user. This effectively 1156 * takes care of automatically setting the WindowManager's 1157 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1158 */ 1159 public static final int KEEP_SCREEN_ON = 0x04000000; 1160 1161 /** 1162 * View flag indicating whether this view should have sound effects enabled 1163 * for events such as clicking and touching. 1164 */ 1165 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1166 1167 /** 1168 * View flag indicating whether this view should have haptic feedback 1169 * enabled for events such as long presses. 1170 */ 1171 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1172 1173 /** 1174 * <p>Indicates that the view hierarchy should stop saving state when 1175 * it reaches this view. If state saving is initiated immediately at 1176 * the view, it will be allowed. 1177 * {@hide} 1178 */ 1179 static final int PARENT_SAVE_DISABLED = 0x20000000; 1180 1181 /** 1182 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1183 * {@hide} 1184 */ 1185 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1186 1187 /** @hide */ 1188 @IntDef(flag = true, 1189 value = { 1190 FOCUSABLES_ALL, 1191 FOCUSABLES_TOUCH_MODE 1192 }) 1193 @Retention(RetentionPolicy.SOURCE) 1194 public @interface FocusableMode {} 1195 1196 /** 1197 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1198 * should add all focusable Views regardless if they are focusable in touch mode. 1199 */ 1200 public static final int FOCUSABLES_ALL = 0x00000000; 1201 1202 /** 1203 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1204 * should add only Views focusable in touch mode. 1205 */ 1206 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1207 1208 /** @hide */ 1209 @IntDef({ 1210 FOCUS_BACKWARD, 1211 FOCUS_FORWARD, 1212 FOCUS_LEFT, 1213 FOCUS_UP, 1214 FOCUS_RIGHT, 1215 FOCUS_DOWN 1216 }) 1217 @Retention(RetentionPolicy.SOURCE) 1218 public @interface FocusDirection {} 1219 1220 /** @hide */ 1221 @IntDef({ 1222 FOCUS_LEFT, 1223 FOCUS_UP, 1224 FOCUS_RIGHT, 1225 FOCUS_DOWN 1226 }) 1227 @Retention(RetentionPolicy.SOURCE) 1228 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1229 1230 /** 1231 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1232 * item. 1233 */ 1234 public static final int FOCUS_BACKWARD = 0x00000001; 1235 1236 /** 1237 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1238 * item. 1239 */ 1240 public static final int FOCUS_FORWARD = 0x00000002; 1241 1242 /** 1243 * Use with {@link #focusSearch(int)}. Move focus to the left. 1244 */ 1245 public static final int FOCUS_LEFT = 0x00000011; 1246 1247 /** 1248 * Use with {@link #focusSearch(int)}. Move focus up. 1249 */ 1250 public static final int FOCUS_UP = 0x00000021; 1251 1252 /** 1253 * Use with {@link #focusSearch(int)}. Move focus to the right. 1254 */ 1255 public static final int FOCUS_RIGHT = 0x00000042; 1256 1257 /** 1258 * Use with {@link #focusSearch(int)}. Move focus down. 1259 */ 1260 public static final int FOCUS_DOWN = 0x00000082; 1261 1262 /** 1263 * Bits of {@link #getMeasuredWidthAndState()} and 1264 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1265 */ 1266 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1267 1268 /** 1269 * Bits of {@link #getMeasuredWidthAndState()} and 1270 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1271 */ 1272 public static final int MEASURED_STATE_MASK = 0xff000000; 1273 1274 /** 1275 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1276 * for functions that combine both width and height into a single int, 1277 * such as {@link #getMeasuredState()} and the childState argument of 1278 * {@link #resolveSizeAndState(int, int, int)}. 1279 */ 1280 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1281 1282 /** 1283 * Bit of {@link #getMeasuredWidthAndState()} and 1284 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1285 * is smaller that the space the view would like to have. 1286 */ 1287 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1288 1289 /** 1290 * Base View state sets 1291 */ 1292 // Singles 1293 /** 1294 * Indicates the view has no states set. States are used with 1295 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1296 * view depending on its state. 1297 * 1298 * @see android.graphics.drawable.Drawable 1299 * @see #getDrawableState() 1300 */ 1301 protected static final int[] EMPTY_STATE_SET; 1302 /** 1303 * Indicates the view is enabled. States are used with 1304 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1305 * view depending on its state. 1306 * 1307 * @see android.graphics.drawable.Drawable 1308 * @see #getDrawableState() 1309 */ 1310 protected static final int[] ENABLED_STATE_SET; 1311 /** 1312 * Indicates the view is focused. States are used with 1313 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1314 * view depending on its state. 1315 * 1316 * @see android.graphics.drawable.Drawable 1317 * @see #getDrawableState() 1318 */ 1319 protected static final int[] FOCUSED_STATE_SET; 1320 /** 1321 * Indicates the view is selected. States are used with 1322 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1323 * view depending on its state. 1324 * 1325 * @see android.graphics.drawable.Drawable 1326 * @see #getDrawableState() 1327 */ 1328 protected static final int[] SELECTED_STATE_SET; 1329 /** 1330 * Indicates the view is pressed. States are used with 1331 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1332 * view depending on its state. 1333 * 1334 * @see android.graphics.drawable.Drawable 1335 * @see #getDrawableState() 1336 */ 1337 protected static final int[] PRESSED_STATE_SET; 1338 /** 1339 * Indicates the view's window has focus. States are used with 1340 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1341 * view depending on its state. 1342 * 1343 * @see android.graphics.drawable.Drawable 1344 * @see #getDrawableState() 1345 */ 1346 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1347 // Doubles 1348 /** 1349 * Indicates the view is enabled and has the focus. 1350 * 1351 * @see #ENABLED_STATE_SET 1352 * @see #FOCUSED_STATE_SET 1353 */ 1354 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1355 /** 1356 * Indicates the view is enabled and selected. 1357 * 1358 * @see #ENABLED_STATE_SET 1359 * @see #SELECTED_STATE_SET 1360 */ 1361 protected static final int[] ENABLED_SELECTED_STATE_SET; 1362 /** 1363 * Indicates the view is enabled and that its window has focus. 1364 * 1365 * @see #ENABLED_STATE_SET 1366 * @see #WINDOW_FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1369 /** 1370 * Indicates the view is focused and selected. 1371 * 1372 * @see #FOCUSED_STATE_SET 1373 * @see #SELECTED_STATE_SET 1374 */ 1375 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1376 /** 1377 * Indicates the view has the focus and that its window has the focus. 1378 * 1379 * @see #FOCUSED_STATE_SET 1380 * @see #WINDOW_FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1383 /** 1384 * Indicates the view is selected and that its window has the focus. 1385 * 1386 * @see #SELECTED_STATE_SET 1387 * @see #WINDOW_FOCUSED_STATE_SET 1388 */ 1389 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1390 // Triples 1391 /** 1392 * Indicates the view is enabled, focused and selected. 1393 * 1394 * @see #ENABLED_STATE_SET 1395 * @see #FOCUSED_STATE_SET 1396 * @see #SELECTED_STATE_SET 1397 */ 1398 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1399 /** 1400 * Indicates the view is enabled, focused and its window has the focus. 1401 * 1402 * @see #ENABLED_STATE_SET 1403 * @see #FOCUSED_STATE_SET 1404 * @see #WINDOW_FOCUSED_STATE_SET 1405 */ 1406 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1407 /** 1408 * Indicates the view is enabled, selected and its window has the focus. 1409 * 1410 * @see #ENABLED_STATE_SET 1411 * @see #SELECTED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1415 /** 1416 * Indicates the view is focused, selected and its window has the focus. 1417 * 1418 * @see #FOCUSED_STATE_SET 1419 * @see #SELECTED_STATE_SET 1420 * @see #WINDOW_FOCUSED_STATE_SET 1421 */ 1422 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1423 /** 1424 * Indicates the view is enabled, focused, selected and its window 1425 * has the focus. 1426 * 1427 * @see #ENABLED_STATE_SET 1428 * @see #FOCUSED_STATE_SET 1429 * @see #SELECTED_STATE_SET 1430 * @see #WINDOW_FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1433 /** 1434 * Indicates the view is pressed and its window has the focus. 1435 * 1436 * @see #PRESSED_STATE_SET 1437 * @see #WINDOW_FOCUSED_STATE_SET 1438 */ 1439 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1440 /** 1441 * Indicates the view is pressed and selected. 1442 * 1443 * @see #PRESSED_STATE_SET 1444 * @see #SELECTED_STATE_SET 1445 */ 1446 protected static final int[] PRESSED_SELECTED_STATE_SET; 1447 /** 1448 * Indicates the view is pressed, selected and its window has the focus. 1449 * 1450 * @see #PRESSED_STATE_SET 1451 * @see #SELECTED_STATE_SET 1452 * @see #WINDOW_FOCUSED_STATE_SET 1453 */ 1454 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1455 /** 1456 * Indicates the view is pressed and focused. 1457 * 1458 * @see #PRESSED_STATE_SET 1459 * @see #FOCUSED_STATE_SET 1460 */ 1461 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1462 /** 1463 * Indicates the view is pressed, focused and its window has the focus. 1464 * 1465 * @see #PRESSED_STATE_SET 1466 * @see #FOCUSED_STATE_SET 1467 * @see #WINDOW_FOCUSED_STATE_SET 1468 */ 1469 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1470 /** 1471 * Indicates the view is pressed, focused and selected. 1472 * 1473 * @see #PRESSED_STATE_SET 1474 * @see #SELECTED_STATE_SET 1475 * @see #FOCUSED_STATE_SET 1476 */ 1477 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1478 /** 1479 * Indicates the view is pressed, focused, selected and its window has the focus. 1480 * 1481 * @see #PRESSED_STATE_SET 1482 * @see #FOCUSED_STATE_SET 1483 * @see #SELECTED_STATE_SET 1484 * @see #WINDOW_FOCUSED_STATE_SET 1485 */ 1486 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1487 /** 1488 * Indicates the view is pressed and enabled. 1489 * 1490 * @see #PRESSED_STATE_SET 1491 * @see #ENABLED_STATE_SET 1492 */ 1493 protected static final int[] PRESSED_ENABLED_STATE_SET; 1494 /** 1495 * Indicates the view is pressed, enabled and its window has the focus. 1496 * 1497 * @see #PRESSED_STATE_SET 1498 * @see #ENABLED_STATE_SET 1499 * @see #WINDOW_FOCUSED_STATE_SET 1500 */ 1501 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1502 /** 1503 * Indicates the view is pressed, enabled and selected. 1504 * 1505 * @see #PRESSED_STATE_SET 1506 * @see #ENABLED_STATE_SET 1507 * @see #SELECTED_STATE_SET 1508 */ 1509 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1510 /** 1511 * Indicates the view is pressed, enabled, selected and its window has the 1512 * focus. 1513 * 1514 * @see #PRESSED_STATE_SET 1515 * @see #ENABLED_STATE_SET 1516 * @see #SELECTED_STATE_SET 1517 * @see #WINDOW_FOCUSED_STATE_SET 1518 */ 1519 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1520 /** 1521 * Indicates the view is pressed, enabled and focused. 1522 * 1523 * @see #PRESSED_STATE_SET 1524 * @see #ENABLED_STATE_SET 1525 * @see #FOCUSED_STATE_SET 1526 */ 1527 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1528 /** 1529 * Indicates the view is pressed, enabled, focused and its window has the 1530 * focus. 1531 * 1532 * @see #PRESSED_STATE_SET 1533 * @see #ENABLED_STATE_SET 1534 * @see #FOCUSED_STATE_SET 1535 * @see #WINDOW_FOCUSED_STATE_SET 1536 */ 1537 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1538 /** 1539 * Indicates the view is pressed, enabled, focused and selected. 1540 * 1541 * @see #PRESSED_STATE_SET 1542 * @see #ENABLED_STATE_SET 1543 * @see #SELECTED_STATE_SET 1544 * @see #FOCUSED_STATE_SET 1545 */ 1546 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1547 /** 1548 * Indicates the view is pressed, enabled, focused, selected and its window 1549 * has the focus. 1550 * 1551 * @see #PRESSED_STATE_SET 1552 * @see #ENABLED_STATE_SET 1553 * @see #SELECTED_STATE_SET 1554 * @see #FOCUSED_STATE_SET 1555 * @see #WINDOW_FOCUSED_STATE_SET 1556 */ 1557 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1558 1559 static { 1560 EMPTY_STATE_SET = StateSet.get(0); 1561 1562 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1563 1564 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1565 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1566 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1567 1568 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1569 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1570 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1571 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1572 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1573 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1574 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1575 | StateSet.VIEW_STATE_FOCUSED); 1576 1577 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1578 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1579 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1580 ENABLED_SELECTED_STATE_SET = StateSet.get( 1581 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1582 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1583 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1584 | StateSet.VIEW_STATE_ENABLED); 1585 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1586 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1587 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1588 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1589 | StateSet.VIEW_STATE_ENABLED); 1590 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1591 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1592 | StateSet.VIEW_STATE_ENABLED); 1593 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1594 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1595 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1596 1597 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1598 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1599 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1600 PRESSED_SELECTED_STATE_SET = StateSet.get( 1601 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1602 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1603 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1604 | StateSet.VIEW_STATE_PRESSED); 1605 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1606 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1607 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1608 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1609 | StateSet.VIEW_STATE_PRESSED); 1610 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1611 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1612 | StateSet.VIEW_STATE_PRESSED); 1613 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1614 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1615 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1616 PRESSED_ENABLED_STATE_SET = StateSet.get( 1617 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1618 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1619 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1620 | StateSet.VIEW_STATE_PRESSED); 1621 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1622 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1623 | StateSet.VIEW_STATE_PRESSED); 1624 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1625 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1626 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1627 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1628 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1629 | StateSet.VIEW_STATE_PRESSED); 1630 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1631 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1632 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1633 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1634 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1635 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1636 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1637 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1638 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1639 | StateSet.VIEW_STATE_PRESSED); 1640 } 1641 1642 /** 1643 * Accessibility event types that are dispatched for text population. 1644 */ 1645 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1646 AccessibilityEvent.TYPE_VIEW_CLICKED 1647 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1648 | AccessibilityEvent.TYPE_VIEW_SELECTED 1649 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1650 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1651 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1652 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1653 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1654 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1655 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1656 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1657 1658 /** 1659 * Temporary Rect currently for use in setBackground(). This will probably 1660 * be extended in the future to hold our own class with more than just 1661 * a Rect. :) 1662 */ 1663 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1664 1665 /** 1666 * Map used to store views' tags. 1667 */ 1668 private SparseArray<Object> mKeyedTags; 1669 1670 /** 1671 * The next available accessibility id. 1672 */ 1673 private static int sNextAccessibilityViewId; 1674 1675 /** 1676 * The animation currently associated with this view. 1677 * @hide 1678 */ 1679 protected Animation mCurrentAnimation = null; 1680 1681 /** 1682 * Width as measured during measure pass. 1683 * {@hide} 1684 */ 1685 @ViewDebug.ExportedProperty(category = "measurement") 1686 int mMeasuredWidth; 1687 1688 /** 1689 * Height as measured during measure pass. 1690 * {@hide} 1691 */ 1692 @ViewDebug.ExportedProperty(category = "measurement") 1693 int mMeasuredHeight; 1694 1695 /** 1696 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1697 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1698 * its display list. This flag, used only when hw accelerated, allows us to clear the 1699 * flag while retaining this information until it's needed (at getDisplayList() time and 1700 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1701 * 1702 * {@hide} 1703 */ 1704 boolean mRecreateDisplayList = false; 1705 1706 /** 1707 * The view's identifier. 1708 * {@hide} 1709 * 1710 * @see #setId(int) 1711 * @see #getId() 1712 */ 1713 @IdRes 1714 @ViewDebug.ExportedProperty(resolveId = true) 1715 int mID = NO_ID; 1716 1717 /** 1718 * The stable ID of this view for accessibility purposes. 1719 */ 1720 int mAccessibilityViewId = NO_ID; 1721 1722 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1723 1724 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1725 1726 /** 1727 * The view's tag. 1728 * {@hide} 1729 * 1730 * @see #setTag(Object) 1731 * @see #getTag() 1732 */ 1733 protected Object mTag = null; 1734 1735 // for mPrivateFlags: 1736 /** {@hide} */ 1737 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1738 /** {@hide} */ 1739 static final int PFLAG_FOCUSED = 0x00000002; 1740 /** {@hide} */ 1741 static final int PFLAG_SELECTED = 0x00000004; 1742 /** {@hide} */ 1743 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1744 /** {@hide} */ 1745 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1746 /** {@hide} */ 1747 static final int PFLAG_DRAWN = 0x00000020; 1748 /** 1749 * When this flag is set, this view is running an animation on behalf of its 1750 * children and should therefore not cancel invalidate requests, even if they 1751 * lie outside of this view's bounds. 1752 * 1753 * {@hide} 1754 */ 1755 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1756 /** {@hide} */ 1757 static final int PFLAG_SKIP_DRAW = 0x00000080; 1758 /** {@hide} */ 1759 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1760 /** {@hide} */ 1761 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1762 /** {@hide} */ 1763 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1764 /** {@hide} */ 1765 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1766 /** {@hide} */ 1767 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1768 1769 private static final int PFLAG_PRESSED = 0x00004000; 1770 1771 /** {@hide} */ 1772 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1773 /** 1774 * Flag used to indicate that this view should be drawn once more (and only once 1775 * more) after its animation has completed. 1776 * {@hide} 1777 */ 1778 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1779 1780 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1781 1782 /** 1783 * Indicates that the View returned true when onSetAlpha() was called and that 1784 * the alpha must be restored. 1785 * {@hide} 1786 */ 1787 static final int PFLAG_ALPHA_SET = 0x00040000; 1788 1789 /** 1790 * Set by {@link #setScrollContainer(boolean)}. 1791 */ 1792 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1793 1794 /** 1795 * Set by {@link #setScrollContainer(boolean)}. 1796 */ 1797 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1798 1799 /** 1800 * View flag indicating whether this view was invalidated (fully or partially.) 1801 * 1802 * @hide 1803 */ 1804 static final int PFLAG_DIRTY = 0x00200000; 1805 1806 /** 1807 * View flag indicating whether this view was invalidated by an opaque 1808 * invalidate request. 1809 * 1810 * @hide 1811 */ 1812 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1813 1814 /** 1815 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_DIRTY_MASK = 0x00600000; 1820 1821 /** 1822 * Indicates whether the background is opaque. 1823 * 1824 * @hide 1825 */ 1826 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1827 1828 /** 1829 * Indicates whether the scrollbars are opaque. 1830 * 1831 * @hide 1832 */ 1833 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1834 1835 /** 1836 * Indicates whether the view is opaque. 1837 * 1838 * @hide 1839 */ 1840 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1841 1842 /** 1843 * Indicates a prepressed state; 1844 * the short time between ACTION_DOWN and recognizing 1845 * a 'real' press. Prepressed is used to recognize quick taps 1846 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1847 * 1848 * @hide 1849 */ 1850 private static final int PFLAG_PREPRESSED = 0x02000000; 1851 1852 /** 1853 * Indicates whether the view is temporarily detached. 1854 * 1855 * @hide 1856 */ 1857 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1858 1859 /** 1860 * Indicates that we should awaken scroll bars once attached 1861 * 1862 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1863 * during window attachment and it is no longer needed. Feel free to repurpose it. 1864 * 1865 * @hide 1866 */ 1867 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1868 1869 /** 1870 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1871 * @hide 1872 */ 1873 private static final int PFLAG_HOVERED = 0x10000000; 1874 1875 /** 1876 * no longer needed, should be reused 1877 */ 1878 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1879 1880 /** {@hide} */ 1881 static final int PFLAG_ACTIVATED = 0x40000000; 1882 1883 /** 1884 * Indicates that this view was specifically invalidated, not just dirtied because some 1885 * child view was invalidated. The flag is used to determine when we need to recreate 1886 * a view's display list (as opposed to just returning a reference to its existing 1887 * display list). 1888 * 1889 * @hide 1890 */ 1891 static final int PFLAG_INVALIDATED = 0x80000000; 1892 1893 /** 1894 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1895 * 1896 * |-------|-------|-------|-------| 1897 * 1 PFLAG2_DRAG_CAN_ACCEPT 1898 * 1 PFLAG2_DRAG_HOVERED 1899 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1900 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1901 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1902 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1903 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1904 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1905 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1906 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1907 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1908 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1909 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1910 * 111 PFLAG2_TEXT_DIRECTION_MASK 1911 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1912 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1913 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1914 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1915 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1916 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1917 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1918 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1919 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1920 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1921 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1922 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1923 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1924 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1925 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1926 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1927 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1928 * 1 PFLAG2_VIEW_QUICK_REJECTED 1929 * 1 PFLAG2_PADDING_RESOLVED 1930 * 1 PFLAG2_DRAWABLE_RESOLVED 1931 * 1 PFLAG2_HAS_TRANSIENT_STATE 1932 * |-------|-------|-------|-------| 1933 */ 1934 1935 /** 1936 * Indicates that this view has reported that it can accept the current drag's content. 1937 * Cleared when the drag operation concludes. 1938 * @hide 1939 */ 1940 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1941 1942 /** 1943 * Indicates that this view is currently directly under the drag location in a 1944 * drag-and-drop operation involving content that it can accept. Cleared when 1945 * the drag exits the view, or when the drag operation concludes. 1946 * @hide 1947 */ 1948 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1949 1950 /** @hide */ 1951 @IntDef({ 1952 LAYOUT_DIRECTION_LTR, 1953 LAYOUT_DIRECTION_RTL, 1954 LAYOUT_DIRECTION_INHERIT, 1955 LAYOUT_DIRECTION_LOCALE 1956 }) 1957 @Retention(RetentionPolicy.SOURCE) 1958 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1959 public @interface LayoutDir {} 1960 1961 /** @hide */ 1962 @IntDef({ 1963 LAYOUT_DIRECTION_LTR, 1964 LAYOUT_DIRECTION_RTL 1965 }) 1966 @Retention(RetentionPolicy.SOURCE) 1967 public @interface ResolvedLayoutDir {} 1968 1969 /** 1970 * A flag to indicate that the layout direction of this view has not been defined yet. 1971 * @hide 1972 */ 1973 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1974 1975 /** 1976 * Horizontal layout direction of this view is from Left to Right. 1977 * Use with {@link #setLayoutDirection}. 1978 */ 1979 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1980 1981 /** 1982 * Horizontal layout direction of this view is from Right to Left. 1983 * Use with {@link #setLayoutDirection}. 1984 */ 1985 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1986 1987 /** 1988 * Horizontal layout direction of this view is inherited from its parent. 1989 * Use with {@link #setLayoutDirection}. 1990 */ 1991 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1992 1993 /** 1994 * Horizontal layout direction of this view is from deduced from the default language 1995 * script for the locale. Use with {@link #setLayoutDirection}. 1996 */ 1997 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1998 1999 /** 2000 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2001 * @hide 2002 */ 2003 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2004 2005 /** 2006 * Mask for use with private flags indicating bits used for horizontal layout direction. 2007 * @hide 2008 */ 2009 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2010 2011 /** 2012 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2013 * right-to-left direction. 2014 * @hide 2015 */ 2016 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2017 2018 /** 2019 * Indicates whether the view horizontal layout direction has been resolved. 2020 * @hide 2021 */ 2022 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2023 2024 /** 2025 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2026 * @hide 2027 */ 2028 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2029 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2030 2031 /* 2032 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2033 * flag value. 2034 * @hide 2035 */ 2036 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2037 LAYOUT_DIRECTION_LTR, 2038 LAYOUT_DIRECTION_RTL, 2039 LAYOUT_DIRECTION_INHERIT, 2040 LAYOUT_DIRECTION_LOCALE 2041 }; 2042 2043 /** 2044 * Default horizontal layout direction. 2045 */ 2046 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2047 2048 /** 2049 * Default horizontal layout direction. 2050 * @hide 2051 */ 2052 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2053 2054 /** 2055 * Text direction is inherited through {@link ViewGroup} 2056 */ 2057 public static final int TEXT_DIRECTION_INHERIT = 0; 2058 2059 /** 2060 * Text direction is using "first strong algorithm". The first strong directional character 2061 * determines the paragraph direction. If there is no strong directional character, the 2062 * paragraph direction is the view's resolved layout direction. 2063 */ 2064 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2065 2066 /** 2067 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2068 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2069 * If there are neither, the paragraph direction is the view's resolved layout direction. 2070 */ 2071 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2072 2073 /** 2074 * Text direction is forced to LTR. 2075 */ 2076 public static final int TEXT_DIRECTION_LTR = 3; 2077 2078 /** 2079 * Text direction is forced to RTL. 2080 */ 2081 public static final int TEXT_DIRECTION_RTL = 4; 2082 2083 /** 2084 * Text direction is coming from the system Locale. 2085 */ 2086 public static final int TEXT_DIRECTION_LOCALE = 5; 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 LTR. 2092 */ 2093 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2094 2095 /** 2096 * Text direction is using "first strong algorithm". The first strong directional character 2097 * determines the paragraph direction. If there is no strong directional character, the 2098 * paragraph direction is RTL. 2099 */ 2100 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2101 2102 /** 2103 * Default text direction is inherited 2104 */ 2105 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2106 2107 /** 2108 * Default resolved text direction 2109 * @hide 2110 */ 2111 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2112 2113 /** 2114 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2115 * @hide 2116 */ 2117 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2118 2119 /** 2120 * Mask for use with private flags indicating bits used for text direction. 2121 * @hide 2122 */ 2123 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2124 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2125 2126 /** 2127 * Array of text direction flags for mapping attribute "textDirection" to correct 2128 * flag value. 2129 * @hide 2130 */ 2131 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2132 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2133 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2134 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2135 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2136 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2137 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2138 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2139 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2140 }; 2141 2142 /** 2143 * Indicates whether the view text direction has been resolved. 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2147 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2148 2149 /** 2150 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2151 * @hide 2152 */ 2153 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2154 2155 /** 2156 * Mask for use with private flags indicating bits used for resolved text direction. 2157 * @hide 2158 */ 2159 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2160 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2161 2162 /** 2163 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2164 * @hide 2165 */ 2166 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2167 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2168 2169 /** @hide */ 2170 @IntDef({ 2171 TEXT_ALIGNMENT_INHERIT, 2172 TEXT_ALIGNMENT_GRAVITY, 2173 TEXT_ALIGNMENT_CENTER, 2174 TEXT_ALIGNMENT_TEXT_START, 2175 TEXT_ALIGNMENT_TEXT_END, 2176 TEXT_ALIGNMENT_VIEW_START, 2177 TEXT_ALIGNMENT_VIEW_END 2178 }) 2179 @Retention(RetentionPolicy.SOURCE) 2180 public @interface TextAlignment {} 2181 2182 /** 2183 * Default text alignment. The text alignment of this View is inherited from its parent. 2184 * Use with {@link #setTextAlignment(int)} 2185 */ 2186 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2187 2188 /** 2189 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2190 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2191 * 2192 * Use with {@link #setTextAlignment(int)} 2193 */ 2194 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2195 2196 /** 2197 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2198 * 2199 * Use with {@link #setTextAlignment(int)} 2200 */ 2201 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2202 2203 /** 2204 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2205 * 2206 * Use with {@link #setTextAlignment(int)} 2207 */ 2208 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2209 2210 /** 2211 * Center the paragraph, e.g. ALIGN_CENTER. 2212 * 2213 * Use with {@link #setTextAlignment(int)} 2214 */ 2215 public static final int TEXT_ALIGNMENT_CENTER = 4; 2216 2217 /** 2218 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2219 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2220 * 2221 * Use with {@link #setTextAlignment(int)} 2222 */ 2223 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2224 2225 /** 2226 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2227 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2228 * 2229 * Use with {@link #setTextAlignment(int)} 2230 */ 2231 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2232 2233 /** 2234 * Default text alignment is inherited 2235 */ 2236 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2237 2238 /** 2239 * Default resolved text alignment 2240 * @hide 2241 */ 2242 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2243 2244 /** 2245 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2246 * @hide 2247 */ 2248 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2249 2250 /** 2251 * Mask for use with private flags indicating bits used for text alignment. 2252 * @hide 2253 */ 2254 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2255 2256 /** 2257 * Array of text direction flags for mapping attribute "textAlignment" to correct 2258 * flag value. 2259 * @hide 2260 */ 2261 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2262 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2263 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2264 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2265 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2266 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2267 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2268 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2269 }; 2270 2271 /** 2272 * Indicates whether the view text alignment has been resolved. 2273 * @hide 2274 */ 2275 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2276 2277 /** 2278 * Bit shift to get the resolved text alignment. 2279 * @hide 2280 */ 2281 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2282 2283 /** 2284 * Mask for use with private flags indicating bits used for text alignment. 2285 * @hide 2286 */ 2287 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2288 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2289 2290 /** 2291 * Indicates whether if the view text alignment has been resolved to gravity 2292 */ 2293 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2294 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2295 2296 // Accessiblity constants for mPrivateFlags2 2297 2298 /** 2299 * Shift for the bits in {@link #mPrivateFlags2} related to the 2300 * "importantForAccessibility" attribute. 2301 */ 2302 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2303 2304 /** 2305 * Automatically determine whether a view is important for accessibility. 2306 */ 2307 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2308 2309 /** 2310 * The view is important for accessibility. 2311 */ 2312 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2313 2314 /** 2315 * The view is not important for accessibility. 2316 */ 2317 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2318 2319 /** 2320 * The view is not important for accessibility, nor are any of its 2321 * descendant views. 2322 */ 2323 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2324 2325 /** 2326 * The default whether the view is important for accessibility. 2327 */ 2328 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2329 2330 /** 2331 * Mask for obtaining the bits which specify how to determine 2332 * whether a view is important for accessibility. 2333 */ 2334 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2335 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2336 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2337 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2338 2339 /** 2340 * Shift for the bits in {@link #mPrivateFlags2} related to the 2341 * "accessibilityLiveRegion" attribute. 2342 */ 2343 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2344 2345 /** 2346 * Live region mode specifying that accessibility services should not 2347 * automatically announce changes to this view. This is the default live 2348 * region mode for most views. 2349 * <p> 2350 * Use with {@link #setAccessibilityLiveRegion(int)}. 2351 */ 2352 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2353 2354 /** 2355 * Live region mode specifying that accessibility services should announce 2356 * changes to this view. 2357 * <p> 2358 * Use with {@link #setAccessibilityLiveRegion(int)}. 2359 */ 2360 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2361 2362 /** 2363 * Live region mode specifying that accessibility services should interrupt 2364 * ongoing speech to immediately announce changes to this view. 2365 * <p> 2366 * Use with {@link #setAccessibilityLiveRegion(int)}. 2367 */ 2368 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2369 2370 /** 2371 * The default whether the view is important for accessibility. 2372 */ 2373 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2374 2375 /** 2376 * Mask for obtaining the bits which specify a view's accessibility live 2377 * region mode. 2378 */ 2379 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2380 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2381 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2382 2383 /** 2384 * Flag indicating whether a view has accessibility focus. 2385 */ 2386 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2387 2388 /** 2389 * Flag whether the accessibility state of the subtree rooted at this view changed. 2390 */ 2391 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2392 2393 /** 2394 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2395 * is used to check whether later changes to the view's transform should invalidate the 2396 * view to force the quickReject test to run again. 2397 */ 2398 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2399 2400 /** 2401 * Flag indicating that start/end padding has been resolved into left/right padding 2402 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2403 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2404 * during measurement. In some special cases this is required such as when an adapter-based 2405 * view measures prospective children without attaching them to a window. 2406 */ 2407 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2408 2409 /** 2410 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2411 */ 2412 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2413 2414 /** 2415 * Indicates that the view is tracking some sort of transient state 2416 * that the app should not need to be aware of, but that the framework 2417 * should take special care to preserve. 2418 */ 2419 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2420 2421 /** 2422 * Group of bits indicating that RTL properties resolution is done. 2423 */ 2424 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2425 PFLAG2_TEXT_DIRECTION_RESOLVED | 2426 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2427 PFLAG2_PADDING_RESOLVED | 2428 PFLAG2_DRAWABLE_RESOLVED; 2429 2430 // There are a couple of flags left in mPrivateFlags2 2431 2432 /* End of masks for mPrivateFlags2 */ 2433 2434 /** 2435 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2436 * 2437 * |-------|-------|-------|-------| 2438 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2439 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2440 * 1 PFLAG3_IS_LAID_OUT 2441 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2442 * 1 PFLAG3_CALLED_SUPER 2443 * 1 PFLAG3_APPLYING_INSETS 2444 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2445 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2446 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2447 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2448 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2449 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2450 * 1 PFLAG3_SCROLL_INDICATOR_START 2451 * 1 PFLAG3_SCROLL_INDICATOR_END 2452 * 1 PFLAG3_ASSIST_BLOCKED 2453 * xxxxxxxx * NO LONGER NEEDED, SHOULD BE REUSED * 2454 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2455 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2456 * 1 PFLAG3_TEMPORARY_DETACH 2457 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2458 * |-------|-------|-------|-------| 2459 */ 2460 2461 /** 2462 * Flag indicating that view has a transform animation set on it. This is used to track whether 2463 * an animation is cleared between successive frames, in order to tell the associated 2464 * DisplayList to clear its animation matrix. 2465 */ 2466 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2467 2468 /** 2469 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2470 * animation is cleared between successive frames, in order to tell the associated 2471 * DisplayList to restore its alpha value. 2472 */ 2473 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2474 2475 /** 2476 * Flag indicating that the view has been through at least one layout since it 2477 * was last attached to a window. 2478 */ 2479 static final int PFLAG3_IS_LAID_OUT = 0x4; 2480 2481 /** 2482 * Flag indicating that a call to measure() was skipped and should be done 2483 * instead when layout() is invoked. 2484 */ 2485 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2486 2487 /** 2488 * Flag indicating that an overridden method correctly called down to 2489 * the superclass implementation as required by the API spec. 2490 */ 2491 static final int PFLAG3_CALLED_SUPER = 0x10; 2492 2493 /** 2494 * Flag indicating that we're in the process of applying window insets. 2495 */ 2496 static final int PFLAG3_APPLYING_INSETS = 0x20; 2497 2498 /** 2499 * Flag indicating that we're in the process of fitting system windows using the old method. 2500 */ 2501 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2502 2503 /** 2504 * Flag indicating that nested scrolling is enabled for this view. 2505 * The view will optionally cooperate with views up its parent chain to allow for 2506 * integrated nested scrolling along the same axis. 2507 */ 2508 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2509 2510 /** 2511 * Flag indicating that the bottom scroll indicator should be displayed 2512 * when this view can scroll up. 2513 */ 2514 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2515 2516 /** 2517 * Flag indicating that the bottom scroll indicator should be displayed 2518 * when this view can scroll down. 2519 */ 2520 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2521 2522 /** 2523 * Flag indicating that the left scroll indicator should be displayed 2524 * when this view can scroll left. 2525 */ 2526 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2527 2528 /** 2529 * Flag indicating that the right scroll indicator should be displayed 2530 * when this view can scroll right. 2531 */ 2532 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2533 2534 /** 2535 * Flag indicating that the start scroll indicator should be displayed 2536 * when this view can scroll in the start direction. 2537 */ 2538 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2539 2540 /** 2541 * Flag indicating that the end scroll indicator should be displayed 2542 * when this view can scroll in the end direction. 2543 */ 2544 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2545 2546 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2547 2548 static final int SCROLL_INDICATORS_NONE = 0x0000; 2549 2550 /** 2551 * Mask for use with setFlags indicating bits used for indicating which 2552 * scroll indicators are enabled. 2553 */ 2554 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2555 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2556 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2557 | PFLAG3_SCROLL_INDICATOR_END; 2558 2559 /** 2560 * Left-shift required to translate between public scroll indicator flags 2561 * and internal PFLAGS3 flags. When used as a right-shift, translates 2562 * PFLAGS3 flags to public flags. 2563 */ 2564 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2565 2566 /** @hide */ 2567 @Retention(RetentionPolicy.SOURCE) 2568 @IntDef(flag = true, 2569 value = { 2570 SCROLL_INDICATOR_TOP, 2571 SCROLL_INDICATOR_BOTTOM, 2572 SCROLL_INDICATOR_LEFT, 2573 SCROLL_INDICATOR_RIGHT, 2574 SCROLL_INDICATOR_START, 2575 SCROLL_INDICATOR_END, 2576 }) 2577 public @interface ScrollIndicators {} 2578 2579 /** 2580 * Scroll indicator direction for the top edge of the view. 2581 * 2582 * @see #setScrollIndicators(int) 2583 * @see #setScrollIndicators(int, int) 2584 * @see #getScrollIndicators() 2585 */ 2586 public static final int SCROLL_INDICATOR_TOP = 2587 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2588 2589 /** 2590 * Scroll indicator direction for the bottom edge of the view. 2591 * 2592 * @see #setScrollIndicators(int) 2593 * @see #setScrollIndicators(int, int) 2594 * @see #getScrollIndicators() 2595 */ 2596 public static final int SCROLL_INDICATOR_BOTTOM = 2597 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2598 2599 /** 2600 * Scroll indicator direction for the left edge of the view. 2601 * 2602 * @see #setScrollIndicators(int) 2603 * @see #setScrollIndicators(int, int) 2604 * @see #getScrollIndicators() 2605 */ 2606 public static final int SCROLL_INDICATOR_LEFT = 2607 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2608 2609 /** 2610 * Scroll indicator direction for the right edge of the view. 2611 * 2612 * @see #setScrollIndicators(int) 2613 * @see #setScrollIndicators(int, int) 2614 * @see #getScrollIndicators() 2615 */ 2616 public static final int SCROLL_INDICATOR_RIGHT = 2617 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2618 2619 /** 2620 * Scroll indicator direction for the starting edge of the view. 2621 * <p> 2622 * Resolved according to the view's layout direction, see 2623 * {@link #getLayoutDirection()} for more information. 2624 * 2625 * @see #setScrollIndicators(int) 2626 * @see #setScrollIndicators(int, int) 2627 * @see #getScrollIndicators() 2628 */ 2629 public static final int SCROLL_INDICATOR_START = 2630 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2631 2632 /** 2633 * Scroll indicator direction for the ending edge of the view. 2634 * <p> 2635 * Resolved according to the view's layout direction, see 2636 * {@link #getLayoutDirection()} for more information. 2637 * 2638 * @see #setScrollIndicators(int) 2639 * @see #setScrollIndicators(int, int) 2640 * @see #getScrollIndicators() 2641 */ 2642 public static final int SCROLL_INDICATOR_END = 2643 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2644 2645 /** 2646 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2647 * into this view.<p> 2648 */ 2649 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2650 2651 /** 2652 * Whether this view has rendered elements that overlap (see {@link 2653 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 2654 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 2655 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 2656 * determined by whatever {@link #hasOverlappingRendering()} returns. 2657 */ 2658 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 2659 2660 /** 2661 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 2662 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 2663 */ 2664 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 2665 2666 /** 2667 * Flag indicating that the view is temporarily detached from the parent view. 2668 * 2669 * @see #onStartTemporaryDetach() 2670 * @see #onFinishTemporaryDetach() 2671 */ 2672 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 2673 2674 /** 2675 * Flag indicating that the view does not wish to be revealed within its parent 2676 * hierarchy when it gains focus. Expressed in the negative since the historical 2677 * default behavior is to reveal on focus; this flag suppresses that behavior. 2678 * 2679 * @see #setRevealOnFocusHint(boolean) 2680 * @see #getRevealOnFocusHint() 2681 */ 2682 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 2683 2684 /* End of masks for mPrivateFlags3 */ 2685 2686 /** 2687 * Always allow a user to over-scroll this view, provided it is a 2688 * view that can scroll. 2689 * 2690 * @see #getOverScrollMode() 2691 * @see #setOverScrollMode(int) 2692 */ 2693 public static final int OVER_SCROLL_ALWAYS = 0; 2694 2695 /** 2696 * Allow a user to over-scroll this view only if the content is large 2697 * enough to meaningfully scroll, provided it is a view that can scroll. 2698 * 2699 * @see #getOverScrollMode() 2700 * @see #setOverScrollMode(int) 2701 */ 2702 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2703 2704 /** 2705 * Never allow a user to over-scroll this view. 2706 * 2707 * @see #getOverScrollMode() 2708 * @see #setOverScrollMode(int) 2709 */ 2710 public static final int OVER_SCROLL_NEVER = 2; 2711 2712 /** 2713 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2714 * requested the system UI (status bar) to be visible (the default). 2715 * 2716 * @see #setSystemUiVisibility(int) 2717 */ 2718 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2719 2720 /** 2721 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2722 * system UI to enter an unobtrusive "low profile" mode. 2723 * 2724 * <p>This is for use in games, book readers, video players, or any other 2725 * "immersive" application where the usual system chrome is deemed too distracting. 2726 * 2727 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2728 * 2729 * @see #setSystemUiVisibility(int) 2730 */ 2731 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2732 2733 /** 2734 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2735 * system navigation be temporarily hidden. 2736 * 2737 * <p>This is an even less obtrusive state than that called for by 2738 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2739 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2740 * those to disappear. This is useful (in conjunction with the 2741 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2742 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2743 * window flags) for displaying content using every last pixel on the display. 2744 * 2745 * <p>There is a limitation: because navigation controls are so important, the least user 2746 * interaction will cause them to reappear immediately. When this happens, both 2747 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2748 * so that both elements reappear at the same time. 2749 * 2750 * @see #setSystemUiVisibility(int) 2751 */ 2752 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2753 2754 /** 2755 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2756 * into the normal fullscreen mode so that its content can take over the screen 2757 * while still allowing the user to interact with the application. 2758 * 2759 * <p>This has the same visual effect as 2760 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2761 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2762 * meaning that non-critical screen decorations (such as the status bar) will be 2763 * hidden while the user is in the View's window, focusing the experience on 2764 * that content. Unlike the window flag, if you are using ActionBar in 2765 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2766 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2767 * hide the action bar. 2768 * 2769 * <p>This approach to going fullscreen is best used over the window flag when 2770 * it is a transient state -- that is, the application does this at certain 2771 * points in its user interaction where it wants to allow the user to focus 2772 * on content, but not as a continuous state. For situations where the application 2773 * would like to simply stay full screen the entire time (such as a game that 2774 * wants to take over the screen), the 2775 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2776 * is usually a better approach. The state set here will be removed by the system 2777 * in various situations (such as the user moving to another application) like 2778 * the other system UI states. 2779 * 2780 * <p>When using this flag, the application should provide some easy facility 2781 * for the user to go out of it. A common example would be in an e-book 2782 * reader, where tapping on the screen brings back whatever screen and UI 2783 * decorations that had been hidden while the user was immersed in reading 2784 * the book. 2785 * 2786 * @see #setSystemUiVisibility(int) 2787 */ 2788 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2789 2790 /** 2791 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2792 * flags, we would like a stable view of the content insets given to 2793 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2794 * will always represent the worst case that the application can expect 2795 * as a continuous state. In the stock Android UI this is the space for 2796 * the system bar, nav bar, and status bar, but not more transient elements 2797 * such as an input method. 2798 * 2799 * The stable layout your UI sees is based on the system UI modes you can 2800 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2801 * then you will get a stable layout for changes of the 2802 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2803 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2804 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2805 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2806 * with a stable layout. (Note that you should avoid using 2807 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2808 * 2809 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2810 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2811 * then a hidden status bar will be considered a "stable" state for purposes 2812 * here. This allows your UI to continually hide the status bar, while still 2813 * using the system UI flags to hide the action bar while still retaining 2814 * a stable layout. Note that changing the window fullscreen flag will never 2815 * provide a stable layout for a clean transition. 2816 * 2817 * <p>If you are using ActionBar in 2818 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2819 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2820 * insets it adds to those given to the application. 2821 */ 2822 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2823 2824 /** 2825 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2826 * to be laid out as if it has requested 2827 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2828 * allows it to avoid artifacts when switching in and out of that mode, at 2829 * the expense that some of its user interface may be covered by screen 2830 * decorations when they are shown. You can perform layout of your inner 2831 * UI elements to account for the navigation system UI through the 2832 * {@link #fitSystemWindows(Rect)} method. 2833 */ 2834 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2835 2836 /** 2837 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2838 * to be laid out as if it has requested 2839 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2840 * allows it to avoid artifacts when switching in and out of that mode, at 2841 * the expense that some of its user interface may be covered by screen 2842 * decorations when they are shown. You can perform layout of your inner 2843 * UI elements to account for non-fullscreen system UI through the 2844 * {@link #fitSystemWindows(Rect)} method. 2845 */ 2846 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2847 2848 /** 2849 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2850 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2851 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2852 * user interaction. 2853 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2854 * has an effect when used in combination with that flag.</p> 2855 */ 2856 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2857 2858 /** 2859 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2860 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2861 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2862 * experience while also hiding the system bars. If this flag is not set, 2863 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2864 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2865 * if the user swipes from the top of the screen. 2866 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2867 * system gestures, such as swiping from the top of the screen. These transient system bars 2868 * will overlay app’s content, may have some degree of transparency, and will automatically 2869 * hide after a short timeout. 2870 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2871 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2872 * with one or both of those flags.</p> 2873 */ 2874 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2875 2876 /** 2877 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2878 * is compatible with light status bar backgrounds. 2879 * 2880 * <p>For this to take effect, the window must request 2881 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2882 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2883 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2884 * FLAG_TRANSLUCENT_STATUS}. 2885 * 2886 * @see android.R.attr#windowLightStatusBar 2887 */ 2888 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2889 2890 /** 2891 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2892 */ 2893 @Deprecated 2894 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2895 2896 /** 2897 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2898 */ 2899 @Deprecated 2900 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2901 2902 /** 2903 * @hide 2904 * 2905 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2906 * out of the public fields to keep the undefined bits out of the developer's way. 2907 * 2908 * Flag to make the status bar not expandable. Unless you also 2909 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2910 */ 2911 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2912 2913 /** 2914 * @hide 2915 * 2916 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2917 * out of the public fields to keep the undefined bits out of the developer's way. 2918 * 2919 * Flag to hide notification icons and scrolling ticker text. 2920 */ 2921 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2922 2923 /** 2924 * @hide 2925 * 2926 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2927 * out of the public fields to keep the undefined bits out of the developer's way. 2928 * 2929 * Flag to disable incoming notification alerts. This will not block 2930 * icons, but it will block sound, vibrating and other visual or aural notifications. 2931 */ 2932 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2933 2934 /** 2935 * @hide 2936 * 2937 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2938 * out of the public fields to keep the undefined bits out of the developer's way. 2939 * 2940 * Flag to hide only the scrolling ticker. Note that 2941 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2942 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2943 */ 2944 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2945 2946 /** 2947 * @hide 2948 * 2949 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2950 * out of the public fields to keep the undefined bits out of the developer's way. 2951 * 2952 * Flag to hide the center system info area. 2953 */ 2954 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2955 2956 /** 2957 * @hide 2958 * 2959 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2960 * out of the public fields to keep the undefined bits out of the developer's way. 2961 * 2962 * Flag to hide only the home button. Don't use this 2963 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2964 */ 2965 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2966 2967 /** 2968 * @hide 2969 * 2970 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2971 * out of the public fields to keep the undefined bits out of the developer's way. 2972 * 2973 * Flag to hide only the back button. Don't use this 2974 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2975 */ 2976 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2977 2978 /** 2979 * @hide 2980 * 2981 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2982 * out of the public fields to keep the undefined bits out of the developer's way. 2983 * 2984 * Flag to hide only the clock. You might use this if your activity has 2985 * its own clock making the status bar's clock redundant. 2986 */ 2987 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2988 2989 /** 2990 * @hide 2991 * 2992 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2993 * out of the public fields to keep the undefined bits out of the developer's way. 2994 * 2995 * Flag to hide only the recent apps button. Don't use this 2996 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2997 */ 2998 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2999 3000 /** 3001 * @hide 3002 * 3003 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3004 * out of the public fields to keep the undefined bits out of the developer's way. 3005 * 3006 * Flag to disable the global search gesture. Don't use this 3007 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3008 */ 3009 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3010 3011 /** 3012 * @hide 3013 * 3014 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3015 * out of the public fields to keep the undefined bits out of the developer's way. 3016 * 3017 * Flag to specify that the status bar is displayed in transient mode. 3018 */ 3019 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3020 3021 /** 3022 * @hide 3023 * 3024 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3025 * out of the public fields to keep the undefined bits out of the developer's way. 3026 * 3027 * Flag to specify that the navigation bar is displayed in transient mode. 3028 */ 3029 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3030 3031 /** 3032 * @hide 3033 * 3034 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3035 * out of the public fields to keep the undefined bits out of the developer's way. 3036 * 3037 * Flag to specify that the hidden status bar would like to be shown. 3038 */ 3039 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3040 3041 /** 3042 * @hide 3043 * 3044 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3045 * out of the public fields to keep the undefined bits out of the developer's way. 3046 * 3047 * Flag to specify that the hidden navigation bar would like to be shown. 3048 */ 3049 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3050 3051 /** 3052 * @hide 3053 * 3054 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3055 * out of the public fields to keep the undefined bits out of the developer's way. 3056 * 3057 * Flag to specify that the status bar is displayed in translucent mode. 3058 */ 3059 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3060 3061 /** 3062 * @hide 3063 * 3064 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3065 * out of the public fields to keep the undefined bits out of the developer's way. 3066 * 3067 * Flag to specify that the navigation bar is displayed in translucent mode. 3068 */ 3069 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3070 3071 /** 3072 * @hide 3073 * 3074 * Makes navigation bar transparent (but not the status bar). 3075 */ 3076 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3077 3078 /** 3079 * @hide 3080 * 3081 * Makes status bar transparent (but not the navigation bar). 3082 */ 3083 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3084 3085 /** 3086 * @hide 3087 * 3088 * Makes both status bar and navigation bar transparent. 3089 */ 3090 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3091 | STATUS_BAR_TRANSPARENT; 3092 3093 /** 3094 * @hide 3095 */ 3096 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3097 3098 /** 3099 * These are the system UI flags that can be cleared by events outside 3100 * of an application. Currently this is just the ability to tap on the 3101 * screen while hiding the navigation bar to have it return. 3102 * @hide 3103 */ 3104 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3105 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3106 | SYSTEM_UI_FLAG_FULLSCREEN; 3107 3108 /** 3109 * Flags that can impact the layout in relation to system UI. 3110 */ 3111 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3112 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3113 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3114 3115 /** @hide */ 3116 @IntDef(flag = true, 3117 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3118 @Retention(RetentionPolicy.SOURCE) 3119 public @interface FindViewFlags {} 3120 3121 /** 3122 * Find views that render the specified text. 3123 * 3124 * @see #findViewsWithText(ArrayList, CharSequence, int) 3125 */ 3126 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3127 3128 /** 3129 * Find find views that contain the specified content description. 3130 * 3131 * @see #findViewsWithText(ArrayList, CharSequence, int) 3132 */ 3133 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3134 3135 /** 3136 * Find views that contain {@link AccessibilityNodeProvider}. Such 3137 * a View is a root of virtual view hierarchy and may contain the searched 3138 * text. If this flag is set Views with providers are automatically 3139 * added and it is a responsibility of the client to call the APIs of 3140 * the provider to determine whether the virtual tree rooted at this View 3141 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3142 * representing the virtual views with this text. 3143 * 3144 * @see #findViewsWithText(ArrayList, CharSequence, int) 3145 * 3146 * @hide 3147 */ 3148 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3149 3150 /** 3151 * The undefined cursor position. 3152 * 3153 * @hide 3154 */ 3155 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3156 3157 /** 3158 * Indicates that the screen has changed state and is now off. 3159 * 3160 * @see #onScreenStateChanged(int) 3161 */ 3162 public static final int SCREEN_STATE_OFF = 0x0; 3163 3164 /** 3165 * Indicates that the screen has changed state and is now on. 3166 * 3167 * @see #onScreenStateChanged(int) 3168 */ 3169 public static final int SCREEN_STATE_ON = 0x1; 3170 3171 /** 3172 * Indicates no axis of view scrolling. 3173 */ 3174 public static final int SCROLL_AXIS_NONE = 0; 3175 3176 /** 3177 * Indicates scrolling along the horizontal axis. 3178 */ 3179 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3180 3181 /** 3182 * Indicates scrolling along the vertical axis. 3183 */ 3184 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3185 3186 /** 3187 * Controls the over-scroll mode for this view. 3188 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3189 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3190 * and {@link #OVER_SCROLL_NEVER}. 3191 */ 3192 private int mOverScrollMode; 3193 3194 /** 3195 * The parent this view is attached to. 3196 * {@hide} 3197 * 3198 * @see #getParent() 3199 */ 3200 protected ViewParent mParent; 3201 3202 /** 3203 * {@hide} 3204 */ 3205 AttachInfo mAttachInfo; 3206 3207 /** 3208 * {@hide} 3209 */ 3210 @ViewDebug.ExportedProperty(flagMapping = { 3211 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3212 name = "FORCE_LAYOUT"), 3213 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3214 name = "LAYOUT_REQUIRED"), 3215 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3216 name = "DRAWING_CACHE_INVALID", outputIf = false), 3217 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3218 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3219 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3220 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3221 }, formatToHexString = true) 3222 int mPrivateFlags; 3223 int mPrivateFlags2; 3224 int mPrivateFlags3; 3225 3226 /** 3227 * This view's request for the visibility of the status bar. 3228 * @hide 3229 */ 3230 @ViewDebug.ExportedProperty(flagMapping = { 3231 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3232 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3233 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3234 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3235 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3236 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3237 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3238 equals = SYSTEM_UI_FLAG_VISIBLE, 3239 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3240 }, formatToHexString = true) 3241 int mSystemUiVisibility; 3242 3243 /** 3244 * Reference count for transient state. 3245 * @see #setHasTransientState(boolean) 3246 */ 3247 int mTransientStateCount = 0; 3248 3249 /** 3250 * Count of how many windows this view has been attached to. 3251 */ 3252 int mWindowAttachCount; 3253 3254 /** 3255 * The layout parameters associated with this view and used by the parent 3256 * {@link android.view.ViewGroup} to determine how this view should be 3257 * laid out. 3258 * {@hide} 3259 */ 3260 protected ViewGroup.LayoutParams mLayoutParams; 3261 3262 /** 3263 * The view flags hold various views states. 3264 * {@hide} 3265 */ 3266 @ViewDebug.ExportedProperty(formatToHexString = true) 3267 int mViewFlags; 3268 3269 static class TransformationInfo { 3270 /** 3271 * The transform matrix for the View. This transform is calculated internally 3272 * based on the translation, rotation, and scale properties. 3273 * 3274 * Do *not* use this variable directly; instead call getMatrix(), which will 3275 * load the value from the View's RenderNode. 3276 */ 3277 private final Matrix mMatrix = new Matrix(); 3278 3279 /** 3280 * The inverse transform matrix for the View. This transform is calculated 3281 * internally based on the translation, rotation, and scale properties. 3282 * 3283 * Do *not* use this variable directly; instead call getInverseMatrix(), 3284 * which will load the value from the View's RenderNode. 3285 */ 3286 private Matrix mInverseMatrix; 3287 3288 /** 3289 * The opacity of the View. This is a value from 0 to 1, where 0 means 3290 * completely transparent and 1 means completely opaque. 3291 */ 3292 @ViewDebug.ExportedProperty 3293 float mAlpha = 1f; 3294 3295 /** 3296 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3297 * property only used by transitions, which is composited with the other alpha 3298 * values to calculate the final visual alpha value. 3299 */ 3300 float mTransitionAlpha = 1f; 3301 } 3302 3303 TransformationInfo mTransformationInfo; 3304 3305 /** 3306 * Current clip bounds. to which all drawing of this view are constrained. 3307 */ 3308 Rect mClipBounds = null; 3309 3310 private boolean mLastIsOpaque; 3311 3312 /** 3313 * The distance in pixels from the left edge of this view's parent 3314 * to the left edge of this view. 3315 * {@hide} 3316 */ 3317 @ViewDebug.ExportedProperty(category = "layout") 3318 protected int mLeft; 3319 /** 3320 * The distance in pixels from the left edge of this view's parent 3321 * to the right edge of this view. 3322 * {@hide} 3323 */ 3324 @ViewDebug.ExportedProperty(category = "layout") 3325 protected int mRight; 3326 /** 3327 * The distance in pixels from the top edge of this view's parent 3328 * to the top edge of this view. 3329 * {@hide} 3330 */ 3331 @ViewDebug.ExportedProperty(category = "layout") 3332 protected int mTop; 3333 /** 3334 * The distance in pixels from the top edge of this view's parent 3335 * to the bottom edge of this view. 3336 * {@hide} 3337 */ 3338 @ViewDebug.ExportedProperty(category = "layout") 3339 protected int mBottom; 3340 3341 /** 3342 * The offset, in pixels, by which the content of this view is scrolled 3343 * horizontally. 3344 * {@hide} 3345 */ 3346 @ViewDebug.ExportedProperty(category = "scrolling") 3347 protected int mScrollX; 3348 /** 3349 * The offset, in pixels, by which the content of this view is scrolled 3350 * vertically. 3351 * {@hide} 3352 */ 3353 @ViewDebug.ExportedProperty(category = "scrolling") 3354 protected int mScrollY; 3355 3356 /** 3357 * The left padding in pixels, that is the distance in pixels between the 3358 * left edge of this view and the left edge of its content. 3359 * {@hide} 3360 */ 3361 @ViewDebug.ExportedProperty(category = "padding") 3362 protected int mPaddingLeft = 0; 3363 /** 3364 * The right padding in pixels, that is the distance in pixels between the 3365 * right edge of this view and the right edge of its content. 3366 * {@hide} 3367 */ 3368 @ViewDebug.ExportedProperty(category = "padding") 3369 protected int mPaddingRight = 0; 3370 /** 3371 * The top padding in pixels, that is the distance in pixels between the 3372 * top edge of this view and the top edge of its content. 3373 * {@hide} 3374 */ 3375 @ViewDebug.ExportedProperty(category = "padding") 3376 protected int mPaddingTop; 3377 /** 3378 * The bottom padding in pixels, that is the distance in pixels between the 3379 * bottom edge of this view and the bottom edge of its content. 3380 * {@hide} 3381 */ 3382 @ViewDebug.ExportedProperty(category = "padding") 3383 protected int mPaddingBottom; 3384 3385 /** 3386 * The layout insets in pixels, that is the distance in pixels between the 3387 * visible edges of this view its bounds. 3388 */ 3389 private Insets mLayoutInsets; 3390 3391 /** 3392 * Briefly describes the view and is primarily used for accessibility support. 3393 */ 3394 private CharSequence mContentDescription; 3395 3396 /** 3397 * Specifies the id of a view for which this view serves as a label for 3398 * accessibility purposes. 3399 */ 3400 private int mLabelForId = View.NO_ID; 3401 3402 /** 3403 * Predicate for matching labeled view id with its label for 3404 * accessibility purposes. 3405 */ 3406 private MatchLabelForPredicate mMatchLabelForPredicate; 3407 3408 /** 3409 * Specifies a view before which this one is visited in accessibility traversal. 3410 */ 3411 private int mAccessibilityTraversalBeforeId = NO_ID; 3412 3413 /** 3414 * Specifies a view after which this one is visited in accessibility traversal. 3415 */ 3416 private int mAccessibilityTraversalAfterId = NO_ID; 3417 3418 /** 3419 * Predicate for matching a view by its id. 3420 */ 3421 private MatchIdPredicate mMatchIdPredicate; 3422 3423 /** 3424 * Cache the paddingRight set by the user to append to the scrollbar's size. 3425 * 3426 * @hide 3427 */ 3428 @ViewDebug.ExportedProperty(category = "padding") 3429 protected int mUserPaddingRight; 3430 3431 /** 3432 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3433 * 3434 * @hide 3435 */ 3436 @ViewDebug.ExportedProperty(category = "padding") 3437 protected int mUserPaddingBottom; 3438 3439 /** 3440 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3441 * 3442 * @hide 3443 */ 3444 @ViewDebug.ExportedProperty(category = "padding") 3445 protected int mUserPaddingLeft; 3446 3447 /** 3448 * Cache the paddingStart set by the user to append to the scrollbar's size. 3449 * 3450 */ 3451 @ViewDebug.ExportedProperty(category = "padding") 3452 int mUserPaddingStart; 3453 3454 /** 3455 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3456 * 3457 */ 3458 @ViewDebug.ExportedProperty(category = "padding") 3459 int mUserPaddingEnd; 3460 3461 /** 3462 * Cache initial left padding. 3463 * 3464 * @hide 3465 */ 3466 int mUserPaddingLeftInitial; 3467 3468 /** 3469 * Cache initial right padding. 3470 * 3471 * @hide 3472 */ 3473 int mUserPaddingRightInitial; 3474 3475 /** 3476 * Default undefined padding 3477 */ 3478 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3479 3480 /** 3481 * Cache if a left padding has been defined 3482 */ 3483 private boolean mLeftPaddingDefined = false; 3484 3485 /** 3486 * Cache if a right padding has been defined 3487 */ 3488 private boolean mRightPaddingDefined = false; 3489 3490 /** 3491 * @hide 3492 */ 3493 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3494 /** 3495 * @hide 3496 */ 3497 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3498 3499 private LongSparseLongArray mMeasureCache; 3500 3501 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3502 private Drawable mBackground; 3503 private TintInfo mBackgroundTint; 3504 3505 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3506 private ForegroundInfo mForegroundInfo; 3507 3508 private Drawable mScrollIndicatorDrawable; 3509 3510 /** 3511 * RenderNode used for backgrounds. 3512 * <p> 3513 * When non-null and valid, this is expected to contain an up-to-date copy 3514 * of the background drawable. It is cleared on temporary detach, and reset 3515 * on cleanup. 3516 */ 3517 private RenderNode mBackgroundRenderNode; 3518 3519 private int mBackgroundResource; 3520 private boolean mBackgroundSizeChanged; 3521 3522 private String mTransitionName; 3523 3524 static class TintInfo { 3525 ColorStateList mTintList; 3526 PorterDuff.Mode mTintMode; 3527 boolean mHasTintMode; 3528 boolean mHasTintList; 3529 } 3530 3531 private static class ForegroundInfo { 3532 private Drawable mDrawable; 3533 private TintInfo mTintInfo; 3534 private int mGravity = Gravity.FILL; 3535 private boolean mInsidePadding = true; 3536 private boolean mBoundsChanged = true; 3537 private final Rect mSelfBounds = new Rect(); 3538 private final Rect mOverlayBounds = new Rect(); 3539 } 3540 3541 static class ListenerInfo { 3542 /** 3543 * Listener used to dispatch focus change events. 3544 * This field should be made private, so it is hidden from the SDK. 3545 * {@hide} 3546 */ 3547 protected OnFocusChangeListener mOnFocusChangeListener; 3548 3549 /** 3550 * Listeners for layout change events. 3551 */ 3552 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3553 3554 protected OnScrollChangeListener mOnScrollChangeListener; 3555 3556 /** 3557 * Listeners for attach events. 3558 */ 3559 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3560 3561 /** 3562 * Listener used to dispatch click events. 3563 * This field should be made private, so it is hidden from the SDK. 3564 * {@hide} 3565 */ 3566 public OnClickListener mOnClickListener; 3567 3568 /** 3569 * Listener used to dispatch long click events. 3570 * This field should be made private, so it is hidden from the SDK. 3571 * {@hide} 3572 */ 3573 protected OnLongClickListener mOnLongClickListener; 3574 3575 /** 3576 * Listener used to dispatch context click events. This field should be made private, so it 3577 * is hidden from the SDK. 3578 * {@hide} 3579 */ 3580 protected OnContextClickListener mOnContextClickListener; 3581 3582 /** 3583 * Listener used to build the context menu. 3584 * This field should be made private, so it is hidden from the SDK. 3585 * {@hide} 3586 */ 3587 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3588 3589 private OnKeyListener mOnKeyListener; 3590 3591 private OnTouchListener mOnTouchListener; 3592 3593 private OnHoverListener mOnHoverListener; 3594 3595 private OnGenericMotionListener mOnGenericMotionListener; 3596 3597 private OnDragListener mOnDragListener; 3598 3599 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3600 3601 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3602 } 3603 3604 ListenerInfo mListenerInfo; 3605 3606 // Temporary values used to hold (x,y) coordinates when delegating from the 3607 // two-arg performLongClick() method to the legacy no-arg version. 3608 private float mLongClickX = Float.NaN; 3609 private float mLongClickY = Float.NaN; 3610 3611 /** 3612 * The application environment this view lives in. 3613 * This field should be made private, so it is hidden from the SDK. 3614 * {@hide} 3615 */ 3616 @ViewDebug.ExportedProperty(deepExport = true) 3617 protected Context mContext; 3618 3619 private final Resources mResources; 3620 3621 private ScrollabilityCache mScrollCache; 3622 3623 private int[] mDrawableState = null; 3624 3625 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3626 3627 /** 3628 * Animator that automatically runs based on state changes. 3629 */ 3630 private StateListAnimator mStateListAnimator; 3631 3632 /** 3633 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3634 * the user may specify which view to go to next. 3635 */ 3636 private int mNextFocusLeftId = View.NO_ID; 3637 3638 /** 3639 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3640 * the user may specify which view to go to next. 3641 */ 3642 private int mNextFocusRightId = View.NO_ID; 3643 3644 /** 3645 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3646 * the user may specify which view to go to next. 3647 */ 3648 private int mNextFocusUpId = View.NO_ID; 3649 3650 /** 3651 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3652 * the user may specify which view to go to next. 3653 */ 3654 private int mNextFocusDownId = View.NO_ID; 3655 3656 /** 3657 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3658 * the user may specify which view to go to next. 3659 */ 3660 int mNextFocusForwardId = View.NO_ID; 3661 3662 private CheckForLongPress mPendingCheckForLongPress; 3663 private CheckForTap mPendingCheckForTap = null; 3664 private PerformClick mPerformClick; 3665 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3666 3667 private UnsetPressedState mUnsetPressedState; 3668 3669 /** 3670 * Whether the long press's action has been invoked. The tap's action is invoked on the 3671 * up event while a long press is invoked as soon as the long press duration is reached, so 3672 * a long press could be performed before the tap is checked, in which case the tap's action 3673 * should not be invoked. 3674 */ 3675 private boolean mHasPerformedLongPress; 3676 3677 /** 3678 * Whether a context click button is currently pressed down. This is true when the stylus is 3679 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3680 * pressed. This is false once the button is released or if the stylus has been lifted. 3681 */ 3682 private boolean mInContextButtonPress; 3683 3684 /** 3685 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3686 * true after a stylus button press has occured, when the next up event should not be recognized 3687 * as a tap. 3688 */ 3689 private boolean mIgnoreNextUpEvent; 3690 3691 /** 3692 * The minimum height of the view. We'll try our best to have the height 3693 * of this view to at least this amount. 3694 */ 3695 @ViewDebug.ExportedProperty(category = "measurement") 3696 private int mMinHeight; 3697 3698 /** 3699 * The minimum width of the view. We'll try our best to have the width 3700 * of this view to at least this amount. 3701 */ 3702 @ViewDebug.ExportedProperty(category = "measurement") 3703 private int mMinWidth; 3704 3705 /** 3706 * The delegate to handle touch events that are physically in this view 3707 * but should be handled by another view. 3708 */ 3709 private TouchDelegate mTouchDelegate = null; 3710 3711 /** 3712 * Solid color to use as a background when creating the drawing cache. Enables 3713 * the cache to use 16 bit bitmaps instead of 32 bit. 3714 */ 3715 private int mDrawingCacheBackgroundColor = 0; 3716 3717 /** 3718 * Special tree observer used when mAttachInfo is null. 3719 */ 3720 private ViewTreeObserver mFloatingTreeObserver; 3721 3722 /** 3723 * Cache the touch slop from the context that created the view. 3724 */ 3725 private int mTouchSlop; 3726 3727 /** 3728 * Object that handles automatic animation of view properties. 3729 */ 3730 private ViewPropertyAnimator mAnimator = null; 3731 3732 /** 3733 * List of registered FrameMetricsObservers. 3734 */ 3735 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3736 3737 /** 3738 * Flag indicating that a drag can cross window boundaries. When 3739 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3740 * with this flag set, all visible applications with targetSdkVersion >= 3741 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 3742 * in the drag operation and receive the dragged content. 3743 * 3744 * <p>If this is the only flag set, then the drag recipient will only have access to text data 3745 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3746 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 3747 */ 3748 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3749 3750 /** 3751 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3752 * request read access to the content URI(s) contained in the {@link ClipData} object. 3753 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3754 */ 3755 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3756 3757 /** 3758 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3759 * request write access to the content URI(s) contained in the {@link ClipData} object. 3760 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3761 */ 3762 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3763 3764 /** 3765 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3766 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3767 * reboots until explicitly revoked with 3768 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3769 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3770 */ 3771 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3772 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3773 3774 /** 3775 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3776 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3777 * match against the original granted URI. 3778 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3779 */ 3780 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3781 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3782 3783 /** 3784 * Flag indicating that the drag shadow will be opaque. When 3785 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3786 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3787 */ 3788 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3789 3790 /** 3791 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3792 */ 3793 private float mVerticalScrollFactor; 3794 3795 /** 3796 * Position of the vertical scroll bar. 3797 */ 3798 private int mVerticalScrollbarPosition; 3799 3800 /** 3801 * Position the scroll bar at the default position as determined by the system. 3802 */ 3803 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3804 3805 /** 3806 * Position the scroll bar along the left edge. 3807 */ 3808 public static final int SCROLLBAR_POSITION_LEFT = 1; 3809 3810 /** 3811 * Position the scroll bar along the right edge. 3812 */ 3813 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3814 3815 /** 3816 * Indicates that the view does not have a layer. 3817 * 3818 * @see #getLayerType() 3819 * @see #setLayerType(int, android.graphics.Paint) 3820 * @see #LAYER_TYPE_SOFTWARE 3821 * @see #LAYER_TYPE_HARDWARE 3822 */ 3823 public static final int LAYER_TYPE_NONE = 0; 3824 3825 /** 3826 * <p>Indicates that the view has a software layer. A software layer is backed 3827 * by a bitmap and causes the view to be rendered using Android's software 3828 * rendering pipeline, even if hardware acceleration is enabled.</p> 3829 * 3830 * <p>Software layers have various usages:</p> 3831 * <p>When the application is not using hardware acceleration, a software layer 3832 * is useful to apply a specific color filter and/or blending mode and/or 3833 * translucency to a view and all its children.</p> 3834 * <p>When the application is using hardware acceleration, a software layer 3835 * is useful to render drawing primitives not supported by the hardware 3836 * accelerated pipeline. It can also be used to cache a complex view tree 3837 * into a texture and reduce the complexity of drawing operations. For instance, 3838 * when animating a complex view tree with a translation, a software layer can 3839 * be used to render the view tree only once.</p> 3840 * <p>Software layers should be avoided when the affected view tree updates 3841 * often. Every update will require to re-render the software layer, which can 3842 * potentially be slow (particularly when hardware acceleration is turned on 3843 * since the layer will have to be uploaded into a hardware texture after every 3844 * update.)</p> 3845 * 3846 * @see #getLayerType() 3847 * @see #setLayerType(int, android.graphics.Paint) 3848 * @see #LAYER_TYPE_NONE 3849 * @see #LAYER_TYPE_HARDWARE 3850 */ 3851 public static final int LAYER_TYPE_SOFTWARE = 1; 3852 3853 /** 3854 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3855 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3856 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3857 * rendering pipeline, but only if hardware acceleration is turned on for the 3858 * view hierarchy. When hardware acceleration is turned off, hardware layers 3859 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3860 * 3861 * <p>A hardware layer is useful to apply a specific color filter and/or 3862 * blending mode and/or translucency to a view and all its children.</p> 3863 * <p>A hardware layer can be used to cache a complex view tree into a 3864 * texture and reduce the complexity of drawing operations. For instance, 3865 * when animating a complex view tree with a translation, a hardware layer can 3866 * be used to render the view tree only once.</p> 3867 * <p>A hardware layer can also be used to increase the rendering quality when 3868 * rotation transformations are applied on a view. It can also be used to 3869 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3870 * 3871 * @see #getLayerType() 3872 * @see #setLayerType(int, android.graphics.Paint) 3873 * @see #LAYER_TYPE_NONE 3874 * @see #LAYER_TYPE_SOFTWARE 3875 */ 3876 public static final int LAYER_TYPE_HARDWARE = 2; 3877 3878 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3879 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3880 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3881 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3882 }) 3883 int mLayerType = LAYER_TYPE_NONE; 3884 Paint mLayerPaint; 3885 3886 /** 3887 * Set to true when drawing cache is enabled and cannot be created. 3888 * 3889 * @hide 3890 */ 3891 public boolean mCachingFailed; 3892 private Bitmap mDrawingCache; 3893 private Bitmap mUnscaledDrawingCache; 3894 3895 /** 3896 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3897 * <p> 3898 * When non-null and valid, this is expected to contain an up-to-date copy 3899 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3900 * cleanup. 3901 */ 3902 final RenderNode mRenderNode; 3903 3904 /** 3905 * Set to true when the view is sending hover accessibility events because it 3906 * is the innermost hovered view. 3907 */ 3908 private boolean mSendingHoverAccessibilityEvents; 3909 3910 /** 3911 * Delegate for injecting accessibility functionality. 3912 */ 3913 AccessibilityDelegate mAccessibilityDelegate; 3914 3915 /** 3916 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3917 * and add/remove objects to/from the overlay directly through the Overlay methods. 3918 */ 3919 ViewOverlay mOverlay; 3920 3921 /** 3922 * The currently active parent view for receiving delegated nested scrolling events. 3923 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3924 * by {@link #stopNestedScroll()} at the same point where we clear 3925 * requestDisallowInterceptTouchEvent. 3926 */ 3927 private ViewParent mNestedScrollingParent; 3928 3929 /** 3930 * Consistency verifier for debugging purposes. 3931 * @hide 3932 */ 3933 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3934 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3935 new InputEventConsistencyVerifier(this, 0) : null; 3936 3937 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3938 3939 private int[] mTempNestedScrollConsumed; 3940 3941 /** 3942 * An overlay is going to draw this View instead of being drawn as part of this 3943 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3944 * when this view is invalidated. 3945 */ 3946 GhostView mGhostView; 3947 3948 /** 3949 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3950 * @hide 3951 */ 3952 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3953 public String[] mAttributes; 3954 3955 /** 3956 * Maps a Resource id to its name. 3957 */ 3958 private static SparseArray<String> mAttributeMap; 3959 3960 /** 3961 * Queue of pending runnables. Used to postpone calls to post() until this 3962 * view is attached and has a handler. 3963 */ 3964 private HandlerActionQueue mRunQueue; 3965 3966 /** 3967 * The pointer icon when the mouse hovers on this view. The default is null. 3968 */ 3969 private PointerIcon mPointerIcon; 3970 3971 /** 3972 * @hide 3973 */ 3974 String mStartActivityRequestWho; 3975 3976 @Nullable 3977 private RoundScrollbarRenderer mRoundScrollbarRenderer; 3978 3979 /** 3980 * Simple constructor to use when creating a view from code. 3981 * 3982 * @param context The Context the view is running in, through which it can 3983 * access the current theme, resources, etc. 3984 */ 3985 public View(Context context) { 3986 mContext = context; 3987 mResources = context != null ? context.getResources() : null; 3988 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3989 // Set some flags defaults 3990 mPrivateFlags2 = 3991 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3992 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3993 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3994 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3995 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3996 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3997 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3998 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3999 mUserPaddingStart = UNDEFINED_PADDING; 4000 mUserPaddingEnd = UNDEFINED_PADDING; 4001 mRenderNode = RenderNode.create(getClass().getName(), this); 4002 4003 if (!sCompatibilityDone && context != null) { 4004 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4005 4006 // Older apps may need this compatibility hack for measurement. 4007 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4008 4009 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4010 // of whether a layout was requested on that View. 4011 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4012 4013 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4014 4015 // In M and newer, our widgets can pass a "hint" value in the size 4016 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4017 // know what the expected parent size is going to be, so e.g. list items can size 4018 // themselves at 1/3 the size of their container. It breaks older apps though, 4019 // specifically apps that use some popular open source libraries. 4020 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4021 4022 // Old versions of the platform would give different results from 4023 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4024 // modes, so we always need to run an additional EXACTLY pass. 4025 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4026 4027 // Prior to N, layout params could change without requiring a 4028 // subsequent call to setLayoutParams() and they would usually 4029 // work. Partial layout breaks this assumption. 4030 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4031 4032 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4033 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4034 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4035 4036 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4037 // in apps so we target check it to avoid breaking existing apps. 4038 sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N; 4039 4040 sCascadedDragDrop = targetSdkVersion < N; 4041 4042 sCompatibilityDone = true; 4043 } 4044 } 4045 4046 /** 4047 * Constructor that is called when inflating a view from XML. This is called 4048 * when a view is being constructed from an XML file, supplying attributes 4049 * that were specified in the XML file. This version uses a default style of 4050 * 0, so the only attribute values applied are those in the Context's Theme 4051 * and the given AttributeSet. 4052 * 4053 * <p> 4054 * The method onFinishInflate() will be called after all children have been 4055 * added. 4056 * 4057 * @param context The Context the view is running in, through which it can 4058 * access the current theme, resources, etc. 4059 * @param attrs The attributes of the XML tag that is inflating the view. 4060 * @see #View(Context, AttributeSet, int) 4061 */ 4062 public View(Context context, @Nullable AttributeSet attrs) { 4063 this(context, attrs, 0); 4064 } 4065 4066 /** 4067 * Perform inflation from XML and apply a class-specific base style from a 4068 * theme attribute. This constructor of View allows subclasses to use their 4069 * own base style when they are inflating. For example, a Button class's 4070 * constructor would call this version of the super class constructor and 4071 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4072 * allows the theme's button style to modify all of the base view attributes 4073 * (in particular its background) as well as the Button class's attributes. 4074 * 4075 * @param context The Context the view is running in, through which it can 4076 * access the current theme, resources, etc. 4077 * @param attrs The attributes of the XML tag that is inflating the view. 4078 * @param defStyleAttr An attribute in the current theme that contains a 4079 * reference to a style resource that supplies default values for 4080 * the view. Can be 0 to not look for defaults. 4081 * @see #View(Context, AttributeSet) 4082 */ 4083 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4084 this(context, attrs, defStyleAttr, 0); 4085 } 4086 4087 /** 4088 * Perform inflation from XML and apply a class-specific base style from a 4089 * theme attribute or style resource. This constructor of View allows 4090 * subclasses to use their own base style when they are inflating. 4091 * <p> 4092 * When determining the final value of a particular attribute, there are 4093 * four inputs that come into play: 4094 * <ol> 4095 * <li>Any attribute values in the given AttributeSet. 4096 * <li>The style resource specified in the AttributeSet (named "style"). 4097 * <li>The default style specified by <var>defStyleAttr</var>. 4098 * <li>The default style specified by <var>defStyleRes</var>. 4099 * <li>The base values in this theme. 4100 * </ol> 4101 * <p> 4102 * Each of these inputs is considered in-order, with the first listed taking 4103 * precedence over the following ones. In other words, if in the 4104 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4105 * , then the button's text will <em>always</em> be black, regardless of 4106 * what is specified in any of the styles. 4107 * 4108 * @param context The Context the view is running in, through which it can 4109 * access the current theme, resources, etc. 4110 * @param attrs The attributes of the XML tag that is inflating the view. 4111 * @param defStyleAttr An attribute in the current theme that contains a 4112 * reference to a style resource that supplies default values for 4113 * the view. Can be 0 to not look for defaults. 4114 * @param defStyleRes A resource identifier of a style resource that 4115 * supplies default values for the view, used only if 4116 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4117 * to not look for defaults. 4118 * @see #View(Context, AttributeSet, int) 4119 */ 4120 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4121 this(context); 4122 4123 final TypedArray a = context.obtainStyledAttributes( 4124 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4125 4126 if (mDebugViewAttributes) { 4127 saveAttributeData(attrs, a); 4128 } 4129 4130 Drawable background = null; 4131 4132 int leftPadding = -1; 4133 int topPadding = -1; 4134 int rightPadding = -1; 4135 int bottomPadding = -1; 4136 int startPadding = UNDEFINED_PADDING; 4137 int endPadding = UNDEFINED_PADDING; 4138 4139 int padding = -1; 4140 4141 int viewFlagValues = 0; 4142 int viewFlagMasks = 0; 4143 4144 boolean setScrollContainer = false; 4145 4146 int x = 0; 4147 int y = 0; 4148 4149 float tx = 0; 4150 float ty = 0; 4151 float tz = 0; 4152 float elevation = 0; 4153 float rotation = 0; 4154 float rotationX = 0; 4155 float rotationY = 0; 4156 float sx = 1f; 4157 float sy = 1f; 4158 boolean transformSet = false; 4159 4160 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4161 int overScrollMode = mOverScrollMode; 4162 boolean initializeScrollbars = false; 4163 boolean initializeScrollIndicators = false; 4164 4165 boolean startPaddingDefined = false; 4166 boolean endPaddingDefined = false; 4167 boolean leftPaddingDefined = false; 4168 boolean rightPaddingDefined = false; 4169 4170 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4171 4172 final int N = a.getIndexCount(); 4173 for (int i = 0; i < N; i++) { 4174 int attr = a.getIndex(i); 4175 switch (attr) { 4176 case com.android.internal.R.styleable.View_background: 4177 background = a.getDrawable(attr); 4178 break; 4179 case com.android.internal.R.styleable.View_padding: 4180 padding = a.getDimensionPixelSize(attr, -1); 4181 mUserPaddingLeftInitial = padding; 4182 mUserPaddingRightInitial = padding; 4183 leftPaddingDefined = true; 4184 rightPaddingDefined = true; 4185 break; 4186 case com.android.internal.R.styleable.View_paddingLeft: 4187 leftPadding = a.getDimensionPixelSize(attr, -1); 4188 mUserPaddingLeftInitial = leftPadding; 4189 leftPaddingDefined = true; 4190 break; 4191 case com.android.internal.R.styleable.View_paddingTop: 4192 topPadding = a.getDimensionPixelSize(attr, -1); 4193 break; 4194 case com.android.internal.R.styleable.View_paddingRight: 4195 rightPadding = a.getDimensionPixelSize(attr, -1); 4196 mUserPaddingRightInitial = rightPadding; 4197 rightPaddingDefined = true; 4198 break; 4199 case com.android.internal.R.styleable.View_paddingBottom: 4200 bottomPadding = a.getDimensionPixelSize(attr, -1); 4201 break; 4202 case com.android.internal.R.styleable.View_paddingStart: 4203 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4204 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4205 break; 4206 case com.android.internal.R.styleable.View_paddingEnd: 4207 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4208 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4209 break; 4210 case com.android.internal.R.styleable.View_scrollX: 4211 x = a.getDimensionPixelOffset(attr, 0); 4212 break; 4213 case com.android.internal.R.styleable.View_scrollY: 4214 y = a.getDimensionPixelOffset(attr, 0); 4215 break; 4216 case com.android.internal.R.styleable.View_alpha: 4217 setAlpha(a.getFloat(attr, 1f)); 4218 break; 4219 case com.android.internal.R.styleable.View_transformPivotX: 4220 setPivotX(a.getDimension(attr, 0)); 4221 break; 4222 case com.android.internal.R.styleable.View_transformPivotY: 4223 setPivotY(a.getDimension(attr, 0)); 4224 break; 4225 case com.android.internal.R.styleable.View_translationX: 4226 tx = a.getDimension(attr, 0); 4227 transformSet = true; 4228 break; 4229 case com.android.internal.R.styleable.View_translationY: 4230 ty = a.getDimension(attr, 0); 4231 transformSet = true; 4232 break; 4233 case com.android.internal.R.styleable.View_translationZ: 4234 tz = a.getDimension(attr, 0); 4235 transformSet = true; 4236 break; 4237 case com.android.internal.R.styleable.View_elevation: 4238 elevation = a.getDimension(attr, 0); 4239 transformSet = true; 4240 break; 4241 case com.android.internal.R.styleable.View_rotation: 4242 rotation = a.getFloat(attr, 0); 4243 transformSet = true; 4244 break; 4245 case com.android.internal.R.styleable.View_rotationX: 4246 rotationX = a.getFloat(attr, 0); 4247 transformSet = true; 4248 break; 4249 case com.android.internal.R.styleable.View_rotationY: 4250 rotationY = a.getFloat(attr, 0); 4251 transformSet = true; 4252 break; 4253 case com.android.internal.R.styleable.View_scaleX: 4254 sx = a.getFloat(attr, 1f); 4255 transformSet = true; 4256 break; 4257 case com.android.internal.R.styleable.View_scaleY: 4258 sy = a.getFloat(attr, 1f); 4259 transformSet = true; 4260 break; 4261 case com.android.internal.R.styleable.View_id: 4262 mID = a.getResourceId(attr, NO_ID); 4263 break; 4264 case com.android.internal.R.styleable.View_tag: 4265 mTag = a.getText(attr); 4266 break; 4267 case com.android.internal.R.styleable.View_fitsSystemWindows: 4268 if (a.getBoolean(attr, false)) { 4269 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4270 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4271 } 4272 break; 4273 case com.android.internal.R.styleable.View_focusable: 4274 if (a.getBoolean(attr, false)) { 4275 viewFlagValues |= FOCUSABLE; 4276 viewFlagMasks |= FOCUSABLE_MASK; 4277 } 4278 break; 4279 case com.android.internal.R.styleable.View_focusableInTouchMode: 4280 if (a.getBoolean(attr, false)) { 4281 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4282 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4283 } 4284 break; 4285 case com.android.internal.R.styleable.View_clickable: 4286 if (a.getBoolean(attr, false)) { 4287 viewFlagValues |= CLICKABLE; 4288 viewFlagMasks |= CLICKABLE; 4289 } 4290 break; 4291 case com.android.internal.R.styleable.View_longClickable: 4292 if (a.getBoolean(attr, false)) { 4293 viewFlagValues |= LONG_CLICKABLE; 4294 viewFlagMasks |= LONG_CLICKABLE; 4295 } 4296 break; 4297 case com.android.internal.R.styleable.View_contextClickable: 4298 if (a.getBoolean(attr, false)) { 4299 viewFlagValues |= CONTEXT_CLICKABLE; 4300 viewFlagMasks |= CONTEXT_CLICKABLE; 4301 } 4302 break; 4303 case com.android.internal.R.styleable.View_saveEnabled: 4304 if (!a.getBoolean(attr, true)) { 4305 viewFlagValues |= SAVE_DISABLED; 4306 viewFlagMasks |= SAVE_DISABLED_MASK; 4307 } 4308 break; 4309 case com.android.internal.R.styleable.View_duplicateParentState: 4310 if (a.getBoolean(attr, false)) { 4311 viewFlagValues |= DUPLICATE_PARENT_STATE; 4312 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4313 } 4314 break; 4315 case com.android.internal.R.styleable.View_visibility: 4316 final int visibility = a.getInt(attr, 0); 4317 if (visibility != 0) { 4318 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4319 viewFlagMasks |= VISIBILITY_MASK; 4320 } 4321 break; 4322 case com.android.internal.R.styleable.View_layoutDirection: 4323 // Clear any layout direction flags (included resolved bits) already set 4324 mPrivateFlags2 &= 4325 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4326 // Set the layout direction flags depending on the value of the attribute 4327 final int layoutDirection = a.getInt(attr, -1); 4328 final int value = (layoutDirection != -1) ? 4329 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4330 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4331 break; 4332 case com.android.internal.R.styleable.View_drawingCacheQuality: 4333 final int cacheQuality = a.getInt(attr, 0); 4334 if (cacheQuality != 0) { 4335 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4336 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4337 } 4338 break; 4339 case com.android.internal.R.styleable.View_contentDescription: 4340 setContentDescription(a.getString(attr)); 4341 break; 4342 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4343 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4344 break; 4345 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4346 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4347 break; 4348 case com.android.internal.R.styleable.View_labelFor: 4349 setLabelFor(a.getResourceId(attr, NO_ID)); 4350 break; 4351 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4352 if (!a.getBoolean(attr, true)) { 4353 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4354 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4355 } 4356 break; 4357 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4358 if (!a.getBoolean(attr, true)) { 4359 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4360 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4361 } 4362 break; 4363 case R.styleable.View_scrollbars: 4364 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4365 if (scrollbars != SCROLLBARS_NONE) { 4366 viewFlagValues |= scrollbars; 4367 viewFlagMasks |= SCROLLBARS_MASK; 4368 initializeScrollbars = true; 4369 } 4370 break; 4371 //noinspection deprecation 4372 case R.styleable.View_fadingEdge: 4373 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4374 // Ignore the attribute starting with ICS 4375 break; 4376 } 4377 // With builds < ICS, fall through and apply fading edges 4378 case R.styleable.View_requiresFadingEdge: 4379 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4380 if (fadingEdge != FADING_EDGE_NONE) { 4381 viewFlagValues |= fadingEdge; 4382 viewFlagMasks |= FADING_EDGE_MASK; 4383 initializeFadingEdgeInternal(a); 4384 } 4385 break; 4386 case R.styleable.View_scrollbarStyle: 4387 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4388 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4389 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4390 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4391 } 4392 break; 4393 case R.styleable.View_isScrollContainer: 4394 setScrollContainer = true; 4395 if (a.getBoolean(attr, false)) { 4396 setScrollContainer(true); 4397 } 4398 break; 4399 case com.android.internal.R.styleable.View_keepScreenOn: 4400 if (a.getBoolean(attr, false)) { 4401 viewFlagValues |= KEEP_SCREEN_ON; 4402 viewFlagMasks |= KEEP_SCREEN_ON; 4403 } 4404 break; 4405 case R.styleable.View_filterTouchesWhenObscured: 4406 if (a.getBoolean(attr, false)) { 4407 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4408 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4409 } 4410 break; 4411 case R.styleable.View_nextFocusLeft: 4412 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4413 break; 4414 case R.styleable.View_nextFocusRight: 4415 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4416 break; 4417 case R.styleable.View_nextFocusUp: 4418 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4419 break; 4420 case R.styleable.View_nextFocusDown: 4421 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4422 break; 4423 case R.styleable.View_nextFocusForward: 4424 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4425 break; 4426 case R.styleable.View_minWidth: 4427 mMinWidth = a.getDimensionPixelSize(attr, 0); 4428 break; 4429 case R.styleable.View_minHeight: 4430 mMinHeight = a.getDimensionPixelSize(attr, 0); 4431 break; 4432 case R.styleable.View_onClick: 4433 if (context.isRestricted()) { 4434 throw new IllegalStateException("The android:onClick attribute cannot " 4435 + "be used within a restricted context"); 4436 } 4437 4438 final String handlerName = a.getString(attr); 4439 if (handlerName != null) { 4440 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4441 } 4442 break; 4443 case R.styleable.View_overScrollMode: 4444 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4445 break; 4446 case R.styleable.View_verticalScrollbarPosition: 4447 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4448 break; 4449 case R.styleable.View_layerType: 4450 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4451 break; 4452 case R.styleable.View_textDirection: 4453 // Clear any text direction flag already set 4454 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4455 // Set the text direction flags depending on the value of the attribute 4456 final int textDirection = a.getInt(attr, -1); 4457 if (textDirection != -1) { 4458 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4459 } 4460 break; 4461 case R.styleable.View_textAlignment: 4462 // Clear any text alignment flag already set 4463 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4464 // Set the text alignment flag depending on the value of the attribute 4465 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4466 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4467 break; 4468 case R.styleable.View_importantForAccessibility: 4469 setImportantForAccessibility(a.getInt(attr, 4470 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4471 break; 4472 case R.styleable.View_accessibilityLiveRegion: 4473 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4474 break; 4475 case R.styleable.View_transitionName: 4476 setTransitionName(a.getString(attr)); 4477 break; 4478 case R.styleable.View_nestedScrollingEnabled: 4479 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4480 break; 4481 case R.styleable.View_stateListAnimator: 4482 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4483 a.getResourceId(attr, 0))); 4484 break; 4485 case R.styleable.View_backgroundTint: 4486 // This will get applied later during setBackground(). 4487 if (mBackgroundTint == null) { 4488 mBackgroundTint = new TintInfo(); 4489 } 4490 mBackgroundTint.mTintList = a.getColorStateList( 4491 R.styleable.View_backgroundTint); 4492 mBackgroundTint.mHasTintList = true; 4493 break; 4494 case R.styleable.View_backgroundTintMode: 4495 // This will get applied later during setBackground(). 4496 if (mBackgroundTint == null) { 4497 mBackgroundTint = new TintInfo(); 4498 } 4499 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4500 R.styleable.View_backgroundTintMode, -1), null); 4501 mBackgroundTint.mHasTintMode = true; 4502 break; 4503 case R.styleable.View_outlineProvider: 4504 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4505 PROVIDER_BACKGROUND)); 4506 break; 4507 case R.styleable.View_foreground: 4508 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4509 setForeground(a.getDrawable(attr)); 4510 } 4511 break; 4512 case R.styleable.View_foregroundGravity: 4513 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4514 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4515 } 4516 break; 4517 case R.styleable.View_foregroundTintMode: 4518 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4519 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4520 } 4521 break; 4522 case R.styleable.View_foregroundTint: 4523 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4524 setForegroundTintList(a.getColorStateList(attr)); 4525 } 4526 break; 4527 case R.styleable.View_foregroundInsidePadding: 4528 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4529 if (mForegroundInfo == null) { 4530 mForegroundInfo = new ForegroundInfo(); 4531 } 4532 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4533 mForegroundInfo.mInsidePadding); 4534 } 4535 break; 4536 case R.styleable.View_scrollIndicators: 4537 final int scrollIndicators = 4538 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4539 & SCROLL_INDICATORS_PFLAG3_MASK; 4540 if (scrollIndicators != 0) { 4541 mPrivateFlags3 |= scrollIndicators; 4542 initializeScrollIndicators = true; 4543 } 4544 break; 4545 case R.styleable.View_pointerIcon: 4546 final int resourceId = a.getResourceId(attr, 0); 4547 if (resourceId != 0) { 4548 setPointerIcon(PointerIcon.load( 4549 context.getResources(), resourceId)); 4550 } else { 4551 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 4552 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 4553 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 4554 } 4555 } 4556 break; 4557 case R.styleable.View_forceHasOverlappingRendering: 4558 if (a.peekValue(attr) != null) { 4559 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4560 } 4561 break; 4562 4563 } 4564 } 4565 4566 setOverScrollMode(overScrollMode); 4567 4568 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4569 // the resolved layout direction). Those cached values will be used later during padding 4570 // resolution. 4571 mUserPaddingStart = startPadding; 4572 mUserPaddingEnd = endPadding; 4573 4574 if (background != null) { 4575 setBackground(background); 4576 } 4577 4578 // setBackground above will record that padding is currently provided by the background. 4579 // If we have padding specified via xml, record that here instead and use it. 4580 mLeftPaddingDefined = leftPaddingDefined; 4581 mRightPaddingDefined = rightPaddingDefined; 4582 4583 if (padding >= 0) { 4584 leftPadding = padding; 4585 topPadding = padding; 4586 rightPadding = padding; 4587 bottomPadding = padding; 4588 mUserPaddingLeftInitial = padding; 4589 mUserPaddingRightInitial = padding; 4590 } 4591 4592 if (isRtlCompatibilityMode()) { 4593 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4594 // left / right padding are used if defined (meaning here nothing to do). If they are not 4595 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4596 // start / end and resolve them as left / right (layout direction is not taken into account). 4597 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4598 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4599 // defined. 4600 if (!mLeftPaddingDefined && startPaddingDefined) { 4601 leftPadding = startPadding; 4602 } 4603 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4604 if (!mRightPaddingDefined && endPaddingDefined) { 4605 rightPadding = endPadding; 4606 } 4607 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4608 } else { 4609 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4610 // values defined. Otherwise, left /right values are used. 4611 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4612 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4613 // defined. 4614 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4615 4616 if (mLeftPaddingDefined && !hasRelativePadding) { 4617 mUserPaddingLeftInitial = leftPadding; 4618 } 4619 if (mRightPaddingDefined && !hasRelativePadding) { 4620 mUserPaddingRightInitial = rightPadding; 4621 } 4622 } 4623 4624 internalSetPadding( 4625 mUserPaddingLeftInitial, 4626 topPadding >= 0 ? topPadding : mPaddingTop, 4627 mUserPaddingRightInitial, 4628 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4629 4630 if (viewFlagMasks != 0) { 4631 setFlags(viewFlagValues, viewFlagMasks); 4632 } 4633 4634 if (initializeScrollbars) { 4635 initializeScrollbarsInternal(a); 4636 } 4637 4638 if (initializeScrollIndicators) { 4639 initializeScrollIndicatorsInternal(); 4640 } 4641 4642 a.recycle(); 4643 4644 // Needs to be called after mViewFlags is set 4645 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4646 recomputePadding(); 4647 } 4648 4649 if (x != 0 || y != 0) { 4650 scrollTo(x, y); 4651 } 4652 4653 if (transformSet) { 4654 setTranslationX(tx); 4655 setTranslationY(ty); 4656 setTranslationZ(tz); 4657 setElevation(elevation); 4658 setRotation(rotation); 4659 setRotationX(rotationX); 4660 setRotationY(rotationY); 4661 setScaleX(sx); 4662 setScaleY(sy); 4663 } 4664 4665 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4666 setScrollContainer(true); 4667 } 4668 4669 computeOpaqueFlags(); 4670 } 4671 4672 /** 4673 * An implementation of OnClickListener that attempts to lazily load a 4674 * named click handling method from a parent or ancestor context. 4675 */ 4676 private static class DeclaredOnClickListener implements OnClickListener { 4677 private final View mHostView; 4678 private final String mMethodName; 4679 4680 private Method mResolvedMethod; 4681 private Context mResolvedContext; 4682 4683 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4684 mHostView = hostView; 4685 mMethodName = methodName; 4686 } 4687 4688 @Override 4689 public void onClick(@NonNull View v) { 4690 if (mResolvedMethod == null) { 4691 resolveMethod(mHostView.getContext(), mMethodName); 4692 } 4693 4694 try { 4695 mResolvedMethod.invoke(mResolvedContext, v); 4696 } catch (IllegalAccessException e) { 4697 throw new IllegalStateException( 4698 "Could not execute non-public method for android:onClick", e); 4699 } catch (InvocationTargetException e) { 4700 throw new IllegalStateException( 4701 "Could not execute method for android:onClick", e); 4702 } 4703 } 4704 4705 @NonNull 4706 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4707 while (context != null) { 4708 try { 4709 if (!context.isRestricted()) { 4710 final Method method = context.getClass().getMethod(mMethodName, View.class); 4711 if (method != null) { 4712 mResolvedMethod = method; 4713 mResolvedContext = context; 4714 return; 4715 } 4716 } 4717 } catch (NoSuchMethodException e) { 4718 // Failed to find method, keep searching up the hierarchy. 4719 } 4720 4721 if (context instanceof ContextWrapper) { 4722 context = ((ContextWrapper) context).getBaseContext(); 4723 } else { 4724 // Can't search up the hierarchy, null out and fail. 4725 context = null; 4726 } 4727 } 4728 4729 final int id = mHostView.getId(); 4730 final String idText = id == NO_ID ? "" : " with id '" 4731 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4732 throw new IllegalStateException("Could not find method " + mMethodName 4733 + "(View) in a parent or ancestor Context for android:onClick " 4734 + "attribute defined on view " + mHostView.getClass() + idText); 4735 } 4736 } 4737 4738 /** 4739 * Non-public constructor for use in testing 4740 */ 4741 View() { 4742 mResources = null; 4743 mRenderNode = RenderNode.create(getClass().getName(), this); 4744 } 4745 4746 private static SparseArray<String> getAttributeMap() { 4747 if (mAttributeMap == null) { 4748 mAttributeMap = new SparseArray<>(); 4749 } 4750 return mAttributeMap; 4751 } 4752 4753 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4754 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4755 final int indexCount = t.getIndexCount(); 4756 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4757 4758 int i = 0; 4759 4760 // Store raw XML attributes. 4761 for (int j = 0; j < attrsCount; ++j) { 4762 attributes[i] = attrs.getAttributeName(j); 4763 attributes[i + 1] = attrs.getAttributeValue(j); 4764 i += 2; 4765 } 4766 4767 // Store resolved styleable attributes. 4768 final Resources res = t.getResources(); 4769 final SparseArray<String> attributeMap = getAttributeMap(); 4770 for (int j = 0; j < indexCount; ++j) { 4771 final int index = t.getIndex(j); 4772 if (!t.hasValueOrEmpty(index)) { 4773 // Value is undefined. Skip it. 4774 continue; 4775 } 4776 4777 final int resourceId = t.getResourceId(index, 0); 4778 if (resourceId == 0) { 4779 // Value is not a reference. Skip it. 4780 continue; 4781 } 4782 4783 String resourceName = attributeMap.get(resourceId); 4784 if (resourceName == null) { 4785 try { 4786 resourceName = res.getResourceName(resourceId); 4787 } catch (Resources.NotFoundException e) { 4788 resourceName = "0x" + Integer.toHexString(resourceId); 4789 } 4790 attributeMap.put(resourceId, resourceName); 4791 } 4792 4793 attributes[i] = resourceName; 4794 attributes[i + 1] = t.getString(index); 4795 i += 2; 4796 } 4797 4798 // Trim to fit contents. 4799 final String[] trimmed = new String[i]; 4800 System.arraycopy(attributes, 0, trimmed, 0, i); 4801 mAttributes = trimmed; 4802 } 4803 4804 public String toString() { 4805 StringBuilder out = new StringBuilder(128); 4806 out.append(getClass().getName()); 4807 out.append('{'); 4808 out.append(Integer.toHexString(System.identityHashCode(this))); 4809 out.append(' '); 4810 switch (mViewFlags&VISIBILITY_MASK) { 4811 case VISIBLE: out.append('V'); break; 4812 case INVISIBLE: out.append('I'); break; 4813 case GONE: out.append('G'); break; 4814 default: out.append('.'); break; 4815 } 4816 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4817 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4818 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4819 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4820 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4821 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4822 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4823 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4824 out.append(' '); 4825 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4826 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4827 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4828 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4829 out.append('p'); 4830 } else { 4831 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4832 } 4833 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4834 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4835 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4836 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4837 out.append(' '); 4838 out.append(mLeft); 4839 out.append(','); 4840 out.append(mTop); 4841 out.append('-'); 4842 out.append(mRight); 4843 out.append(','); 4844 out.append(mBottom); 4845 final int id = getId(); 4846 if (id != NO_ID) { 4847 out.append(" #"); 4848 out.append(Integer.toHexString(id)); 4849 final Resources r = mResources; 4850 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4851 try { 4852 String pkgname; 4853 switch (id&0xff000000) { 4854 case 0x7f000000: 4855 pkgname="app"; 4856 break; 4857 case 0x01000000: 4858 pkgname="android"; 4859 break; 4860 default: 4861 pkgname = r.getResourcePackageName(id); 4862 break; 4863 } 4864 String typename = r.getResourceTypeName(id); 4865 String entryname = r.getResourceEntryName(id); 4866 out.append(" "); 4867 out.append(pkgname); 4868 out.append(":"); 4869 out.append(typename); 4870 out.append("/"); 4871 out.append(entryname); 4872 } catch (Resources.NotFoundException e) { 4873 } 4874 } 4875 } 4876 out.append("}"); 4877 return out.toString(); 4878 } 4879 4880 /** 4881 * <p> 4882 * Initializes the fading edges from a given set of styled attributes. This 4883 * method should be called by subclasses that need fading edges and when an 4884 * instance of these subclasses is created programmatically rather than 4885 * being inflated from XML. This method is automatically called when the XML 4886 * is inflated. 4887 * </p> 4888 * 4889 * @param a the styled attributes set to initialize the fading edges from 4890 * 4891 * @removed 4892 */ 4893 protected void initializeFadingEdge(TypedArray a) { 4894 // This method probably shouldn't have been included in the SDK to begin with. 4895 // It relies on 'a' having been initialized using an attribute filter array that is 4896 // not publicly available to the SDK. The old method has been renamed 4897 // to initializeFadingEdgeInternal and hidden for framework use only; 4898 // this one initializes using defaults to make it safe to call for apps. 4899 4900 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4901 4902 initializeFadingEdgeInternal(arr); 4903 4904 arr.recycle(); 4905 } 4906 4907 /** 4908 * <p> 4909 * Initializes the fading edges from a given set of styled attributes. This 4910 * method should be called by subclasses that need fading edges and when an 4911 * instance of these subclasses is created programmatically rather than 4912 * being inflated from XML. This method is automatically called when the XML 4913 * is inflated. 4914 * </p> 4915 * 4916 * @param a the styled attributes set to initialize the fading edges from 4917 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4918 */ 4919 protected void initializeFadingEdgeInternal(TypedArray a) { 4920 initScrollCache(); 4921 4922 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4923 R.styleable.View_fadingEdgeLength, 4924 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4925 } 4926 4927 /** 4928 * Returns the size of the vertical faded edges used to indicate that more 4929 * content in this view is visible. 4930 * 4931 * @return The size in pixels of the vertical faded edge or 0 if vertical 4932 * faded edges are not enabled for this view. 4933 * @attr ref android.R.styleable#View_fadingEdgeLength 4934 */ 4935 public int getVerticalFadingEdgeLength() { 4936 if (isVerticalFadingEdgeEnabled()) { 4937 ScrollabilityCache cache = mScrollCache; 4938 if (cache != null) { 4939 return cache.fadingEdgeLength; 4940 } 4941 } 4942 return 0; 4943 } 4944 4945 /** 4946 * Set the size of the faded edge used to indicate that more content in this 4947 * view is available. Will not change whether the fading edge is enabled; use 4948 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4949 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4950 * for the vertical or horizontal fading edges. 4951 * 4952 * @param length The size in pixels of the faded edge used to indicate that more 4953 * content in this view is visible. 4954 */ 4955 public void setFadingEdgeLength(int length) { 4956 initScrollCache(); 4957 mScrollCache.fadingEdgeLength = length; 4958 } 4959 4960 /** 4961 * Returns the size of the horizontal faded edges used to indicate that more 4962 * content in this view is visible. 4963 * 4964 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4965 * faded edges are not enabled for this view. 4966 * @attr ref android.R.styleable#View_fadingEdgeLength 4967 */ 4968 public int getHorizontalFadingEdgeLength() { 4969 if (isHorizontalFadingEdgeEnabled()) { 4970 ScrollabilityCache cache = mScrollCache; 4971 if (cache != null) { 4972 return cache.fadingEdgeLength; 4973 } 4974 } 4975 return 0; 4976 } 4977 4978 /** 4979 * Returns the width of the vertical scrollbar. 4980 * 4981 * @return The width in pixels of the vertical scrollbar or 0 if there 4982 * is no vertical scrollbar. 4983 */ 4984 public int getVerticalScrollbarWidth() { 4985 ScrollabilityCache cache = mScrollCache; 4986 if (cache != null) { 4987 ScrollBarDrawable scrollBar = cache.scrollBar; 4988 if (scrollBar != null) { 4989 int size = scrollBar.getSize(true); 4990 if (size <= 0) { 4991 size = cache.scrollBarSize; 4992 } 4993 return size; 4994 } 4995 return 0; 4996 } 4997 return 0; 4998 } 4999 5000 /** 5001 * Returns the height of the horizontal scrollbar. 5002 * 5003 * @return The height in pixels of the horizontal scrollbar or 0 if 5004 * there is no horizontal scrollbar. 5005 */ 5006 protected int getHorizontalScrollbarHeight() { 5007 ScrollabilityCache cache = mScrollCache; 5008 if (cache != null) { 5009 ScrollBarDrawable scrollBar = cache.scrollBar; 5010 if (scrollBar != null) { 5011 int size = scrollBar.getSize(false); 5012 if (size <= 0) { 5013 size = cache.scrollBarSize; 5014 } 5015 return size; 5016 } 5017 return 0; 5018 } 5019 return 0; 5020 } 5021 5022 /** 5023 * <p> 5024 * Initializes the scrollbars from a given set of styled attributes. This 5025 * method should be called by subclasses that need scrollbars and when an 5026 * instance of these subclasses is created programmatically rather than 5027 * being inflated from XML. This method is automatically called when the XML 5028 * is inflated. 5029 * </p> 5030 * 5031 * @param a the styled attributes set to initialize the scrollbars from 5032 * 5033 * @removed 5034 */ 5035 protected void initializeScrollbars(TypedArray a) { 5036 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5037 // using the View filter array which is not available to the SDK. As such, internal 5038 // framework usage now uses initializeScrollbarsInternal and we grab a default 5039 // TypedArray with the right filter instead here. 5040 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5041 5042 initializeScrollbarsInternal(arr); 5043 5044 // We ignored the method parameter. Recycle the one we actually did use. 5045 arr.recycle(); 5046 } 5047 5048 /** 5049 * <p> 5050 * Initializes the scrollbars from a given set of styled attributes. This 5051 * method should be called by subclasses that need scrollbars and when an 5052 * instance of these subclasses is created programmatically rather than 5053 * being inflated from XML. This method is automatically called when the XML 5054 * is inflated. 5055 * </p> 5056 * 5057 * @param a the styled attributes set to initialize the scrollbars from 5058 * @hide 5059 */ 5060 protected void initializeScrollbarsInternal(TypedArray a) { 5061 initScrollCache(); 5062 5063 final ScrollabilityCache scrollabilityCache = mScrollCache; 5064 5065 if (scrollabilityCache.scrollBar == null) { 5066 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5067 scrollabilityCache.scrollBar.setState(getDrawableState()); 5068 scrollabilityCache.scrollBar.setCallback(this); 5069 } 5070 5071 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5072 5073 if (!fadeScrollbars) { 5074 scrollabilityCache.state = ScrollabilityCache.ON; 5075 } 5076 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5077 5078 5079 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5080 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5081 .getScrollBarFadeDuration()); 5082 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5083 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5084 ViewConfiguration.getScrollDefaultDelay()); 5085 5086 5087 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5088 com.android.internal.R.styleable.View_scrollbarSize, 5089 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5090 5091 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5092 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5093 5094 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5095 if (thumb != null) { 5096 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5097 } 5098 5099 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5100 false); 5101 if (alwaysDraw) { 5102 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5103 } 5104 5105 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5106 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5107 5108 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5109 if (thumb != null) { 5110 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5111 } 5112 5113 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5114 false); 5115 if (alwaysDraw) { 5116 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5117 } 5118 5119 // Apply layout direction to the new Drawables if needed 5120 final int layoutDirection = getLayoutDirection(); 5121 if (track != null) { 5122 track.setLayoutDirection(layoutDirection); 5123 } 5124 if (thumb != null) { 5125 thumb.setLayoutDirection(layoutDirection); 5126 } 5127 5128 // Re-apply user/background padding so that scrollbar(s) get added 5129 resolvePadding(); 5130 } 5131 5132 private void initializeScrollIndicatorsInternal() { 5133 // Some day maybe we'll break this into top/left/start/etc. and let the 5134 // client control it. Until then, you can have any scroll indicator you 5135 // want as long as it's a 1dp foreground-colored rectangle. 5136 if (mScrollIndicatorDrawable == null) { 5137 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5138 } 5139 } 5140 5141 /** 5142 * <p> 5143 * Initalizes the scrollability cache if necessary. 5144 * </p> 5145 */ 5146 private void initScrollCache() { 5147 if (mScrollCache == null) { 5148 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5149 } 5150 } 5151 5152 private ScrollabilityCache getScrollCache() { 5153 initScrollCache(); 5154 return mScrollCache; 5155 } 5156 5157 /** 5158 * Set the position of the vertical scroll bar. Should be one of 5159 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5160 * {@link #SCROLLBAR_POSITION_RIGHT}. 5161 * 5162 * @param position Where the vertical scroll bar should be positioned. 5163 */ 5164 public void setVerticalScrollbarPosition(int position) { 5165 if (mVerticalScrollbarPosition != position) { 5166 mVerticalScrollbarPosition = position; 5167 computeOpaqueFlags(); 5168 resolvePadding(); 5169 } 5170 } 5171 5172 /** 5173 * @return The position where the vertical scroll bar will show, if applicable. 5174 * @see #setVerticalScrollbarPosition(int) 5175 */ 5176 public int getVerticalScrollbarPosition() { 5177 return mVerticalScrollbarPosition; 5178 } 5179 5180 boolean isOnScrollbar(float x, float y) { 5181 if (mScrollCache == null) { 5182 return false; 5183 } 5184 x += getScrollX(); 5185 y += getScrollY(); 5186 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5187 final Rect bounds = mScrollCache.mScrollBarBounds; 5188 getVerticalScrollBarBounds(bounds); 5189 if (bounds.contains((int)x, (int)y)) { 5190 return true; 5191 } 5192 } 5193 if (isHorizontalScrollBarEnabled()) { 5194 final Rect bounds = mScrollCache.mScrollBarBounds; 5195 getHorizontalScrollBarBounds(bounds); 5196 if (bounds.contains((int)x, (int)y)) { 5197 return true; 5198 } 5199 } 5200 return false; 5201 } 5202 5203 boolean isOnScrollbarThumb(float x, float y) { 5204 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5205 } 5206 5207 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5208 if (mScrollCache == null) { 5209 return false; 5210 } 5211 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5212 x += getScrollX(); 5213 y += getScrollY(); 5214 final Rect bounds = mScrollCache.mScrollBarBounds; 5215 getVerticalScrollBarBounds(bounds); 5216 final int range = computeVerticalScrollRange(); 5217 final int offset = computeVerticalScrollOffset(); 5218 final int extent = computeVerticalScrollExtent(); 5219 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5220 extent, range); 5221 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5222 extent, range, offset); 5223 final int thumbTop = bounds.top + thumbOffset; 5224 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5225 && y <= thumbTop + thumbLength) { 5226 return true; 5227 } 5228 } 5229 return false; 5230 } 5231 5232 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5233 if (mScrollCache == null) { 5234 return false; 5235 } 5236 if (isHorizontalScrollBarEnabled()) { 5237 x += getScrollX(); 5238 y += getScrollY(); 5239 final Rect bounds = mScrollCache.mScrollBarBounds; 5240 getHorizontalScrollBarBounds(bounds); 5241 final int range = computeHorizontalScrollRange(); 5242 final int offset = computeHorizontalScrollOffset(); 5243 final int extent = computeHorizontalScrollExtent(); 5244 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5245 extent, range); 5246 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5247 extent, range, offset); 5248 final int thumbLeft = bounds.left + thumbOffset; 5249 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5250 && y <= bounds.bottom) { 5251 return true; 5252 } 5253 } 5254 return false; 5255 } 5256 5257 boolean isDraggingScrollBar() { 5258 return mScrollCache != null 5259 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5260 } 5261 5262 /** 5263 * Sets the state of all scroll indicators. 5264 * <p> 5265 * See {@link #setScrollIndicators(int, int)} for usage information. 5266 * 5267 * @param indicators a bitmask of indicators that should be enabled, or 5268 * {@code 0} to disable all indicators 5269 * @see #setScrollIndicators(int, int) 5270 * @see #getScrollIndicators() 5271 * @attr ref android.R.styleable#View_scrollIndicators 5272 */ 5273 public void setScrollIndicators(@ScrollIndicators int indicators) { 5274 setScrollIndicators(indicators, 5275 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5276 } 5277 5278 /** 5279 * Sets the state of the scroll indicators specified by the mask. To change 5280 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5281 * <p> 5282 * When a scroll indicator is enabled, it will be displayed if the view 5283 * can scroll in the direction of the indicator. 5284 * <p> 5285 * Multiple indicator types may be enabled or disabled by passing the 5286 * logical OR of the desired types. If multiple types are specified, they 5287 * will all be set to the same enabled state. 5288 * <p> 5289 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5290 * 5291 * @param indicators the indicator direction, or the logical OR of multiple 5292 * indicator directions. One or more of: 5293 * <ul> 5294 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5295 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5296 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5297 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5298 * <li>{@link #SCROLL_INDICATOR_START}</li> 5299 * <li>{@link #SCROLL_INDICATOR_END}</li> 5300 * </ul> 5301 * @see #setScrollIndicators(int) 5302 * @see #getScrollIndicators() 5303 * @attr ref android.R.styleable#View_scrollIndicators 5304 */ 5305 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5306 // Shift and sanitize mask. 5307 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5308 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5309 5310 // Shift and mask indicators. 5311 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5312 indicators &= mask; 5313 5314 // Merge with non-masked flags. 5315 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5316 5317 if (mPrivateFlags3 != updatedFlags) { 5318 mPrivateFlags3 = updatedFlags; 5319 5320 if (indicators != 0) { 5321 initializeScrollIndicatorsInternal(); 5322 } 5323 invalidate(); 5324 } 5325 } 5326 5327 /** 5328 * Returns a bitmask representing the enabled scroll indicators. 5329 * <p> 5330 * For example, if the top and left scroll indicators are enabled and all 5331 * other indicators are disabled, the return value will be 5332 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5333 * <p> 5334 * To check whether the bottom scroll indicator is enabled, use the value 5335 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5336 * 5337 * @return a bitmask representing the enabled scroll indicators 5338 */ 5339 @ScrollIndicators 5340 public int getScrollIndicators() { 5341 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5342 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5343 } 5344 5345 ListenerInfo getListenerInfo() { 5346 if (mListenerInfo != null) { 5347 return mListenerInfo; 5348 } 5349 mListenerInfo = new ListenerInfo(); 5350 return mListenerInfo; 5351 } 5352 5353 /** 5354 * Register a callback to be invoked when the scroll X or Y positions of 5355 * this view change. 5356 * <p> 5357 * <b>Note:</b> Some views handle scrolling independently from View and may 5358 * have their own separate listeners for scroll-type events. For example, 5359 * {@link android.widget.ListView ListView} allows clients to register an 5360 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5361 * to listen for changes in list scroll position. 5362 * 5363 * @param l The listener to notify when the scroll X or Y position changes. 5364 * @see android.view.View#getScrollX() 5365 * @see android.view.View#getScrollY() 5366 */ 5367 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5368 getListenerInfo().mOnScrollChangeListener = l; 5369 } 5370 5371 /** 5372 * Register a callback to be invoked when focus of this view changed. 5373 * 5374 * @param l The callback that will run. 5375 */ 5376 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5377 getListenerInfo().mOnFocusChangeListener = l; 5378 } 5379 5380 /** 5381 * Add a listener that will be called when the bounds of the view change due to 5382 * layout processing. 5383 * 5384 * @param listener The listener that will be called when layout bounds change. 5385 */ 5386 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5387 ListenerInfo li = getListenerInfo(); 5388 if (li.mOnLayoutChangeListeners == null) { 5389 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5390 } 5391 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5392 li.mOnLayoutChangeListeners.add(listener); 5393 } 5394 } 5395 5396 /** 5397 * Remove a listener for layout changes. 5398 * 5399 * @param listener The listener for layout bounds change. 5400 */ 5401 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5402 ListenerInfo li = mListenerInfo; 5403 if (li == null || li.mOnLayoutChangeListeners == null) { 5404 return; 5405 } 5406 li.mOnLayoutChangeListeners.remove(listener); 5407 } 5408 5409 /** 5410 * Add a listener for attach state changes. 5411 * 5412 * This listener will be called whenever this view is attached or detached 5413 * from a window. Remove the listener using 5414 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5415 * 5416 * @param listener Listener to attach 5417 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5418 */ 5419 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5420 ListenerInfo li = getListenerInfo(); 5421 if (li.mOnAttachStateChangeListeners == null) { 5422 li.mOnAttachStateChangeListeners 5423 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5424 } 5425 li.mOnAttachStateChangeListeners.add(listener); 5426 } 5427 5428 /** 5429 * Remove a listener for attach state changes. The listener will receive no further 5430 * notification of window attach/detach events. 5431 * 5432 * @param listener Listener to remove 5433 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5434 */ 5435 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5436 ListenerInfo li = mListenerInfo; 5437 if (li == null || li.mOnAttachStateChangeListeners == null) { 5438 return; 5439 } 5440 li.mOnAttachStateChangeListeners.remove(listener); 5441 } 5442 5443 /** 5444 * Returns the focus-change callback registered for this view. 5445 * 5446 * @return The callback, or null if one is not registered. 5447 */ 5448 public OnFocusChangeListener getOnFocusChangeListener() { 5449 ListenerInfo li = mListenerInfo; 5450 return li != null ? li.mOnFocusChangeListener : null; 5451 } 5452 5453 /** 5454 * Register a callback to be invoked when this view is clicked. If this view is not 5455 * clickable, it becomes clickable. 5456 * 5457 * @param l The callback that will run 5458 * 5459 * @see #setClickable(boolean) 5460 */ 5461 public void setOnClickListener(@Nullable OnClickListener l) { 5462 if (!isClickable()) { 5463 setClickable(true); 5464 } 5465 getListenerInfo().mOnClickListener = l; 5466 } 5467 5468 /** 5469 * Return whether this view has an attached OnClickListener. Returns 5470 * true if there is a listener, false if there is none. 5471 */ 5472 public boolean hasOnClickListeners() { 5473 ListenerInfo li = mListenerInfo; 5474 return (li != null && li.mOnClickListener != null); 5475 } 5476 5477 /** 5478 * Register a callback to be invoked when this view is clicked and held. If this view is not 5479 * long clickable, it becomes long clickable. 5480 * 5481 * @param l The callback that will run 5482 * 5483 * @see #setLongClickable(boolean) 5484 */ 5485 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5486 if (!isLongClickable()) { 5487 setLongClickable(true); 5488 } 5489 getListenerInfo().mOnLongClickListener = l; 5490 } 5491 5492 /** 5493 * Register a callback to be invoked when this view is context clicked. If the view is not 5494 * context clickable, it becomes context clickable. 5495 * 5496 * @param l The callback that will run 5497 * @see #setContextClickable(boolean) 5498 */ 5499 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5500 if (!isContextClickable()) { 5501 setContextClickable(true); 5502 } 5503 getListenerInfo().mOnContextClickListener = l; 5504 } 5505 5506 /** 5507 * Register a callback to be invoked when the context menu for this view is 5508 * being built. If this view is not long clickable, it becomes long clickable. 5509 * 5510 * @param l The callback that will run 5511 * 5512 */ 5513 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5514 if (!isLongClickable()) { 5515 setLongClickable(true); 5516 } 5517 getListenerInfo().mOnCreateContextMenuListener = l; 5518 } 5519 5520 /** 5521 * Set an observer to collect stats for each frame rendered for this view. 5522 * 5523 * @hide 5524 */ 5525 public void addFrameMetricsListener(Window window, 5526 Window.OnFrameMetricsAvailableListener listener, 5527 Handler handler) { 5528 if (mAttachInfo != null) { 5529 if (mAttachInfo.mThreadedRenderer != null) { 5530 if (mFrameMetricsObservers == null) { 5531 mFrameMetricsObservers = new ArrayList<>(); 5532 } 5533 5534 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5535 handler.getLooper(), listener); 5536 mFrameMetricsObservers.add(fmo); 5537 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 5538 } else { 5539 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5540 } 5541 } else { 5542 if (mFrameMetricsObservers == null) { 5543 mFrameMetricsObservers = new ArrayList<>(); 5544 } 5545 5546 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5547 handler.getLooper(), listener); 5548 mFrameMetricsObservers.add(fmo); 5549 } 5550 } 5551 5552 /** 5553 * Remove observer configured to collect frame stats for this view. 5554 * 5555 * @hide 5556 */ 5557 public void removeFrameMetricsListener( 5558 Window.OnFrameMetricsAvailableListener listener) { 5559 ThreadedRenderer renderer = getThreadedRenderer(); 5560 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5561 if (fmo == null) { 5562 throw new IllegalArgumentException( 5563 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 5564 } 5565 5566 if (mFrameMetricsObservers != null) { 5567 mFrameMetricsObservers.remove(fmo); 5568 if (renderer != null) { 5569 renderer.removeFrameMetricsObserver(fmo); 5570 } 5571 } 5572 } 5573 5574 private void registerPendingFrameMetricsObservers() { 5575 if (mFrameMetricsObservers != null) { 5576 ThreadedRenderer renderer = getThreadedRenderer(); 5577 if (renderer != null) { 5578 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5579 renderer.addFrameMetricsObserver(fmo); 5580 } 5581 } else { 5582 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5583 } 5584 } 5585 } 5586 5587 private FrameMetricsObserver findFrameMetricsObserver( 5588 Window.OnFrameMetricsAvailableListener listener) { 5589 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5590 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5591 if (observer.mListener == listener) { 5592 return observer; 5593 } 5594 } 5595 5596 return null; 5597 } 5598 5599 /** 5600 * Call this view's OnClickListener, if it is defined. Performs all normal 5601 * actions associated with clicking: reporting accessibility event, playing 5602 * a sound, etc. 5603 * 5604 * @return True there was an assigned OnClickListener that was called, false 5605 * otherwise is returned. 5606 */ 5607 public boolean performClick() { 5608 final boolean result; 5609 final ListenerInfo li = mListenerInfo; 5610 if (li != null && li.mOnClickListener != null) { 5611 playSoundEffect(SoundEffectConstants.CLICK); 5612 li.mOnClickListener.onClick(this); 5613 result = true; 5614 } else { 5615 result = false; 5616 } 5617 5618 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5619 return result; 5620 } 5621 5622 /** 5623 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5624 * this only calls the listener, and does not do any associated clicking 5625 * actions like reporting an accessibility event. 5626 * 5627 * @return True there was an assigned OnClickListener that was called, false 5628 * otherwise is returned. 5629 */ 5630 public boolean callOnClick() { 5631 ListenerInfo li = mListenerInfo; 5632 if (li != null && li.mOnClickListener != null) { 5633 li.mOnClickListener.onClick(this); 5634 return true; 5635 } 5636 return false; 5637 } 5638 5639 /** 5640 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5641 * context menu if the OnLongClickListener did not consume the event. 5642 * 5643 * @return {@code true} if one of the above receivers consumed the event, 5644 * {@code false} otherwise 5645 */ 5646 public boolean performLongClick() { 5647 return performLongClickInternal(mLongClickX, mLongClickY); 5648 } 5649 5650 /** 5651 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5652 * context menu if the OnLongClickListener did not consume the event, 5653 * anchoring it to an (x,y) coordinate. 5654 * 5655 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5656 * to disable anchoring 5657 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5658 * to disable anchoring 5659 * @return {@code true} if one of the above receivers consumed the event, 5660 * {@code false} otherwise 5661 */ 5662 public boolean performLongClick(float x, float y) { 5663 mLongClickX = x; 5664 mLongClickY = y; 5665 final boolean handled = performLongClick(); 5666 mLongClickX = Float.NaN; 5667 mLongClickY = Float.NaN; 5668 return handled; 5669 } 5670 5671 /** 5672 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5673 * context menu if the OnLongClickListener did not consume the event, 5674 * optionally anchoring it to an (x,y) coordinate. 5675 * 5676 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5677 * to disable anchoring 5678 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5679 * to disable anchoring 5680 * @return {@code true} if one of the above receivers consumed the event, 5681 * {@code false} otherwise 5682 */ 5683 private boolean performLongClickInternal(float x, float y) { 5684 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5685 5686 boolean handled = false; 5687 final ListenerInfo li = mListenerInfo; 5688 if (li != null && li.mOnLongClickListener != null) { 5689 handled = li.mOnLongClickListener.onLongClick(View.this); 5690 } 5691 if (!handled) { 5692 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5693 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5694 } 5695 if (handled) { 5696 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5697 } 5698 return handled; 5699 } 5700 5701 /** 5702 * Call this view's OnContextClickListener, if it is defined. 5703 * 5704 * @param x the x coordinate of the context click 5705 * @param y the y coordinate of the context click 5706 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5707 * otherwise. 5708 */ 5709 public boolean performContextClick(float x, float y) { 5710 return performContextClick(); 5711 } 5712 5713 /** 5714 * Call this view's OnContextClickListener, if it is defined. 5715 * 5716 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5717 * otherwise. 5718 */ 5719 public boolean performContextClick() { 5720 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5721 5722 boolean handled = false; 5723 ListenerInfo li = mListenerInfo; 5724 if (li != null && li.mOnContextClickListener != null) { 5725 handled = li.mOnContextClickListener.onContextClick(View.this); 5726 } 5727 if (handled) { 5728 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5729 } 5730 return handled; 5731 } 5732 5733 /** 5734 * Performs button-related actions during a touch down event. 5735 * 5736 * @param event The event. 5737 * @return True if the down was consumed. 5738 * 5739 * @hide 5740 */ 5741 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5742 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5743 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5744 showContextMenu(event.getX(), event.getY()); 5745 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5746 return true; 5747 } 5748 return false; 5749 } 5750 5751 /** 5752 * Shows the context menu for this view. 5753 * 5754 * @return {@code true} if the context menu was shown, {@code false} 5755 * otherwise 5756 * @see #showContextMenu(float, float) 5757 */ 5758 public boolean showContextMenu() { 5759 return getParent().showContextMenuForChild(this); 5760 } 5761 5762 /** 5763 * Shows the context menu for this view anchored to the specified 5764 * view-relative coordinate. 5765 * 5766 * @param x the X coordinate in pixels relative to the view to which the 5767 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5768 * @param y the Y coordinate in pixels relative to the view to which the 5769 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5770 * @return {@code true} if the context menu was shown, {@code false} 5771 * otherwise 5772 */ 5773 public boolean showContextMenu(float x, float y) { 5774 return getParent().showContextMenuForChild(this, x, y); 5775 } 5776 5777 /** 5778 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5779 * 5780 * @param callback Callback that will control the lifecycle of the action mode 5781 * @return The new action mode if it is started, null otherwise 5782 * 5783 * @see ActionMode 5784 * @see #startActionMode(android.view.ActionMode.Callback, int) 5785 */ 5786 public ActionMode startActionMode(ActionMode.Callback callback) { 5787 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5788 } 5789 5790 /** 5791 * Start an action mode with the given type. 5792 * 5793 * @param callback Callback that will control the lifecycle of the action mode 5794 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5795 * @return The new action mode if it is started, null otherwise 5796 * 5797 * @see ActionMode 5798 */ 5799 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5800 ViewParent parent = getParent(); 5801 if (parent == null) return null; 5802 try { 5803 return parent.startActionModeForChild(this, callback, type); 5804 } catch (AbstractMethodError ame) { 5805 // Older implementations of custom views might not implement this. 5806 return parent.startActionModeForChild(this, callback); 5807 } 5808 } 5809 5810 /** 5811 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5812 * Context, creating a unique View identifier to retrieve the result. 5813 * 5814 * @param intent The Intent to be started. 5815 * @param requestCode The request code to use. 5816 * @hide 5817 */ 5818 public void startActivityForResult(Intent intent, int requestCode) { 5819 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5820 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5821 } 5822 5823 /** 5824 * If this View corresponds to the calling who, dispatches the activity result. 5825 * @param who The identifier for the targeted View to receive the result. 5826 * @param requestCode The integer request code originally supplied to 5827 * startActivityForResult(), allowing you to identify who this 5828 * result came from. 5829 * @param resultCode The integer result code returned by the child activity 5830 * through its setResult(). 5831 * @param data An Intent, which can return result data to the caller 5832 * (various data can be attached to Intent "extras"). 5833 * @return {@code true} if the activity result was dispatched. 5834 * @hide 5835 */ 5836 public boolean dispatchActivityResult( 5837 String who, int requestCode, int resultCode, Intent data) { 5838 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5839 onActivityResult(requestCode, resultCode, data); 5840 mStartActivityRequestWho = null; 5841 return true; 5842 } 5843 return false; 5844 } 5845 5846 /** 5847 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5848 * 5849 * @param requestCode The integer request code originally supplied to 5850 * startActivityForResult(), allowing you to identify who this 5851 * result came from. 5852 * @param resultCode The integer result code returned by the child activity 5853 * through its setResult(). 5854 * @param data An Intent, which can return result data to the caller 5855 * (various data can be attached to Intent "extras"). 5856 * @hide 5857 */ 5858 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5859 // Do nothing. 5860 } 5861 5862 /** 5863 * Register a callback to be invoked when a hardware key is pressed in this view. 5864 * Key presses in software input methods will generally not trigger the methods of 5865 * this listener. 5866 * @param l the key listener to attach to this view 5867 */ 5868 public void setOnKeyListener(OnKeyListener l) { 5869 getListenerInfo().mOnKeyListener = l; 5870 } 5871 5872 /** 5873 * Register a callback to be invoked when a touch event is sent to this view. 5874 * @param l the touch listener to attach to this view 5875 */ 5876 public void setOnTouchListener(OnTouchListener l) { 5877 getListenerInfo().mOnTouchListener = l; 5878 } 5879 5880 /** 5881 * Register a callback to be invoked when a generic motion event is sent to this view. 5882 * @param l the generic motion listener to attach to this view 5883 */ 5884 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5885 getListenerInfo().mOnGenericMotionListener = l; 5886 } 5887 5888 /** 5889 * Register a callback to be invoked when a hover event is sent to this view. 5890 * @param l the hover listener to attach to this view 5891 */ 5892 public void setOnHoverListener(OnHoverListener l) { 5893 getListenerInfo().mOnHoverListener = l; 5894 } 5895 5896 /** 5897 * Register a drag event listener callback object for this View. The parameter is 5898 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5899 * View, the system calls the 5900 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5901 * @param l An implementation of {@link android.view.View.OnDragListener}. 5902 */ 5903 public void setOnDragListener(OnDragListener l) { 5904 getListenerInfo().mOnDragListener = l; 5905 } 5906 5907 /** 5908 * Give this view focus. This will cause 5909 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5910 * 5911 * Note: this does not check whether this {@link View} should get focus, it just 5912 * gives it focus no matter what. It should only be called internally by framework 5913 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5914 * 5915 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5916 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5917 * focus moved when requestFocus() is called. It may not always 5918 * apply, in which case use the default View.FOCUS_DOWN. 5919 * @param previouslyFocusedRect The rectangle of the view that had focus 5920 * prior in this View's coordinate system. 5921 */ 5922 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5923 if (DBG) { 5924 System.out.println(this + " requestFocus()"); 5925 } 5926 5927 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5928 mPrivateFlags |= PFLAG_FOCUSED; 5929 5930 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5931 5932 if (mParent != null) { 5933 mParent.requestChildFocus(this, this); 5934 } 5935 5936 if (mAttachInfo != null) { 5937 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5938 } 5939 5940 onFocusChanged(true, direction, previouslyFocusedRect); 5941 refreshDrawableState(); 5942 } 5943 } 5944 5945 /** 5946 * Sets this view's preference for reveal behavior when it gains focus. 5947 * 5948 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 5949 * this view would prefer to be brought fully into view when it gains focus. 5950 * For example, a text field that a user is meant to type into. Other views such 5951 * as scrolling containers may prefer to opt-out of this behavior.</p> 5952 * 5953 * <p>The default value for views is true, though subclasses may change this 5954 * based on their preferred behavior.</p> 5955 * 5956 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 5957 * 5958 * @see #getRevealOnFocusHint() 5959 */ 5960 public final void setRevealOnFocusHint(boolean revealOnFocus) { 5961 if (revealOnFocus) { 5962 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 5963 } else { 5964 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 5965 } 5966 } 5967 5968 /** 5969 * Returns this view's preference for reveal behavior when it gains focus. 5970 * 5971 * <p>When this method returns true for a child view requesting focus, ancestor 5972 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 5973 * should make a best effort to make the newly focused child fully visible to the user. 5974 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 5975 * other properties affecting visibility to the user as part of the focus change.</p> 5976 * 5977 * @return true if this view would prefer to become fully visible when it gains focus, 5978 * false if it would prefer not to disrupt scroll positioning 5979 * 5980 * @see #setRevealOnFocusHint(boolean) 5981 */ 5982 public final boolean getRevealOnFocusHint() { 5983 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 5984 } 5985 5986 /** 5987 * Populates <code>outRect</code> with the hotspot bounds. By default, 5988 * the hotspot bounds are identical to the screen bounds. 5989 * 5990 * @param outRect rect to populate with hotspot bounds 5991 * @hide Only for internal use by views and widgets. 5992 */ 5993 public void getHotspotBounds(Rect outRect) { 5994 final Drawable background = getBackground(); 5995 if (background != null) { 5996 background.getHotspotBounds(outRect); 5997 } else { 5998 getBoundsOnScreen(outRect); 5999 } 6000 } 6001 6002 /** 6003 * Request that a rectangle of this view be visible on the screen, 6004 * scrolling if necessary just enough. 6005 * 6006 * <p>A View should call this if it maintains some notion of which part 6007 * of its content is interesting. For example, a text editing view 6008 * should call this when its cursor moves. 6009 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6010 * It should not be affected by which part of the View is currently visible or its scroll 6011 * position. 6012 * 6013 * @param rectangle The rectangle in the View's content coordinate space 6014 * @return Whether any parent scrolled. 6015 */ 6016 public boolean requestRectangleOnScreen(Rect rectangle) { 6017 return requestRectangleOnScreen(rectangle, false); 6018 } 6019 6020 /** 6021 * Request that a rectangle of this view be visible on the screen, 6022 * scrolling if necessary just enough. 6023 * 6024 * <p>A View should call this if it maintains some notion of which part 6025 * of its content is interesting. For example, a text editing view 6026 * should call this when its cursor moves. 6027 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6028 * It should not be affected by which part of the View is currently visible or its scroll 6029 * position. 6030 * <p>When <code>immediate</code> is set to true, scrolling will not be 6031 * animated. 6032 * 6033 * @param rectangle The rectangle in the View's content coordinate space 6034 * @param immediate True to forbid animated scrolling, false otherwise 6035 * @return Whether any parent scrolled. 6036 */ 6037 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 6038 if (mParent == null) { 6039 return false; 6040 } 6041 6042 View child = this; 6043 6044 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6045 position.set(rectangle); 6046 6047 ViewParent parent = mParent; 6048 boolean scrolled = false; 6049 while (parent != null) { 6050 rectangle.set((int) position.left, (int) position.top, 6051 (int) position.right, (int) position.bottom); 6052 6053 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6054 6055 if (!(parent instanceof View)) { 6056 break; 6057 } 6058 6059 // move it from child's content coordinate space to parent's content coordinate space 6060 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6061 6062 child = (View) parent; 6063 parent = child.getParent(); 6064 } 6065 6066 return scrolled; 6067 } 6068 6069 /** 6070 * Called when this view wants to give up focus. If focus is cleared 6071 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6072 * <p> 6073 * <strong>Note:</strong> When a View clears focus the framework is trying 6074 * to give focus to the first focusable View from the top. Hence, if this 6075 * View is the first from the top that can take focus, then all callbacks 6076 * related to clearing focus will be invoked after which the framework will 6077 * give focus to this view. 6078 * </p> 6079 */ 6080 public void clearFocus() { 6081 if (DBG) { 6082 System.out.println(this + " clearFocus()"); 6083 } 6084 6085 clearFocusInternal(null, true, true); 6086 } 6087 6088 /** 6089 * Clears focus from the view, optionally propagating the change up through 6090 * the parent hierarchy and requesting that the root view place new focus. 6091 * 6092 * @param propagate whether to propagate the change up through the parent 6093 * hierarchy 6094 * @param refocus when propagate is true, specifies whether to request the 6095 * root view place new focus 6096 */ 6097 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6098 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6099 mPrivateFlags &= ~PFLAG_FOCUSED; 6100 6101 if (propagate && mParent != null) { 6102 mParent.clearChildFocus(this); 6103 } 6104 6105 onFocusChanged(false, 0, null); 6106 refreshDrawableState(); 6107 6108 if (propagate && (!refocus || !rootViewRequestFocus())) { 6109 notifyGlobalFocusCleared(this); 6110 } 6111 } 6112 } 6113 6114 void notifyGlobalFocusCleared(View oldFocus) { 6115 if (oldFocus != null && mAttachInfo != null) { 6116 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6117 } 6118 } 6119 6120 boolean rootViewRequestFocus() { 6121 final View root = getRootView(); 6122 return root != null && root.requestFocus(); 6123 } 6124 6125 /** 6126 * Called internally by the view system when a new view is getting focus. 6127 * This is what clears the old focus. 6128 * <p> 6129 * <b>NOTE:</b> The parent view's focused child must be updated manually 6130 * after calling this method. Otherwise, the view hierarchy may be left in 6131 * an inconstent state. 6132 */ 6133 void unFocus(View focused) { 6134 if (DBG) { 6135 System.out.println(this + " unFocus()"); 6136 } 6137 6138 clearFocusInternal(focused, false, false); 6139 } 6140 6141 /** 6142 * Returns true if this view has focus itself, or is the ancestor of the 6143 * view that has focus. 6144 * 6145 * @return True if this view has or contains focus, false otherwise. 6146 */ 6147 @ViewDebug.ExportedProperty(category = "focus") 6148 public boolean hasFocus() { 6149 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6150 } 6151 6152 /** 6153 * Returns true if this view is focusable or if it contains a reachable View 6154 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6155 * is a View whose parents do not block descendants focus. 6156 * 6157 * Only {@link #VISIBLE} views are considered focusable. 6158 * 6159 * @return True if the view is focusable or if the view contains a focusable 6160 * View, false otherwise. 6161 * 6162 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6163 * @see ViewGroup#getTouchscreenBlocksFocus() 6164 */ 6165 public boolean hasFocusable() { 6166 if (!isFocusableInTouchMode()) { 6167 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6168 final ViewGroup g = (ViewGroup) p; 6169 if (g.shouldBlockFocusForTouchscreen()) { 6170 return false; 6171 } 6172 } 6173 } 6174 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6175 } 6176 6177 /** 6178 * Called by the view system when the focus state of this view changes. 6179 * When the focus change event is caused by directional navigation, direction 6180 * and previouslyFocusedRect provide insight into where the focus is coming from. 6181 * When overriding, be sure to call up through to the super class so that 6182 * the standard focus handling will occur. 6183 * 6184 * @param gainFocus True if the View has focus; false otherwise. 6185 * @param direction The direction focus has moved when requestFocus() 6186 * is called to give this view focus. Values are 6187 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6188 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6189 * It may not always apply, in which case use the default. 6190 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6191 * system, of the previously focused view. If applicable, this will be 6192 * passed in as finer grained information about where the focus is coming 6193 * from (in addition to direction). Will be <code>null</code> otherwise. 6194 */ 6195 @CallSuper 6196 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6197 @Nullable Rect previouslyFocusedRect) { 6198 if (gainFocus) { 6199 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6200 } else { 6201 notifyViewAccessibilityStateChangedIfNeeded( 6202 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6203 } 6204 6205 InputMethodManager imm = InputMethodManager.peekInstance(); 6206 if (!gainFocus) { 6207 if (isPressed()) { 6208 setPressed(false); 6209 } 6210 if (imm != null && mAttachInfo != null 6211 && mAttachInfo.mHasWindowFocus) { 6212 imm.focusOut(this); 6213 } 6214 onFocusLost(); 6215 } else if (imm != null && mAttachInfo != null 6216 && mAttachInfo.mHasWindowFocus) { 6217 imm.focusIn(this); 6218 } 6219 6220 invalidate(true); 6221 ListenerInfo li = mListenerInfo; 6222 if (li != null && li.mOnFocusChangeListener != null) { 6223 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6224 } 6225 6226 if (mAttachInfo != null) { 6227 mAttachInfo.mKeyDispatchState.reset(this); 6228 } 6229 } 6230 6231 /** 6232 * Sends an accessibility event of the given type. If accessibility is 6233 * not enabled this method has no effect. The default implementation calls 6234 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6235 * to populate information about the event source (this View), then calls 6236 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6237 * populate the text content of the event source including its descendants, 6238 * and last calls 6239 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6240 * on its parent to request sending of the event to interested parties. 6241 * <p> 6242 * If an {@link AccessibilityDelegate} has been specified via calling 6243 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6244 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6245 * responsible for handling this call. 6246 * </p> 6247 * 6248 * @param eventType The type of the event to send, as defined by several types from 6249 * {@link android.view.accessibility.AccessibilityEvent}, such as 6250 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6251 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6252 * 6253 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6254 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6255 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6256 * @see AccessibilityDelegate 6257 */ 6258 public void sendAccessibilityEvent(int eventType) { 6259 if (mAccessibilityDelegate != null) { 6260 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6261 } else { 6262 sendAccessibilityEventInternal(eventType); 6263 } 6264 } 6265 6266 /** 6267 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6268 * {@link AccessibilityEvent} to make an announcement which is related to some 6269 * sort of a context change for which none of the events representing UI transitions 6270 * is a good fit. For example, announcing a new page in a book. If accessibility 6271 * is not enabled this method does nothing. 6272 * 6273 * @param text The announcement text. 6274 */ 6275 public void announceForAccessibility(CharSequence text) { 6276 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6277 AccessibilityEvent event = AccessibilityEvent.obtain( 6278 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6279 onInitializeAccessibilityEvent(event); 6280 event.getText().add(text); 6281 event.setContentDescription(null); 6282 mParent.requestSendAccessibilityEvent(this, event); 6283 } 6284 } 6285 6286 /** 6287 * @see #sendAccessibilityEvent(int) 6288 * 6289 * Note: Called from the default {@link AccessibilityDelegate}. 6290 * 6291 * @hide 6292 */ 6293 public void sendAccessibilityEventInternal(int eventType) { 6294 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6295 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6296 } 6297 } 6298 6299 /** 6300 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6301 * takes as an argument an empty {@link AccessibilityEvent} and does not 6302 * perform a check whether accessibility is enabled. 6303 * <p> 6304 * If an {@link AccessibilityDelegate} has been specified via calling 6305 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6306 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6307 * is responsible for handling this call. 6308 * </p> 6309 * 6310 * @param event The event to send. 6311 * 6312 * @see #sendAccessibilityEvent(int) 6313 */ 6314 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6315 if (mAccessibilityDelegate != null) { 6316 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6317 } else { 6318 sendAccessibilityEventUncheckedInternal(event); 6319 } 6320 } 6321 6322 /** 6323 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6324 * 6325 * Note: Called from the default {@link AccessibilityDelegate}. 6326 * 6327 * @hide 6328 */ 6329 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6330 if (!isShown()) { 6331 return; 6332 } 6333 onInitializeAccessibilityEvent(event); 6334 // Only a subset of accessibility events populates text content. 6335 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6336 dispatchPopulateAccessibilityEvent(event); 6337 } 6338 // In the beginning we called #isShown(), so we know that getParent() is not null. 6339 getParent().requestSendAccessibilityEvent(this, event); 6340 } 6341 6342 /** 6343 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6344 * to its children for adding their text content to the event. Note that the 6345 * event text is populated in a separate dispatch path since we add to the 6346 * event not only the text of the source but also the text of all its descendants. 6347 * A typical implementation will call 6348 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6349 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6350 * on each child. Override this method if custom population of the event text 6351 * content is required. 6352 * <p> 6353 * If an {@link AccessibilityDelegate} has been specified via calling 6354 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6355 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6356 * is responsible for handling this call. 6357 * </p> 6358 * <p> 6359 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6360 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6361 * </p> 6362 * 6363 * @param event The event. 6364 * 6365 * @return True if the event population was completed. 6366 */ 6367 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6368 if (mAccessibilityDelegate != null) { 6369 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6370 } else { 6371 return dispatchPopulateAccessibilityEventInternal(event); 6372 } 6373 } 6374 6375 /** 6376 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6377 * 6378 * Note: Called from the default {@link AccessibilityDelegate}. 6379 * 6380 * @hide 6381 */ 6382 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6383 onPopulateAccessibilityEvent(event); 6384 return false; 6385 } 6386 6387 /** 6388 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6389 * giving a chance to this View to populate the accessibility event with its 6390 * text content. While this method is free to modify event 6391 * attributes other than text content, doing so should normally be performed in 6392 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6393 * <p> 6394 * Example: Adding formatted date string to an accessibility event in addition 6395 * to the text added by the super implementation: 6396 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6397 * super.onPopulateAccessibilityEvent(event); 6398 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6399 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6400 * mCurrentDate.getTimeInMillis(), flags); 6401 * event.getText().add(selectedDateUtterance); 6402 * }</pre> 6403 * <p> 6404 * If an {@link AccessibilityDelegate} has been specified via calling 6405 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6406 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6407 * is responsible for handling this call. 6408 * </p> 6409 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6410 * information to the event, in case the default implementation has basic information to add. 6411 * </p> 6412 * 6413 * @param event The accessibility event which to populate. 6414 * 6415 * @see #sendAccessibilityEvent(int) 6416 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6417 */ 6418 @CallSuper 6419 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6420 if (mAccessibilityDelegate != null) { 6421 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6422 } else { 6423 onPopulateAccessibilityEventInternal(event); 6424 } 6425 } 6426 6427 /** 6428 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6429 * 6430 * Note: Called from the default {@link AccessibilityDelegate}. 6431 * 6432 * @hide 6433 */ 6434 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6435 } 6436 6437 /** 6438 * Initializes an {@link AccessibilityEvent} with information about 6439 * this View which is the event source. In other words, the source of 6440 * an accessibility event is the view whose state change triggered firing 6441 * the event. 6442 * <p> 6443 * Example: Setting the password property of an event in addition 6444 * to properties set by the super implementation: 6445 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6446 * super.onInitializeAccessibilityEvent(event); 6447 * event.setPassword(true); 6448 * }</pre> 6449 * <p> 6450 * If an {@link AccessibilityDelegate} has been specified via calling 6451 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6452 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6453 * is responsible for handling this call. 6454 * </p> 6455 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6456 * information to the event, in case the default implementation has basic information to add. 6457 * </p> 6458 * @param event The event to initialize. 6459 * 6460 * @see #sendAccessibilityEvent(int) 6461 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6462 */ 6463 @CallSuper 6464 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6465 if (mAccessibilityDelegate != null) { 6466 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6467 } else { 6468 onInitializeAccessibilityEventInternal(event); 6469 } 6470 } 6471 6472 /** 6473 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6474 * 6475 * Note: Called from the default {@link AccessibilityDelegate}. 6476 * 6477 * @hide 6478 */ 6479 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6480 event.setSource(this); 6481 event.setClassName(getAccessibilityClassName()); 6482 event.setPackageName(getContext().getPackageName()); 6483 event.setEnabled(isEnabled()); 6484 event.setContentDescription(mContentDescription); 6485 6486 switch (event.getEventType()) { 6487 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6488 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6489 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6490 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6491 event.setItemCount(focusablesTempList.size()); 6492 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6493 if (mAttachInfo != null) { 6494 focusablesTempList.clear(); 6495 } 6496 } break; 6497 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6498 CharSequence text = getIterableTextForAccessibility(); 6499 if (text != null && text.length() > 0) { 6500 event.setFromIndex(getAccessibilitySelectionStart()); 6501 event.setToIndex(getAccessibilitySelectionEnd()); 6502 event.setItemCount(text.length()); 6503 } 6504 } break; 6505 } 6506 } 6507 6508 /** 6509 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6510 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6511 * This method is responsible for obtaining an accessibility node info from a 6512 * pool of reusable instances and calling 6513 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6514 * initialize the former. 6515 * <p> 6516 * Note: The client is responsible for recycling the obtained instance by calling 6517 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6518 * </p> 6519 * 6520 * @return A populated {@link AccessibilityNodeInfo}. 6521 * 6522 * @see AccessibilityNodeInfo 6523 */ 6524 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6525 if (mAccessibilityDelegate != null) { 6526 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6527 } else { 6528 return createAccessibilityNodeInfoInternal(); 6529 } 6530 } 6531 6532 /** 6533 * @see #createAccessibilityNodeInfo() 6534 * 6535 * @hide 6536 */ 6537 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6538 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6539 if (provider != null) { 6540 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6541 } else { 6542 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6543 onInitializeAccessibilityNodeInfo(info); 6544 return info; 6545 } 6546 } 6547 6548 /** 6549 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6550 * The base implementation sets: 6551 * <ul> 6552 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6553 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6554 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6555 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6556 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6557 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6558 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6559 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6560 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6561 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6562 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6563 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6564 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6565 * </ul> 6566 * <p> 6567 * Subclasses should override this method, call the super implementation, 6568 * and set additional attributes. 6569 * </p> 6570 * <p> 6571 * If an {@link AccessibilityDelegate} has been specified via calling 6572 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6573 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6574 * is responsible for handling this call. 6575 * </p> 6576 * 6577 * @param info The instance to initialize. 6578 */ 6579 @CallSuper 6580 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6581 if (mAccessibilityDelegate != null) { 6582 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6583 } else { 6584 onInitializeAccessibilityNodeInfoInternal(info); 6585 } 6586 } 6587 6588 /** 6589 * Gets the location of this view in screen coordinates. 6590 * 6591 * @param outRect The output location 6592 * @hide 6593 */ 6594 public void getBoundsOnScreen(Rect outRect) { 6595 getBoundsOnScreen(outRect, false); 6596 } 6597 6598 /** 6599 * Gets the location of this view in screen coordinates. 6600 * 6601 * @param outRect The output location 6602 * @param clipToParent Whether to clip child bounds to the parent ones. 6603 * @hide 6604 */ 6605 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6606 if (mAttachInfo == null) { 6607 return; 6608 } 6609 6610 RectF position = mAttachInfo.mTmpTransformRect; 6611 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6612 6613 if (!hasIdentityMatrix()) { 6614 getMatrix().mapRect(position); 6615 } 6616 6617 position.offset(mLeft, mTop); 6618 6619 ViewParent parent = mParent; 6620 while (parent instanceof View) { 6621 View parentView = (View) parent; 6622 6623 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6624 6625 if (clipToParent) { 6626 position.left = Math.max(position.left, 0); 6627 position.top = Math.max(position.top, 0); 6628 position.right = Math.min(position.right, parentView.getWidth()); 6629 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6630 } 6631 6632 if (!parentView.hasIdentityMatrix()) { 6633 parentView.getMatrix().mapRect(position); 6634 } 6635 6636 position.offset(parentView.mLeft, parentView.mTop); 6637 6638 parent = parentView.mParent; 6639 } 6640 6641 if (parent instanceof ViewRootImpl) { 6642 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6643 position.offset(0, -viewRootImpl.mCurScrollY); 6644 } 6645 6646 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6647 6648 outRect.set(Math.round(position.left), Math.round(position.top), 6649 Math.round(position.right), Math.round(position.bottom)); 6650 } 6651 6652 /** 6653 * Return the class name of this object to be used for accessibility purposes. 6654 * Subclasses should only override this if they are implementing something that 6655 * should be seen as a completely new class of view when used by accessibility, 6656 * unrelated to the class it is deriving from. This is used to fill in 6657 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6658 */ 6659 public CharSequence getAccessibilityClassName() { 6660 return View.class.getName(); 6661 } 6662 6663 /** 6664 * Called when assist structure is being retrieved from a view as part of 6665 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6666 * @param structure Fill in with structured view data. The default implementation 6667 * fills in all data that can be inferred from the view itself. 6668 */ 6669 public void onProvideStructure(ViewStructure structure) { 6670 final int id = mID; 6671 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6672 && (id&0x0000ffff) != 0) { 6673 String pkg, type, entry; 6674 try { 6675 final Resources res = getResources(); 6676 entry = res.getResourceEntryName(id); 6677 type = res.getResourceTypeName(id); 6678 pkg = res.getResourcePackageName(id); 6679 } catch (Resources.NotFoundException e) { 6680 entry = type = pkg = null; 6681 } 6682 structure.setId(id, pkg, type, entry); 6683 } else { 6684 structure.setId(id, null, null, null); 6685 } 6686 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6687 if (!hasIdentityMatrix()) { 6688 structure.setTransformation(getMatrix()); 6689 } 6690 structure.setElevation(getZ()); 6691 structure.setVisibility(getVisibility()); 6692 structure.setEnabled(isEnabled()); 6693 if (isClickable()) { 6694 structure.setClickable(true); 6695 } 6696 if (isFocusable()) { 6697 structure.setFocusable(true); 6698 } 6699 if (isFocused()) { 6700 structure.setFocused(true); 6701 } 6702 if (isAccessibilityFocused()) { 6703 structure.setAccessibilityFocused(true); 6704 } 6705 if (isSelected()) { 6706 structure.setSelected(true); 6707 } 6708 if (isActivated()) { 6709 structure.setActivated(true); 6710 } 6711 if (isLongClickable()) { 6712 structure.setLongClickable(true); 6713 } 6714 if (this instanceof Checkable) { 6715 structure.setCheckable(true); 6716 if (((Checkable)this).isChecked()) { 6717 structure.setChecked(true); 6718 } 6719 } 6720 if (isContextClickable()) { 6721 structure.setContextClickable(true); 6722 } 6723 structure.setClassName(getAccessibilityClassName().toString()); 6724 structure.setContentDescription(getContentDescription()); 6725 } 6726 6727 /** 6728 * Called when assist structure is being retrieved from a view as part of 6729 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6730 * generate additional virtual structure under this view. The defaullt implementation 6731 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6732 * view's virtual accessibility nodes, if any. You can override this for a more 6733 * optimal implementation providing this data. 6734 */ 6735 public void onProvideVirtualStructure(ViewStructure structure) { 6736 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6737 if (provider != null) { 6738 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6739 structure.setChildCount(1); 6740 ViewStructure root = structure.newChild(0); 6741 populateVirtualStructure(root, provider, info); 6742 info.recycle(); 6743 } 6744 } 6745 6746 private void populateVirtualStructure(ViewStructure structure, 6747 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6748 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6749 null, null, null); 6750 Rect rect = structure.getTempRect(); 6751 info.getBoundsInParent(rect); 6752 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6753 structure.setVisibility(VISIBLE); 6754 structure.setEnabled(info.isEnabled()); 6755 if (info.isClickable()) { 6756 structure.setClickable(true); 6757 } 6758 if (info.isFocusable()) { 6759 structure.setFocusable(true); 6760 } 6761 if (info.isFocused()) { 6762 structure.setFocused(true); 6763 } 6764 if (info.isAccessibilityFocused()) { 6765 structure.setAccessibilityFocused(true); 6766 } 6767 if (info.isSelected()) { 6768 structure.setSelected(true); 6769 } 6770 if (info.isLongClickable()) { 6771 structure.setLongClickable(true); 6772 } 6773 if (info.isCheckable()) { 6774 structure.setCheckable(true); 6775 if (info.isChecked()) { 6776 structure.setChecked(true); 6777 } 6778 } 6779 if (info.isContextClickable()) { 6780 structure.setContextClickable(true); 6781 } 6782 CharSequence cname = info.getClassName(); 6783 structure.setClassName(cname != null ? cname.toString() : null); 6784 structure.setContentDescription(info.getContentDescription()); 6785 if (info.getText() != null || info.getError() != null) { 6786 structure.setText(info.getText(), info.getTextSelectionStart(), 6787 info.getTextSelectionEnd()); 6788 } 6789 final int NCHILDREN = info.getChildCount(); 6790 if (NCHILDREN > 0) { 6791 structure.setChildCount(NCHILDREN); 6792 for (int i=0; i<NCHILDREN; i++) { 6793 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6794 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6795 ViewStructure child = structure.newChild(i); 6796 populateVirtualStructure(child, provider, cinfo); 6797 cinfo.recycle(); 6798 } 6799 } 6800 } 6801 6802 /** 6803 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6804 * implementation calls {@link #onProvideStructure} and 6805 * {@link #onProvideVirtualStructure}. 6806 */ 6807 public void dispatchProvideStructure(ViewStructure structure) { 6808 if (!isAssistBlocked()) { 6809 onProvideStructure(structure); 6810 onProvideVirtualStructure(structure); 6811 } else { 6812 structure.setClassName(getAccessibilityClassName().toString()); 6813 structure.setAssistBlocked(true); 6814 } 6815 } 6816 6817 /** 6818 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6819 * 6820 * Note: Called from the default {@link AccessibilityDelegate}. 6821 * 6822 * @hide 6823 */ 6824 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6825 if (mAttachInfo == null) { 6826 return; 6827 } 6828 6829 Rect bounds = mAttachInfo.mTmpInvalRect; 6830 6831 getDrawingRect(bounds); 6832 info.setBoundsInParent(bounds); 6833 6834 getBoundsOnScreen(bounds, true); 6835 info.setBoundsInScreen(bounds); 6836 6837 ViewParent parent = getParentForAccessibility(); 6838 if (parent instanceof View) { 6839 info.setParent((View) parent); 6840 } 6841 6842 if (mID != View.NO_ID) { 6843 View rootView = getRootView(); 6844 if (rootView == null) { 6845 rootView = this; 6846 } 6847 6848 View label = rootView.findLabelForView(this, mID); 6849 if (label != null) { 6850 info.setLabeledBy(label); 6851 } 6852 6853 if ((mAttachInfo.mAccessibilityFetchFlags 6854 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6855 && Resources.resourceHasPackage(mID)) { 6856 try { 6857 String viewId = getResources().getResourceName(mID); 6858 info.setViewIdResourceName(viewId); 6859 } catch (Resources.NotFoundException nfe) { 6860 /* ignore */ 6861 } 6862 } 6863 } 6864 6865 if (mLabelForId != View.NO_ID) { 6866 View rootView = getRootView(); 6867 if (rootView == null) { 6868 rootView = this; 6869 } 6870 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6871 if (labeled != null) { 6872 info.setLabelFor(labeled); 6873 } 6874 } 6875 6876 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6877 View rootView = getRootView(); 6878 if (rootView == null) { 6879 rootView = this; 6880 } 6881 View next = rootView.findViewInsideOutShouldExist(this, 6882 mAccessibilityTraversalBeforeId); 6883 if (next != null && next.includeForAccessibility()) { 6884 info.setTraversalBefore(next); 6885 } 6886 } 6887 6888 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6889 View rootView = getRootView(); 6890 if (rootView == null) { 6891 rootView = this; 6892 } 6893 View next = rootView.findViewInsideOutShouldExist(this, 6894 mAccessibilityTraversalAfterId); 6895 if (next != null && next.includeForAccessibility()) { 6896 info.setTraversalAfter(next); 6897 } 6898 } 6899 6900 info.setVisibleToUser(isVisibleToUser()); 6901 6902 info.setImportantForAccessibility(isImportantForAccessibility()); 6903 info.setPackageName(mContext.getPackageName()); 6904 info.setClassName(getAccessibilityClassName()); 6905 info.setContentDescription(getContentDescription()); 6906 6907 info.setEnabled(isEnabled()); 6908 info.setClickable(isClickable()); 6909 info.setFocusable(isFocusable()); 6910 info.setFocused(isFocused()); 6911 info.setAccessibilityFocused(isAccessibilityFocused()); 6912 info.setSelected(isSelected()); 6913 info.setLongClickable(isLongClickable()); 6914 info.setContextClickable(isContextClickable()); 6915 info.setLiveRegion(getAccessibilityLiveRegion()); 6916 6917 // TODO: These make sense only if we are in an AdapterView but all 6918 // views can be selected. Maybe from accessibility perspective 6919 // we should report as selectable view in an AdapterView. 6920 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6921 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6922 6923 if (isFocusable()) { 6924 if (isFocused()) { 6925 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6926 } else { 6927 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6928 } 6929 } 6930 6931 if (!isAccessibilityFocused()) { 6932 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6933 } else { 6934 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6935 } 6936 6937 if (isClickable() && isEnabled()) { 6938 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6939 } 6940 6941 if (isLongClickable() && isEnabled()) { 6942 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6943 } 6944 6945 if (isContextClickable() && isEnabled()) { 6946 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6947 } 6948 6949 CharSequence text = getIterableTextForAccessibility(); 6950 if (text != null && text.length() > 0) { 6951 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6952 6953 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6954 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6955 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6956 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6957 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6958 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6959 } 6960 6961 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6962 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6963 } 6964 6965 /** 6966 * Determine the order in which this view will be drawn relative to its siblings for a11y 6967 * 6968 * @param info The info whose drawing order should be populated 6969 */ 6970 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6971 /* 6972 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6973 * drawing order may not be well-defined, and some Views with custom drawing order may 6974 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6975 */ 6976 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6977 info.setDrawingOrder(0); 6978 return; 6979 } 6980 int drawingOrderInParent = 1; 6981 // Iterate up the hierarchy if parents are not important for a11y 6982 View viewAtDrawingLevel = this; 6983 final ViewParent parent = getParentForAccessibility(); 6984 while (viewAtDrawingLevel != parent) { 6985 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6986 if (!(currentParent instanceof ViewGroup)) { 6987 // Should only happen for the Decor 6988 drawingOrderInParent = 0; 6989 break; 6990 } else { 6991 final ViewGroup parentGroup = (ViewGroup) currentParent; 6992 final int childCount = parentGroup.getChildCount(); 6993 if (childCount > 1) { 6994 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6995 if (preorderedList != null) { 6996 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6997 for (int i = 0; i < childDrawIndex; i++) { 6998 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6999 } 7000 } else { 7001 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 7002 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 7003 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 7004 .getChildDrawingOrder(childCount, childIndex) : childIndex; 7005 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 7006 if (childDrawIndex != 0) { 7007 for (int i = 0; i < numChildrenToIterate; i++) { 7008 final int otherDrawIndex = (customOrder ? 7009 parentGroup.getChildDrawingOrder(childCount, i) : i); 7010 if (otherDrawIndex < childDrawIndex) { 7011 drawingOrderInParent += 7012 numViewsForAccessibility(parentGroup.getChildAt(i)); 7013 } 7014 } 7015 } 7016 } 7017 } 7018 } 7019 viewAtDrawingLevel = (View) currentParent; 7020 } 7021 info.setDrawingOrder(drawingOrderInParent); 7022 } 7023 7024 private static int numViewsForAccessibility(View view) { 7025 if (view != null) { 7026 if (view.includeForAccessibility()) { 7027 return 1; 7028 } else if (view instanceof ViewGroup) { 7029 return ((ViewGroup) view).getNumChildrenForAccessibility(); 7030 } 7031 } 7032 return 0; 7033 } 7034 7035 private View findLabelForView(View view, int labeledId) { 7036 if (mMatchLabelForPredicate == null) { 7037 mMatchLabelForPredicate = new MatchLabelForPredicate(); 7038 } 7039 mMatchLabelForPredicate.mLabeledId = labeledId; 7040 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 7041 } 7042 7043 /** 7044 * Computes whether this view is visible to the user. Such a view is 7045 * attached, visible, all its predecessors are visible, it is not clipped 7046 * entirely by its predecessors, and has an alpha greater than zero. 7047 * 7048 * @return Whether the view is visible on the screen. 7049 * 7050 * @hide 7051 */ 7052 protected boolean isVisibleToUser() { 7053 return isVisibleToUser(null); 7054 } 7055 7056 /** 7057 * Computes whether the given portion of this view is visible to the user. 7058 * Such a view is attached, visible, all its predecessors are visible, 7059 * has an alpha greater than zero, and the specified portion is not 7060 * clipped entirely by its predecessors. 7061 * 7062 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7063 * <code>null</code>, and the entire view will be tested in this case. 7064 * When <code>true</code> is returned by the function, the actual visible 7065 * region will be stored in this parameter; that is, if boundInView is fully 7066 * contained within the view, no modification will be made, otherwise regions 7067 * outside of the visible area of the view will be clipped. 7068 * 7069 * @return Whether the specified portion of the view is visible on the screen. 7070 * 7071 * @hide 7072 */ 7073 protected boolean isVisibleToUser(Rect boundInView) { 7074 if (mAttachInfo != null) { 7075 // Attached to invisible window means this view is not visible. 7076 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7077 return false; 7078 } 7079 // An invisible predecessor or one with alpha zero means 7080 // that this view is not visible to the user. 7081 Object current = this; 7082 while (current instanceof View) { 7083 View view = (View) current; 7084 // We have attach info so this view is attached and there is no 7085 // need to check whether we reach to ViewRootImpl on the way up. 7086 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7087 view.getVisibility() != VISIBLE) { 7088 return false; 7089 } 7090 current = view.mParent; 7091 } 7092 // Check if the view is entirely covered by its predecessors. 7093 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7094 Point offset = mAttachInfo.mPoint; 7095 if (!getGlobalVisibleRect(visibleRect, offset)) { 7096 return false; 7097 } 7098 // Check if the visible portion intersects the rectangle of interest. 7099 if (boundInView != null) { 7100 visibleRect.offset(-offset.x, -offset.y); 7101 return boundInView.intersect(visibleRect); 7102 } 7103 return true; 7104 } 7105 return false; 7106 } 7107 7108 /** 7109 * Returns the delegate for implementing accessibility support via 7110 * composition. For more details see {@link AccessibilityDelegate}. 7111 * 7112 * @return The delegate, or null if none set. 7113 * 7114 * @hide 7115 */ 7116 public AccessibilityDelegate getAccessibilityDelegate() { 7117 return mAccessibilityDelegate; 7118 } 7119 7120 /** 7121 * Sets a delegate for implementing accessibility support via composition 7122 * (as opposed to inheritance). For more details, see 7123 * {@link AccessibilityDelegate}. 7124 * <p> 7125 * <strong>Note:</strong> On platform versions prior to 7126 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7127 * views in the {@code android.widget.*} package are called <i>before</i> 7128 * host methods. This prevents certain properties such as class name from 7129 * being modified by overriding 7130 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7131 * as any changes will be overwritten by the host class. 7132 * <p> 7133 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7134 * methods are called <i>after</i> host methods, which all properties to be 7135 * modified without being overwritten by the host class. 7136 * 7137 * @param delegate the object to which accessibility method calls should be 7138 * delegated 7139 * @see AccessibilityDelegate 7140 */ 7141 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7142 mAccessibilityDelegate = delegate; 7143 } 7144 7145 /** 7146 * Gets the provider for managing a virtual view hierarchy rooted at this View 7147 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7148 * that explore the window content. 7149 * <p> 7150 * If this method returns an instance, this instance is responsible for managing 7151 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7152 * View including the one representing the View itself. Similarly the returned 7153 * instance is responsible for performing accessibility actions on any virtual 7154 * view or the root view itself. 7155 * </p> 7156 * <p> 7157 * If an {@link AccessibilityDelegate} has been specified via calling 7158 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7159 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7160 * is responsible for handling this call. 7161 * </p> 7162 * 7163 * @return The provider. 7164 * 7165 * @see AccessibilityNodeProvider 7166 */ 7167 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7168 if (mAccessibilityDelegate != null) { 7169 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7170 } else { 7171 return null; 7172 } 7173 } 7174 7175 /** 7176 * Gets the unique identifier of this view on the screen for accessibility purposes. 7177 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7178 * 7179 * @return The view accessibility id. 7180 * 7181 * @hide 7182 */ 7183 public int getAccessibilityViewId() { 7184 if (mAccessibilityViewId == NO_ID) { 7185 mAccessibilityViewId = sNextAccessibilityViewId++; 7186 } 7187 return mAccessibilityViewId; 7188 } 7189 7190 /** 7191 * Gets the unique identifier of the window in which this View reseides. 7192 * 7193 * @return The window accessibility id. 7194 * 7195 * @hide 7196 */ 7197 public int getAccessibilityWindowId() { 7198 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7199 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7200 } 7201 7202 /** 7203 * Returns the {@link View}'s content description. 7204 * <p> 7205 * <strong>Note:</strong> Do not override this method, as it will have no 7206 * effect on the content description presented to accessibility services. 7207 * You must call {@link #setContentDescription(CharSequence)} to modify the 7208 * content description. 7209 * 7210 * @return the content description 7211 * @see #setContentDescription(CharSequence) 7212 * @attr ref android.R.styleable#View_contentDescription 7213 */ 7214 @ViewDebug.ExportedProperty(category = "accessibility") 7215 public CharSequence getContentDescription() { 7216 return mContentDescription; 7217 } 7218 7219 /** 7220 * Sets the {@link View}'s content description. 7221 * <p> 7222 * A content description briefly describes the view and is primarily used 7223 * for accessibility support to determine how a view should be presented to 7224 * the user. In the case of a view with no textual representation, such as 7225 * {@link android.widget.ImageButton}, a useful content description 7226 * explains what the view does. For example, an image button with a phone 7227 * icon that is used to place a call may use "Call" as its content 7228 * description. An image of a floppy disk that is used to save a file may 7229 * use "Save". 7230 * 7231 * @param contentDescription The content description. 7232 * @see #getContentDescription() 7233 * @attr ref android.R.styleable#View_contentDescription 7234 */ 7235 @RemotableViewMethod 7236 public void setContentDescription(CharSequence contentDescription) { 7237 if (mContentDescription == null) { 7238 if (contentDescription == null) { 7239 return; 7240 } 7241 } else if (mContentDescription.equals(contentDescription)) { 7242 return; 7243 } 7244 mContentDescription = contentDescription; 7245 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7246 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7247 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7248 notifySubtreeAccessibilityStateChangedIfNeeded(); 7249 } else { 7250 notifyViewAccessibilityStateChangedIfNeeded( 7251 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7252 } 7253 } 7254 7255 /** 7256 * Sets the id of a view before which this one is visited in accessibility traversal. 7257 * A screen-reader must visit the content of this view before the content of the one 7258 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7259 * will traverse the entire content of B before traversing the entire content of A, 7260 * regardles of what traversal strategy it is using. 7261 * <p> 7262 * Views that do not have specified before/after relationships are traversed in order 7263 * determined by the screen-reader. 7264 * </p> 7265 * <p> 7266 * Setting that this view is before a view that is not important for accessibility 7267 * or if this view is not important for accessibility will have no effect as the 7268 * screen-reader is not aware of unimportant views. 7269 * </p> 7270 * 7271 * @param beforeId The id of a view this one precedes in accessibility traversal. 7272 * 7273 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7274 * 7275 * @see #setImportantForAccessibility(int) 7276 */ 7277 @RemotableViewMethod 7278 public void setAccessibilityTraversalBefore(int beforeId) { 7279 if (mAccessibilityTraversalBeforeId == beforeId) { 7280 return; 7281 } 7282 mAccessibilityTraversalBeforeId = beforeId; 7283 notifyViewAccessibilityStateChangedIfNeeded( 7284 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7285 } 7286 7287 /** 7288 * Gets the id of a view before which this one is visited in accessibility traversal. 7289 * 7290 * @return The id of a view this one precedes in accessibility traversal if 7291 * specified, otherwise {@link #NO_ID}. 7292 * 7293 * @see #setAccessibilityTraversalBefore(int) 7294 */ 7295 public int getAccessibilityTraversalBefore() { 7296 return mAccessibilityTraversalBeforeId; 7297 } 7298 7299 /** 7300 * Sets the id of a view after which this one is visited in accessibility traversal. 7301 * A screen-reader must visit the content of the other view before the content of this 7302 * one. For example, if view B is set to be after view A, then a screen-reader 7303 * will traverse the entire content of A before traversing the entire content of B, 7304 * regardles of what traversal strategy it is using. 7305 * <p> 7306 * Views that do not have specified before/after relationships are traversed in order 7307 * determined by the screen-reader. 7308 * </p> 7309 * <p> 7310 * Setting that this view is after a view that is not important for accessibility 7311 * or if this view is not important for accessibility will have no effect as the 7312 * screen-reader is not aware of unimportant views. 7313 * </p> 7314 * 7315 * @param afterId The id of a view this one succedees in accessibility traversal. 7316 * 7317 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7318 * 7319 * @see #setImportantForAccessibility(int) 7320 */ 7321 @RemotableViewMethod 7322 public void setAccessibilityTraversalAfter(int afterId) { 7323 if (mAccessibilityTraversalAfterId == afterId) { 7324 return; 7325 } 7326 mAccessibilityTraversalAfterId = afterId; 7327 notifyViewAccessibilityStateChangedIfNeeded( 7328 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7329 } 7330 7331 /** 7332 * Gets the id of a view after which this one is visited in accessibility traversal. 7333 * 7334 * @return The id of a view this one succeedes in accessibility traversal if 7335 * specified, otherwise {@link #NO_ID}. 7336 * 7337 * @see #setAccessibilityTraversalAfter(int) 7338 */ 7339 public int getAccessibilityTraversalAfter() { 7340 return mAccessibilityTraversalAfterId; 7341 } 7342 7343 /** 7344 * Gets the id of a view for which this view serves as a label for 7345 * accessibility purposes. 7346 * 7347 * @return The labeled view id. 7348 */ 7349 @ViewDebug.ExportedProperty(category = "accessibility") 7350 public int getLabelFor() { 7351 return mLabelForId; 7352 } 7353 7354 /** 7355 * Sets the id of a view for which this view serves as a label for 7356 * accessibility purposes. 7357 * 7358 * @param id The labeled view id. 7359 */ 7360 @RemotableViewMethod 7361 public void setLabelFor(@IdRes int id) { 7362 if (mLabelForId == id) { 7363 return; 7364 } 7365 mLabelForId = id; 7366 if (mLabelForId != View.NO_ID 7367 && mID == View.NO_ID) { 7368 mID = generateViewId(); 7369 } 7370 notifyViewAccessibilityStateChangedIfNeeded( 7371 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7372 } 7373 7374 /** 7375 * Invoked whenever this view loses focus, either by losing window focus or by losing 7376 * focus within its window. This method can be used to clear any state tied to the 7377 * focus. For instance, if a button is held pressed with the trackball and the window 7378 * loses focus, this method can be used to cancel the press. 7379 * 7380 * Subclasses of View overriding this method should always call super.onFocusLost(). 7381 * 7382 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7383 * @see #onWindowFocusChanged(boolean) 7384 * 7385 * @hide pending API council approval 7386 */ 7387 @CallSuper 7388 protected void onFocusLost() { 7389 resetPressedState(); 7390 } 7391 7392 private void resetPressedState() { 7393 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7394 return; 7395 } 7396 7397 if (isPressed()) { 7398 setPressed(false); 7399 7400 if (!mHasPerformedLongPress) { 7401 removeLongPressCallback(); 7402 } 7403 } 7404 } 7405 7406 /** 7407 * Returns true if this view has focus 7408 * 7409 * @return True if this view has focus, false otherwise. 7410 */ 7411 @ViewDebug.ExportedProperty(category = "focus") 7412 public boolean isFocused() { 7413 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7414 } 7415 7416 /** 7417 * Find the view in the hierarchy rooted at this view that currently has 7418 * focus. 7419 * 7420 * @return The view that currently has focus, or null if no focused view can 7421 * be found. 7422 */ 7423 public View findFocus() { 7424 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7425 } 7426 7427 /** 7428 * Indicates whether this view is one of the set of scrollable containers in 7429 * its window. 7430 * 7431 * @return whether this view is one of the set of scrollable containers in 7432 * its window 7433 * 7434 * @attr ref android.R.styleable#View_isScrollContainer 7435 */ 7436 public boolean isScrollContainer() { 7437 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7438 } 7439 7440 /** 7441 * Change whether this view is one of the set of scrollable containers in 7442 * its window. This will be used to determine whether the window can 7443 * resize or must pan when a soft input area is open -- scrollable 7444 * containers allow the window to use resize mode since the container 7445 * will appropriately shrink. 7446 * 7447 * @attr ref android.R.styleable#View_isScrollContainer 7448 */ 7449 public void setScrollContainer(boolean isScrollContainer) { 7450 if (isScrollContainer) { 7451 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7452 mAttachInfo.mScrollContainers.add(this); 7453 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7454 } 7455 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7456 } else { 7457 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7458 mAttachInfo.mScrollContainers.remove(this); 7459 } 7460 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7461 } 7462 } 7463 7464 /** 7465 * Returns the quality of the drawing cache. 7466 * 7467 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7468 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7469 * 7470 * @see #setDrawingCacheQuality(int) 7471 * @see #setDrawingCacheEnabled(boolean) 7472 * @see #isDrawingCacheEnabled() 7473 * 7474 * @attr ref android.R.styleable#View_drawingCacheQuality 7475 */ 7476 @DrawingCacheQuality 7477 public int getDrawingCacheQuality() { 7478 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7479 } 7480 7481 /** 7482 * Set the drawing cache quality of this view. This value is used only when the 7483 * drawing cache is enabled 7484 * 7485 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7486 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7487 * 7488 * @see #getDrawingCacheQuality() 7489 * @see #setDrawingCacheEnabled(boolean) 7490 * @see #isDrawingCacheEnabled() 7491 * 7492 * @attr ref android.R.styleable#View_drawingCacheQuality 7493 */ 7494 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7495 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7496 } 7497 7498 /** 7499 * Returns whether the screen should remain on, corresponding to the current 7500 * value of {@link #KEEP_SCREEN_ON}. 7501 * 7502 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7503 * 7504 * @see #setKeepScreenOn(boolean) 7505 * 7506 * @attr ref android.R.styleable#View_keepScreenOn 7507 */ 7508 public boolean getKeepScreenOn() { 7509 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7510 } 7511 7512 /** 7513 * Controls whether the screen should remain on, modifying the 7514 * value of {@link #KEEP_SCREEN_ON}. 7515 * 7516 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7517 * 7518 * @see #getKeepScreenOn() 7519 * 7520 * @attr ref android.R.styleable#View_keepScreenOn 7521 */ 7522 public void setKeepScreenOn(boolean keepScreenOn) { 7523 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7524 } 7525 7526 /** 7527 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7528 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7529 * 7530 * @attr ref android.R.styleable#View_nextFocusLeft 7531 */ 7532 public int getNextFocusLeftId() { 7533 return mNextFocusLeftId; 7534 } 7535 7536 /** 7537 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7538 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7539 * decide automatically. 7540 * 7541 * @attr ref android.R.styleable#View_nextFocusLeft 7542 */ 7543 public void setNextFocusLeftId(int nextFocusLeftId) { 7544 mNextFocusLeftId = nextFocusLeftId; 7545 } 7546 7547 /** 7548 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7549 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7550 * 7551 * @attr ref android.R.styleable#View_nextFocusRight 7552 */ 7553 public int getNextFocusRightId() { 7554 return mNextFocusRightId; 7555 } 7556 7557 /** 7558 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7559 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7560 * decide automatically. 7561 * 7562 * @attr ref android.R.styleable#View_nextFocusRight 7563 */ 7564 public void setNextFocusRightId(int nextFocusRightId) { 7565 mNextFocusRightId = nextFocusRightId; 7566 } 7567 7568 /** 7569 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7570 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7571 * 7572 * @attr ref android.R.styleable#View_nextFocusUp 7573 */ 7574 public int getNextFocusUpId() { 7575 return mNextFocusUpId; 7576 } 7577 7578 /** 7579 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7580 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7581 * decide automatically. 7582 * 7583 * @attr ref android.R.styleable#View_nextFocusUp 7584 */ 7585 public void setNextFocusUpId(int nextFocusUpId) { 7586 mNextFocusUpId = nextFocusUpId; 7587 } 7588 7589 /** 7590 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7591 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7592 * 7593 * @attr ref android.R.styleable#View_nextFocusDown 7594 */ 7595 public int getNextFocusDownId() { 7596 return mNextFocusDownId; 7597 } 7598 7599 /** 7600 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7601 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7602 * decide automatically. 7603 * 7604 * @attr ref android.R.styleable#View_nextFocusDown 7605 */ 7606 public void setNextFocusDownId(int nextFocusDownId) { 7607 mNextFocusDownId = nextFocusDownId; 7608 } 7609 7610 /** 7611 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7612 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7613 * 7614 * @attr ref android.R.styleable#View_nextFocusForward 7615 */ 7616 public int getNextFocusForwardId() { 7617 return mNextFocusForwardId; 7618 } 7619 7620 /** 7621 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7622 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7623 * decide automatically. 7624 * 7625 * @attr ref android.R.styleable#View_nextFocusForward 7626 */ 7627 public void setNextFocusForwardId(int nextFocusForwardId) { 7628 mNextFocusForwardId = nextFocusForwardId; 7629 } 7630 7631 /** 7632 * Returns the visibility of this view and all of its ancestors 7633 * 7634 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7635 */ 7636 public boolean isShown() { 7637 View current = this; 7638 //noinspection ConstantConditions 7639 do { 7640 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7641 return false; 7642 } 7643 ViewParent parent = current.mParent; 7644 if (parent == null) { 7645 return false; // We are not attached to the view root 7646 } 7647 if (!(parent instanceof View)) { 7648 return true; 7649 } 7650 current = (View) parent; 7651 } while (current != null); 7652 7653 return false; 7654 } 7655 7656 /** 7657 * Called by the view hierarchy when the content insets for a window have 7658 * changed, to allow it to adjust its content to fit within those windows. 7659 * The content insets tell you the space that the status bar, input method, 7660 * and other system windows infringe on the application's window. 7661 * 7662 * <p>You do not normally need to deal with this function, since the default 7663 * window decoration given to applications takes care of applying it to the 7664 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7665 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7666 * and your content can be placed under those system elements. You can then 7667 * use this method within your view hierarchy if you have parts of your UI 7668 * which you would like to ensure are not being covered. 7669 * 7670 * <p>The default implementation of this method simply applies the content 7671 * insets to the view's padding, consuming that content (modifying the 7672 * insets to be 0), and returning true. This behavior is off by default, but can 7673 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7674 * 7675 * <p>This function's traversal down the hierarchy is depth-first. The same content 7676 * insets object is propagated down the hierarchy, so any changes made to it will 7677 * be seen by all following views (including potentially ones above in 7678 * the hierarchy since this is a depth-first traversal). The first view 7679 * that returns true will abort the entire traversal. 7680 * 7681 * <p>The default implementation works well for a situation where it is 7682 * used with a container that covers the entire window, allowing it to 7683 * apply the appropriate insets to its content on all edges. If you need 7684 * a more complicated layout (such as two different views fitting system 7685 * windows, one on the top of the window, and one on the bottom), 7686 * you can override the method and handle the insets however you would like. 7687 * Note that the insets provided by the framework are always relative to the 7688 * far edges of the window, not accounting for the location of the called view 7689 * within that window. (In fact when this method is called you do not yet know 7690 * where the layout will place the view, as it is done before layout happens.) 7691 * 7692 * <p>Note: unlike many View methods, there is no dispatch phase to this 7693 * call. If you are overriding it in a ViewGroup and want to allow the 7694 * call to continue to your children, you must be sure to call the super 7695 * implementation. 7696 * 7697 * <p>Here is a sample layout that makes use of fitting system windows 7698 * to have controls for a video view placed inside of the window decorations 7699 * that it hides and shows. This can be used with code like the second 7700 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7701 * 7702 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7703 * 7704 * @param insets Current content insets of the window. Prior to 7705 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7706 * the insets or else you and Android will be unhappy. 7707 * 7708 * @return {@code true} if this view applied the insets and it should not 7709 * continue propagating further down the hierarchy, {@code false} otherwise. 7710 * @see #getFitsSystemWindows() 7711 * @see #setFitsSystemWindows(boolean) 7712 * @see #setSystemUiVisibility(int) 7713 * 7714 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7715 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7716 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7717 * to implement handling their own insets. 7718 */ 7719 @Deprecated 7720 protected boolean fitSystemWindows(Rect insets) { 7721 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7722 if (insets == null) { 7723 // Null insets by definition have already been consumed. 7724 // This call cannot apply insets since there are none to apply, 7725 // so return false. 7726 return false; 7727 } 7728 // If we're not in the process of dispatching the newer apply insets call, 7729 // that means we're not in the compatibility path. Dispatch into the newer 7730 // apply insets path and take things from there. 7731 try { 7732 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7733 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7734 } finally { 7735 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7736 } 7737 } else { 7738 // We're being called from the newer apply insets path. 7739 // Perform the standard fallback behavior. 7740 return fitSystemWindowsInt(insets); 7741 } 7742 } 7743 7744 private boolean fitSystemWindowsInt(Rect insets) { 7745 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7746 mUserPaddingStart = UNDEFINED_PADDING; 7747 mUserPaddingEnd = UNDEFINED_PADDING; 7748 Rect localInsets = sThreadLocal.get(); 7749 if (localInsets == null) { 7750 localInsets = new Rect(); 7751 sThreadLocal.set(localInsets); 7752 } 7753 boolean res = computeFitSystemWindows(insets, localInsets); 7754 mUserPaddingLeftInitial = localInsets.left; 7755 mUserPaddingRightInitial = localInsets.right; 7756 internalSetPadding(localInsets.left, localInsets.top, 7757 localInsets.right, localInsets.bottom); 7758 return res; 7759 } 7760 return false; 7761 } 7762 7763 /** 7764 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7765 * 7766 * <p>This method should be overridden by views that wish to apply a policy different from or 7767 * in addition to the default behavior. Clients that wish to force a view subtree 7768 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7769 * 7770 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7771 * it will be called during dispatch instead of this method. The listener may optionally 7772 * call this method from its own implementation if it wishes to apply the view's default 7773 * insets policy in addition to its own.</p> 7774 * 7775 * <p>Implementations of this method should either return the insets parameter unchanged 7776 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7777 * that this view applied itself. This allows new inset types added in future platform 7778 * versions to pass through existing implementations unchanged without being erroneously 7779 * consumed.</p> 7780 * 7781 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7782 * property is set then the view will consume the system window insets and apply them 7783 * as padding for the view.</p> 7784 * 7785 * @param insets Insets to apply 7786 * @return The supplied insets with any applied insets consumed 7787 */ 7788 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7789 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7790 // We weren't called from within a direct call to fitSystemWindows, 7791 // call into it as a fallback in case we're in a class that overrides it 7792 // and has logic to perform. 7793 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7794 return insets.consumeSystemWindowInsets(); 7795 } 7796 } else { 7797 // We were called from within a direct call to fitSystemWindows. 7798 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7799 return insets.consumeSystemWindowInsets(); 7800 } 7801 } 7802 return insets; 7803 } 7804 7805 /** 7806 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7807 * window insets to this view. The listener's 7808 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7809 * method will be called instead of the view's 7810 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7811 * 7812 * @param listener Listener to set 7813 * 7814 * @see #onApplyWindowInsets(WindowInsets) 7815 */ 7816 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7817 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7818 } 7819 7820 /** 7821 * Request to apply the given window insets to this view or another view in its subtree. 7822 * 7823 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7824 * obscured by window decorations or overlays. This can include the status and navigation bars, 7825 * action bars, input methods and more. New inset categories may be added in the future. 7826 * The method returns the insets provided minus any that were applied by this view or its 7827 * children.</p> 7828 * 7829 * <p>Clients wishing to provide custom behavior should override the 7830 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7831 * {@link OnApplyWindowInsetsListener} via the 7832 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7833 * method.</p> 7834 * 7835 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7836 * </p> 7837 * 7838 * @param insets Insets to apply 7839 * @return The provided insets minus the insets that were consumed 7840 */ 7841 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7842 try { 7843 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7844 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7845 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7846 } else { 7847 return onApplyWindowInsets(insets); 7848 } 7849 } finally { 7850 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7851 } 7852 } 7853 7854 /** 7855 * Compute the view's coordinate within the surface. 7856 * 7857 * <p>Computes the coordinates of this view in its surface. The argument 7858 * must be an array of two integers. After the method returns, the array 7859 * contains the x and y location in that order.</p> 7860 * @hide 7861 * @param location an array of two integers in which to hold the coordinates 7862 */ 7863 public void getLocationInSurface(@Size(2) int[] location) { 7864 getLocationInWindow(location); 7865 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7866 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7867 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7868 } 7869 } 7870 7871 /** 7872 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7873 * only available if the view is attached. 7874 * 7875 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7876 */ 7877 public WindowInsets getRootWindowInsets() { 7878 if (mAttachInfo != null) { 7879 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7880 } 7881 return null; 7882 } 7883 7884 /** 7885 * @hide Compute the insets that should be consumed by this view and the ones 7886 * that should propagate to those under it. 7887 */ 7888 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7889 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7890 || mAttachInfo == null 7891 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7892 && !mAttachInfo.mOverscanRequested)) { 7893 outLocalInsets.set(inoutInsets); 7894 inoutInsets.set(0, 0, 0, 0); 7895 return true; 7896 } else { 7897 // The application wants to take care of fitting system window for 7898 // the content... however we still need to take care of any overscan here. 7899 final Rect overscan = mAttachInfo.mOverscanInsets; 7900 outLocalInsets.set(overscan); 7901 inoutInsets.left -= overscan.left; 7902 inoutInsets.top -= overscan.top; 7903 inoutInsets.right -= overscan.right; 7904 inoutInsets.bottom -= overscan.bottom; 7905 return false; 7906 } 7907 } 7908 7909 /** 7910 * Compute insets that should be consumed by this view and the ones that should propagate 7911 * to those under it. 7912 * 7913 * @param in Insets currently being processed by this View, likely received as a parameter 7914 * to {@link #onApplyWindowInsets(WindowInsets)}. 7915 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7916 * by this view 7917 * @return Insets that should be passed along to views under this one 7918 */ 7919 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7920 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7921 || mAttachInfo == null 7922 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7923 outLocalInsets.set(in.getSystemWindowInsets()); 7924 return in.consumeSystemWindowInsets(); 7925 } else { 7926 outLocalInsets.set(0, 0, 0, 0); 7927 return in; 7928 } 7929 } 7930 7931 /** 7932 * Sets whether or not this view should account for system screen decorations 7933 * such as the status bar and inset its content; that is, controlling whether 7934 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7935 * executed. See that method for more details. 7936 * 7937 * <p>Note that if you are providing your own implementation of 7938 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7939 * flag to true -- your implementation will be overriding the default 7940 * implementation that checks this flag. 7941 * 7942 * @param fitSystemWindows If true, then the default implementation of 7943 * {@link #fitSystemWindows(Rect)} will be executed. 7944 * 7945 * @attr ref android.R.styleable#View_fitsSystemWindows 7946 * @see #getFitsSystemWindows() 7947 * @see #fitSystemWindows(Rect) 7948 * @see #setSystemUiVisibility(int) 7949 */ 7950 public void setFitsSystemWindows(boolean fitSystemWindows) { 7951 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7952 } 7953 7954 /** 7955 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7956 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7957 * will be executed. 7958 * 7959 * @return {@code true} if the default implementation of 7960 * {@link #fitSystemWindows(Rect)} will be executed. 7961 * 7962 * @attr ref android.R.styleable#View_fitsSystemWindows 7963 * @see #setFitsSystemWindows(boolean) 7964 * @see #fitSystemWindows(Rect) 7965 * @see #setSystemUiVisibility(int) 7966 */ 7967 @ViewDebug.ExportedProperty 7968 public boolean getFitsSystemWindows() { 7969 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7970 } 7971 7972 /** @hide */ 7973 public boolean fitsSystemWindows() { 7974 return getFitsSystemWindows(); 7975 } 7976 7977 /** 7978 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7979 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7980 */ 7981 @Deprecated 7982 public void requestFitSystemWindows() { 7983 if (mParent != null) { 7984 mParent.requestFitSystemWindows(); 7985 } 7986 } 7987 7988 /** 7989 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7990 */ 7991 public void requestApplyInsets() { 7992 requestFitSystemWindows(); 7993 } 7994 7995 /** 7996 * For use by PhoneWindow to make its own system window fitting optional. 7997 * @hide 7998 */ 7999 public void makeOptionalFitsSystemWindows() { 8000 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 8001 } 8002 8003 /** 8004 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 8005 * treat them as such. 8006 * @hide 8007 */ 8008 public void getOutsets(Rect outOutsetRect) { 8009 if (mAttachInfo != null) { 8010 outOutsetRect.set(mAttachInfo.mOutsets); 8011 } else { 8012 outOutsetRect.setEmpty(); 8013 } 8014 } 8015 8016 /** 8017 * Returns the visibility status for this view. 8018 * 8019 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8020 * @attr ref android.R.styleable#View_visibility 8021 */ 8022 @ViewDebug.ExportedProperty(mapping = { 8023 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 8024 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 8025 @ViewDebug.IntToString(from = GONE, to = "GONE") 8026 }) 8027 @Visibility 8028 public int getVisibility() { 8029 return mViewFlags & VISIBILITY_MASK; 8030 } 8031 8032 /** 8033 * Set the visibility state of this view. 8034 * 8035 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8036 * @attr ref android.R.styleable#View_visibility 8037 */ 8038 @RemotableViewMethod 8039 public void setVisibility(@Visibility int visibility) { 8040 setFlags(visibility, VISIBILITY_MASK); 8041 } 8042 8043 /** 8044 * Returns the enabled status for this view. The interpretation of the 8045 * enabled state varies by subclass. 8046 * 8047 * @return True if this view is enabled, false otherwise. 8048 */ 8049 @ViewDebug.ExportedProperty 8050 public boolean isEnabled() { 8051 return (mViewFlags & ENABLED_MASK) == ENABLED; 8052 } 8053 8054 /** 8055 * Set the enabled state of this view. The interpretation of the enabled 8056 * state varies by subclass. 8057 * 8058 * @param enabled True if this view is enabled, false otherwise. 8059 */ 8060 @RemotableViewMethod 8061 public void setEnabled(boolean enabled) { 8062 if (enabled == isEnabled()) return; 8063 8064 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8065 8066 /* 8067 * The View most likely has to change its appearance, so refresh 8068 * the drawable state. 8069 */ 8070 refreshDrawableState(); 8071 8072 // Invalidate too, since the default behavior for views is to be 8073 // be drawn at 50% alpha rather than to change the drawable. 8074 invalidate(true); 8075 8076 if (!enabled) { 8077 cancelPendingInputEvents(); 8078 } 8079 } 8080 8081 /** 8082 * Set whether this view can receive the focus. 8083 * 8084 * Setting this to false will also ensure that this view is not focusable 8085 * in touch mode. 8086 * 8087 * @param focusable If true, this view can receive the focus. 8088 * 8089 * @see #setFocusableInTouchMode(boolean) 8090 * @attr ref android.R.styleable#View_focusable 8091 */ 8092 public void setFocusable(boolean focusable) { 8093 if (!focusable) { 8094 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8095 } 8096 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8097 } 8098 8099 /** 8100 * Set whether this view can receive focus while in touch mode. 8101 * 8102 * Setting this to true will also ensure that this view is focusable. 8103 * 8104 * @param focusableInTouchMode If true, this view can receive the focus while 8105 * in touch mode. 8106 * 8107 * @see #setFocusable(boolean) 8108 * @attr ref android.R.styleable#View_focusableInTouchMode 8109 */ 8110 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8111 // Focusable in touch mode should always be set before the focusable flag 8112 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8113 // which, in touch mode, will not successfully request focus on this view 8114 // because the focusable in touch mode flag is not set 8115 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8116 if (focusableInTouchMode) { 8117 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8118 } 8119 } 8120 8121 /** 8122 * Set whether this view should have sound effects enabled for events such as 8123 * clicking and touching. 8124 * 8125 * <p>You may wish to disable sound effects for a view if you already play sounds, 8126 * for instance, a dial key that plays dtmf tones. 8127 * 8128 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8129 * @see #isSoundEffectsEnabled() 8130 * @see #playSoundEffect(int) 8131 * @attr ref android.R.styleable#View_soundEffectsEnabled 8132 */ 8133 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8134 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8135 } 8136 8137 /** 8138 * @return whether this view should have sound effects enabled for events such as 8139 * clicking and touching. 8140 * 8141 * @see #setSoundEffectsEnabled(boolean) 8142 * @see #playSoundEffect(int) 8143 * @attr ref android.R.styleable#View_soundEffectsEnabled 8144 */ 8145 @ViewDebug.ExportedProperty 8146 public boolean isSoundEffectsEnabled() { 8147 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8148 } 8149 8150 /** 8151 * Set whether this view should have haptic feedback for events such as 8152 * long presses. 8153 * 8154 * <p>You may wish to disable haptic feedback if your view already controls 8155 * its own haptic feedback. 8156 * 8157 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8158 * @see #isHapticFeedbackEnabled() 8159 * @see #performHapticFeedback(int) 8160 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8161 */ 8162 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8163 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8164 } 8165 8166 /** 8167 * @return whether this view should have haptic feedback enabled for events 8168 * long presses. 8169 * 8170 * @see #setHapticFeedbackEnabled(boolean) 8171 * @see #performHapticFeedback(int) 8172 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8173 */ 8174 @ViewDebug.ExportedProperty 8175 public boolean isHapticFeedbackEnabled() { 8176 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8177 } 8178 8179 /** 8180 * Returns the layout direction for this view. 8181 * 8182 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8183 * {@link #LAYOUT_DIRECTION_RTL}, 8184 * {@link #LAYOUT_DIRECTION_INHERIT} or 8185 * {@link #LAYOUT_DIRECTION_LOCALE}. 8186 * 8187 * @attr ref android.R.styleable#View_layoutDirection 8188 * 8189 * @hide 8190 */ 8191 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8192 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8193 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8194 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8195 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8196 }) 8197 @LayoutDir 8198 public int getRawLayoutDirection() { 8199 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8200 } 8201 8202 /** 8203 * Set the layout direction for this view. This will propagate a reset of layout direction 8204 * resolution to the view's children and resolve layout direction for this view. 8205 * 8206 * @param layoutDirection the layout direction to set. Should be one of: 8207 * 8208 * {@link #LAYOUT_DIRECTION_LTR}, 8209 * {@link #LAYOUT_DIRECTION_RTL}, 8210 * {@link #LAYOUT_DIRECTION_INHERIT}, 8211 * {@link #LAYOUT_DIRECTION_LOCALE}. 8212 * 8213 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8214 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8215 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8216 * 8217 * @attr ref android.R.styleable#View_layoutDirection 8218 */ 8219 @RemotableViewMethod 8220 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8221 if (getRawLayoutDirection() != layoutDirection) { 8222 // Reset the current layout direction and the resolved one 8223 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8224 resetRtlProperties(); 8225 // Set the new layout direction (filtered) 8226 mPrivateFlags2 |= 8227 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8228 // We need to resolve all RTL properties as they all depend on layout direction 8229 resolveRtlPropertiesIfNeeded(); 8230 requestLayout(); 8231 invalidate(true); 8232 } 8233 } 8234 8235 /** 8236 * Returns the resolved layout direction for this view. 8237 * 8238 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8239 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8240 * 8241 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8242 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8243 * 8244 * @attr ref android.R.styleable#View_layoutDirection 8245 */ 8246 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8247 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8248 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8249 }) 8250 @ResolvedLayoutDir 8251 public int getLayoutDirection() { 8252 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8253 if (targetSdkVersion < JELLY_BEAN_MR1) { 8254 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8255 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8256 } 8257 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8258 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8259 } 8260 8261 /** 8262 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8263 * layout attribute and/or the inherited value from the parent 8264 * 8265 * @return true if the layout is right-to-left. 8266 * 8267 * @hide 8268 */ 8269 @ViewDebug.ExportedProperty(category = "layout") 8270 public boolean isLayoutRtl() { 8271 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8272 } 8273 8274 /** 8275 * Indicates whether the view is currently tracking transient state that the 8276 * app should not need to concern itself with saving and restoring, but that 8277 * the framework should take special note to preserve when possible. 8278 * 8279 * <p>A view with transient state cannot be trivially rebound from an external 8280 * data source, such as an adapter binding item views in a list. This may be 8281 * because the view is performing an animation, tracking user selection 8282 * of content, or similar.</p> 8283 * 8284 * @return true if the view has transient state 8285 */ 8286 @ViewDebug.ExportedProperty(category = "layout") 8287 public boolean hasTransientState() { 8288 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8289 } 8290 8291 /** 8292 * Set whether this view is currently tracking transient state that the 8293 * framework should attempt to preserve when possible. This flag is reference counted, 8294 * so every call to setHasTransientState(true) should be paired with a later call 8295 * to setHasTransientState(false). 8296 * 8297 * <p>A view with transient state cannot be trivially rebound from an external 8298 * data source, such as an adapter binding item views in a list. This may be 8299 * because the view is performing an animation, tracking user selection 8300 * of content, or similar.</p> 8301 * 8302 * @param hasTransientState true if this view has transient state 8303 */ 8304 public void setHasTransientState(boolean hasTransientState) { 8305 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8306 mTransientStateCount - 1; 8307 if (mTransientStateCount < 0) { 8308 mTransientStateCount = 0; 8309 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8310 "unmatched pair of setHasTransientState calls"); 8311 } else if ((hasTransientState && mTransientStateCount == 1) || 8312 (!hasTransientState && mTransientStateCount == 0)) { 8313 // update flag if we've just incremented up from 0 or decremented down to 0 8314 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8315 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8316 if (mParent != null) { 8317 try { 8318 mParent.childHasTransientStateChanged(this, hasTransientState); 8319 } catch (AbstractMethodError e) { 8320 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8321 " does not fully implement ViewParent", e); 8322 } 8323 } 8324 } 8325 } 8326 8327 /** 8328 * Returns true if this view is currently attached to a window. 8329 */ 8330 public boolean isAttachedToWindow() { 8331 return mAttachInfo != null; 8332 } 8333 8334 /** 8335 * Returns true if this view has been through at least one layout since it 8336 * was last attached to or detached from a window. 8337 */ 8338 public boolean isLaidOut() { 8339 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8340 } 8341 8342 /** 8343 * If this view doesn't do any drawing on its own, set this flag to 8344 * allow further optimizations. By default, this flag is not set on 8345 * View, but could be set on some View subclasses such as ViewGroup. 8346 * 8347 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8348 * you should clear this flag. 8349 * 8350 * @param willNotDraw whether or not this View draw on its own 8351 */ 8352 public void setWillNotDraw(boolean willNotDraw) { 8353 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8354 } 8355 8356 /** 8357 * Returns whether or not this View draws on its own. 8358 * 8359 * @return true if this view has nothing to draw, false otherwise 8360 */ 8361 @ViewDebug.ExportedProperty(category = "drawing") 8362 public boolean willNotDraw() { 8363 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8364 } 8365 8366 /** 8367 * When a View's drawing cache is enabled, drawing is redirected to an 8368 * offscreen bitmap. Some views, like an ImageView, must be able to 8369 * bypass this mechanism if they already draw a single bitmap, to avoid 8370 * unnecessary usage of the memory. 8371 * 8372 * @param willNotCacheDrawing true if this view does not cache its 8373 * drawing, false otherwise 8374 */ 8375 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8376 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8377 } 8378 8379 /** 8380 * Returns whether or not this View can cache its drawing or not. 8381 * 8382 * @return true if this view does not cache its drawing, false otherwise 8383 */ 8384 @ViewDebug.ExportedProperty(category = "drawing") 8385 public boolean willNotCacheDrawing() { 8386 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8387 } 8388 8389 /** 8390 * Indicates whether this view reacts to click events or not. 8391 * 8392 * @return true if the view is clickable, false otherwise 8393 * 8394 * @see #setClickable(boolean) 8395 * @attr ref android.R.styleable#View_clickable 8396 */ 8397 @ViewDebug.ExportedProperty 8398 public boolean isClickable() { 8399 return (mViewFlags & CLICKABLE) == CLICKABLE; 8400 } 8401 8402 /** 8403 * Enables or disables click events for this view. When a view 8404 * is clickable it will change its state to "pressed" on every click. 8405 * Subclasses should set the view clickable to visually react to 8406 * user's clicks. 8407 * 8408 * @param clickable true to make the view clickable, false otherwise 8409 * 8410 * @see #isClickable() 8411 * @attr ref android.R.styleable#View_clickable 8412 */ 8413 public void setClickable(boolean clickable) { 8414 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8415 } 8416 8417 /** 8418 * Indicates whether this view reacts to long click events or not. 8419 * 8420 * @return true if the view is long clickable, false otherwise 8421 * 8422 * @see #setLongClickable(boolean) 8423 * @attr ref android.R.styleable#View_longClickable 8424 */ 8425 public boolean isLongClickable() { 8426 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8427 } 8428 8429 /** 8430 * Enables or disables long click events for this view. When a view is long 8431 * clickable it reacts to the user holding down the button for a longer 8432 * duration than a tap. This event can either launch the listener or a 8433 * context menu. 8434 * 8435 * @param longClickable true to make the view long clickable, false otherwise 8436 * @see #isLongClickable() 8437 * @attr ref android.R.styleable#View_longClickable 8438 */ 8439 public void setLongClickable(boolean longClickable) { 8440 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8441 } 8442 8443 /** 8444 * Indicates whether this view reacts to context clicks or not. 8445 * 8446 * @return true if the view is context clickable, false otherwise 8447 * @see #setContextClickable(boolean) 8448 * @attr ref android.R.styleable#View_contextClickable 8449 */ 8450 public boolean isContextClickable() { 8451 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8452 } 8453 8454 /** 8455 * Enables or disables context clicking for this view. This event can launch the listener. 8456 * 8457 * @param contextClickable true to make the view react to a context click, false otherwise 8458 * @see #isContextClickable() 8459 * @attr ref android.R.styleable#View_contextClickable 8460 */ 8461 public void setContextClickable(boolean contextClickable) { 8462 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8463 } 8464 8465 /** 8466 * Sets the pressed state for this view and provides a touch coordinate for 8467 * animation hinting. 8468 * 8469 * @param pressed Pass true to set the View's internal state to "pressed", 8470 * or false to reverts the View's internal state from a 8471 * previously set "pressed" state. 8472 * @param x The x coordinate of the touch that caused the press 8473 * @param y The y coordinate of the touch that caused the press 8474 */ 8475 private void setPressed(boolean pressed, float x, float y) { 8476 if (pressed) { 8477 drawableHotspotChanged(x, y); 8478 } 8479 8480 setPressed(pressed); 8481 } 8482 8483 /** 8484 * Sets the pressed state for this view. 8485 * 8486 * @see #isClickable() 8487 * @see #setClickable(boolean) 8488 * 8489 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8490 * the View's internal state from a previously set "pressed" state. 8491 */ 8492 public void setPressed(boolean pressed) { 8493 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8494 8495 if (pressed) { 8496 mPrivateFlags |= PFLAG_PRESSED; 8497 } else { 8498 mPrivateFlags &= ~PFLAG_PRESSED; 8499 } 8500 8501 if (needsRefresh) { 8502 refreshDrawableState(); 8503 } 8504 dispatchSetPressed(pressed); 8505 } 8506 8507 /** 8508 * Dispatch setPressed to all of this View's children. 8509 * 8510 * @see #setPressed(boolean) 8511 * 8512 * @param pressed The new pressed state 8513 */ 8514 protected void dispatchSetPressed(boolean pressed) { 8515 } 8516 8517 /** 8518 * Indicates whether the view is currently in pressed state. Unless 8519 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8520 * the pressed state. 8521 * 8522 * @see #setPressed(boolean) 8523 * @see #isClickable() 8524 * @see #setClickable(boolean) 8525 * 8526 * @return true if the view is currently pressed, false otherwise 8527 */ 8528 @ViewDebug.ExportedProperty 8529 public boolean isPressed() { 8530 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8531 } 8532 8533 /** 8534 * @hide 8535 * Indicates whether this view will participate in data collection through 8536 * {@link ViewStructure}. If true, it will not provide any data 8537 * for itself or its children. If false, the normal data collection will be allowed. 8538 * 8539 * @return Returns false if assist data collection is not blocked, else true. 8540 * 8541 * @see #setAssistBlocked(boolean) 8542 * @attr ref android.R.styleable#View_assistBlocked 8543 */ 8544 public boolean isAssistBlocked() { 8545 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8546 } 8547 8548 /** 8549 * @hide 8550 * Controls whether assist data collection from this view and its children is enabled 8551 * (that is, whether {@link #onProvideStructure} and 8552 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8553 * allowing normal assist collection. Setting this to false will disable assist collection. 8554 * 8555 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8556 * (the default) to allow it. 8557 * 8558 * @see #isAssistBlocked() 8559 * @see #onProvideStructure 8560 * @see #onProvideVirtualStructure 8561 * @attr ref android.R.styleable#View_assistBlocked 8562 */ 8563 public void setAssistBlocked(boolean enabled) { 8564 if (enabled) { 8565 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8566 } else { 8567 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8568 } 8569 } 8570 8571 /** 8572 * Indicates whether this view will save its state (that is, 8573 * whether its {@link #onSaveInstanceState} method will be called). 8574 * 8575 * @return Returns true if the view state saving is enabled, else false. 8576 * 8577 * @see #setSaveEnabled(boolean) 8578 * @attr ref android.R.styleable#View_saveEnabled 8579 */ 8580 public boolean isSaveEnabled() { 8581 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8582 } 8583 8584 /** 8585 * Controls whether the saving of this view's state is 8586 * enabled (that is, whether its {@link #onSaveInstanceState} method 8587 * will be called). Note that even if freezing is enabled, the 8588 * view still must have an id assigned to it (via {@link #setId(int)}) 8589 * for its state to be saved. This flag can only disable the 8590 * saving of this view; any child views may still have their state saved. 8591 * 8592 * @param enabled Set to false to <em>disable</em> state saving, or true 8593 * (the default) to allow it. 8594 * 8595 * @see #isSaveEnabled() 8596 * @see #setId(int) 8597 * @see #onSaveInstanceState() 8598 * @attr ref android.R.styleable#View_saveEnabled 8599 */ 8600 public void setSaveEnabled(boolean enabled) { 8601 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8602 } 8603 8604 /** 8605 * Gets whether the framework should discard touches when the view's 8606 * window is obscured by another visible window. 8607 * Refer to the {@link View} security documentation for more details. 8608 * 8609 * @return True if touch filtering is enabled. 8610 * 8611 * @see #setFilterTouchesWhenObscured(boolean) 8612 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8613 */ 8614 @ViewDebug.ExportedProperty 8615 public boolean getFilterTouchesWhenObscured() { 8616 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8617 } 8618 8619 /** 8620 * Sets whether the framework should discard touches when the view's 8621 * window is obscured by another visible window. 8622 * Refer to the {@link View} security documentation for more details. 8623 * 8624 * @param enabled True if touch filtering should be enabled. 8625 * 8626 * @see #getFilterTouchesWhenObscured 8627 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8628 */ 8629 public void setFilterTouchesWhenObscured(boolean enabled) { 8630 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8631 FILTER_TOUCHES_WHEN_OBSCURED); 8632 } 8633 8634 /** 8635 * Indicates whether the entire hierarchy under this view will save its 8636 * state when a state saving traversal occurs from its parent. The default 8637 * is true; if false, these views will not be saved unless 8638 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8639 * 8640 * @return Returns true if the view state saving from parent is enabled, else false. 8641 * 8642 * @see #setSaveFromParentEnabled(boolean) 8643 */ 8644 public boolean isSaveFromParentEnabled() { 8645 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8646 } 8647 8648 /** 8649 * Controls whether the entire hierarchy under this view will save its 8650 * state when a state saving traversal occurs from its parent. The default 8651 * is true; if false, these views will not be saved unless 8652 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8653 * 8654 * @param enabled Set to false to <em>disable</em> state saving, or true 8655 * (the default) to allow it. 8656 * 8657 * @see #isSaveFromParentEnabled() 8658 * @see #setId(int) 8659 * @see #onSaveInstanceState() 8660 */ 8661 public void setSaveFromParentEnabled(boolean enabled) { 8662 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8663 } 8664 8665 8666 /** 8667 * Returns whether this View is able to take focus. 8668 * 8669 * @return True if this view can take focus, or false otherwise. 8670 * @attr ref android.R.styleable#View_focusable 8671 */ 8672 @ViewDebug.ExportedProperty(category = "focus") 8673 public final boolean isFocusable() { 8674 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8675 } 8676 8677 /** 8678 * When a view is focusable, it may not want to take focus when in touch mode. 8679 * For example, a button would like focus when the user is navigating via a D-pad 8680 * so that the user can click on it, but once the user starts touching the screen, 8681 * the button shouldn't take focus 8682 * @return Whether the view is focusable in touch mode. 8683 * @attr ref android.R.styleable#View_focusableInTouchMode 8684 */ 8685 @ViewDebug.ExportedProperty 8686 public final boolean isFocusableInTouchMode() { 8687 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8688 } 8689 8690 /** 8691 * Find the nearest view in the specified direction that can take focus. 8692 * This does not actually give focus to that view. 8693 * 8694 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8695 * 8696 * @return The nearest focusable in the specified direction, or null if none 8697 * can be found. 8698 */ 8699 public View focusSearch(@FocusRealDirection int direction) { 8700 if (mParent != null) { 8701 return mParent.focusSearch(this, direction); 8702 } else { 8703 return null; 8704 } 8705 } 8706 8707 /** 8708 * This method is the last chance for the focused view and its ancestors to 8709 * respond to an arrow key. This is called when the focused view did not 8710 * consume the key internally, nor could the view system find a new view in 8711 * the requested direction to give focus to. 8712 * 8713 * @param focused The currently focused view. 8714 * @param direction The direction focus wants to move. One of FOCUS_UP, 8715 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8716 * @return True if the this view consumed this unhandled move. 8717 */ 8718 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8719 return false; 8720 } 8721 8722 /** 8723 * If a user manually specified the next view id for a particular direction, 8724 * use the root to look up the view. 8725 * @param root The root view of the hierarchy containing this view. 8726 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8727 * or FOCUS_BACKWARD. 8728 * @return The user specified next view, or null if there is none. 8729 */ 8730 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8731 switch (direction) { 8732 case FOCUS_LEFT: 8733 if (mNextFocusLeftId == View.NO_ID) return null; 8734 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8735 case FOCUS_RIGHT: 8736 if (mNextFocusRightId == View.NO_ID) return null; 8737 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8738 case FOCUS_UP: 8739 if (mNextFocusUpId == View.NO_ID) return null; 8740 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8741 case FOCUS_DOWN: 8742 if (mNextFocusDownId == View.NO_ID) return null; 8743 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8744 case FOCUS_FORWARD: 8745 if (mNextFocusForwardId == View.NO_ID) return null; 8746 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8747 case FOCUS_BACKWARD: { 8748 if (mID == View.NO_ID) return null; 8749 final int id = mID; 8750 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8751 @Override 8752 public boolean apply(View t) { 8753 return t.mNextFocusForwardId == id; 8754 } 8755 }); 8756 } 8757 } 8758 return null; 8759 } 8760 8761 private View findViewInsideOutShouldExist(View root, int id) { 8762 if (mMatchIdPredicate == null) { 8763 mMatchIdPredicate = new MatchIdPredicate(); 8764 } 8765 mMatchIdPredicate.mId = id; 8766 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8767 if (result == null) { 8768 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8769 } 8770 return result; 8771 } 8772 8773 /** 8774 * Find and return all focusable views that are descendants of this view, 8775 * possibly including this view if it is focusable itself. 8776 * 8777 * @param direction The direction of the focus 8778 * @return A list of focusable views 8779 */ 8780 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8781 ArrayList<View> result = new ArrayList<View>(24); 8782 addFocusables(result, direction); 8783 return result; 8784 } 8785 8786 /** 8787 * Add any focusable views that are descendants of this view (possibly 8788 * including this view if it is focusable itself) to views. If we are in touch mode, 8789 * only add views that are also focusable in touch mode. 8790 * 8791 * @param views Focusable views found so far 8792 * @param direction The direction of the focus 8793 */ 8794 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8795 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 8796 } 8797 8798 /** 8799 * Adds any focusable views that are descendants of this view (possibly 8800 * including this view if it is focusable itself) to views. This method 8801 * adds all focusable views regardless if we are in touch mode or 8802 * only views focusable in touch mode if we are in touch mode or 8803 * only views that can take accessibility focus if accessibility is enabled 8804 * depending on the focusable mode parameter. 8805 * 8806 * @param views Focusable views found so far or null if all we are interested is 8807 * the number of focusables. 8808 * @param direction The direction of the focus. 8809 * @param focusableMode The type of focusables to be added. 8810 * 8811 * @see #FOCUSABLES_ALL 8812 * @see #FOCUSABLES_TOUCH_MODE 8813 */ 8814 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8815 @FocusableMode int focusableMode) { 8816 if (views == null) { 8817 return; 8818 } 8819 if (!isFocusable()) { 8820 return; 8821 } 8822 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8823 && !isFocusableInTouchMode()) { 8824 return; 8825 } 8826 views.add(this); 8827 } 8828 8829 /** 8830 * Finds the Views that contain given text. The containment is case insensitive. 8831 * The search is performed by either the text that the View renders or the content 8832 * description that describes the view for accessibility purposes and the view does 8833 * not render or both. Clients can specify how the search is to be performed via 8834 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8835 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8836 * 8837 * @param outViews The output list of matching Views. 8838 * @param searched The text to match against. 8839 * 8840 * @see #FIND_VIEWS_WITH_TEXT 8841 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8842 * @see #setContentDescription(CharSequence) 8843 */ 8844 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8845 @FindViewFlags int flags) { 8846 if (getAccessibilityNodeProvider() != null) { 8847 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8848 outViews.add(this); 8849 } 8850 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8851 && (searched != null && searched.length() > 0) 8852 && (mContentDescription != null && mContentDescription.length() > 0)) { 8853 String searchedLowerCase = searched.toString().toLowerCase(); 8854 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8855 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8856 outViews.add(this); 8857 } 8858 } 8859 } 8860 8861 /** 8862 * Find and return all touchable views that are descendants of this view, 8863 * possibly including this view if it is touchable itself. 8864 * 8865 * @return A list of touchable views 8866 */ 8867 public ArrayList<View> getTouchables() { 8868 ArrayList<View> result = new ArrayList<View>(); 8869 addTouchables(result); 8870 return result; 8871 } 8872 8873 /** 8874 * Add any touchable views that are descendants of this view (possibly 8875 * including this view if it is touchable itself) to views. 8876 * 8877 * @param views Touchable views found so far 8878 */ 8879 public void addTouchables(ArrayList<View> views) { 8880 final int viewFlags = mViewFlags; 8881 8882 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8883 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8884 && (viewFlags & ENABLED_MASK) == ENABLED) { 8885 views.add(this); 8886 } 8887 } 8888 8889 /** 8890 * Returns whether this View is accessibility focused. 8891 * 8892 * @return True if this View is accessibility focused. 8893 */ 8894 public boolean isAccessibilityFocused() { 8895 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8896 } 8897 8898 /** 8899 * Call this to try to give accessibility focus to this view. 8900 * 8901 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8902 * returns false or the view is no visible or the view already has accessibility 8903 * focus. 8904 * 8905 * See also {@link #focusSearch(int)}, which is what you call to say that you 8906 * have focus, and you want your parent to look for the next one. 8907 * 8908 * @return Whether this view actually took accessibility focus. 8909 * 8910 * @hide 8911 */ 8912 public boolean requestAccessibilityFocus() { 8913 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8914 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8915 return false; 8916 } 8917 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8918 return false; 8919 } 8920 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8921 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8922 ViewRootImpl viewRootImpl = getViewRootImpl(); 8923 if (viewRootImpl != null) { 8924 viewRootImpl.setAccessibilityFocus(this, null); 8925 } 8926 invalidate(); 8927 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8928 return true; 8929 } 8930 return false; 8931 } 8932 8933 /** 8934 * Call this to try to clear accessibility focus of this view. 8935 * 8936 * See also {@link #focusSearch(int)}, which is what you call to say that you 8937 * have focus, and you want your parent to look for the next one. 8938 * 8939 * @hide 8940 */ 8941 public void clearAccessibilityFocus() { 8942 clearAccessibilityFocusNoCallbacks(0); 8943 8944 // Clear the global reference of accessibility focus if this view or 8945 // any of its descendants had accessibility focus. This will NOT send 8946 // an event or update internal state if focus is cleared from a 8947 // descendant view, which may leave views in inconsistent states. 8948 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8949 if (viewRootImpl != null) { 8950 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8951 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8952 viewRootImpl.setAccessibilityFocus(null, null); 8953 } 8954 } 8955 } 8956 8957 private void sendAccessibilityHoverEvent(int eventType) { 8958 // Since we are not delivering to a client accessibility events from not 8959 // important views (unless the clinet request that) we need to fire the 8960 // event from the deepest view exposed to the client. As a consequence if 8961 // the user crosses a not exposed view the client will see enter and exit 8962 // of the exposed predecessor followed by and enter and exit of that same 8963 // predecessor when entering and exiting the not exposed descendant. This 8964 // is fine since the client has a clear idea which view is hovered at the 8965 // price of a couple more events being sent. This is a simple and 8966 // working solution. 8967 View source = this; 8968 while (true) { 8969 if (source.includeForAccessibility()) { 8970 source.sendAccessibilityEvent(eventType); 8971 return; 8972 } 8973 ViewParent parent = source.getParent(); 8974 if (parent instanceof View) { 8975 source = (View) parent; 8976 } else { 8977 return; 8978 } 8979 } 8980 } 8981 8982 /** 8983 * Clears accessibility focus without calling any callback methods 8984 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8985 * is used separately from that one for clearing accessibility focus when 8986 * giving this focus to another view. 8987 * 8988 * @param action The action, if any, that led to focus being cleared. Set to 8989 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 8990 * the window. 8991 */ 8992 void clearAccessibilityFocusNoCallbacks(int action) { 8993 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8994 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8995 invalidate(); 8996 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8997 AccessibilityEvent event = AccessibilityEvent.obtain( 8998 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8999 event.setAction(action); 9000 if (mAccessibilityDelegate != null) { 9001 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 9002 } else { 9003 sendAccessibilityEventUnchecked(event); 9004 } 9005 } 9006 } 9007 } 9008 9009 /** 9010 * Call this to try to give focus to a specific view or to one of its 9011 * descendants. 9012 * 9013 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9014 * false), or if it is focusable and it is not focusable in touch mode 9015 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9016 * 9017 * See also {@link #focusSearch(int)}, which is what you call to say that you 9018 * have focus, and you want your parent to look for the next one. 9019 * 9020 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 9021 * {@link #FOCUS_DOWN} and <code>null</code>. 9022 * 9023 * @return Whether this view or one of its descendants actually took focus. 9024 */ 9025 public final boolean requestFocus() { 9026 return requestFocus(View.FOCUS_DOWN); 9027 } 9028 9029 /** 9030 * Call this to try to give focus to a specific view or to one of its 9031 * descendants and give it a hint about what direction focus is heading. 9032 * 9033 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9034 * false), or if it is focusable and it is not focusable in touch mode 9035 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9036 * 9037 * See also {@link #focusSearch(int)}, which is what you call to say that you 9038 * have focus, and you want your parent to look for the next one. 9039 * 9040 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 9041 * <code>null</code> set for the previously focused rectangle. 9042 * 9043 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9044 * @return Whether this view or one of its descendants actually took focus. 9045 */ 9046 public final boolean requestFocus(int direction) { 9047 return requestFocus(direction, null); 9048 } 9049 9050 /** 9051 * Call this to try to give focus to a specific view or to one of its descendants 9052 * and give it hints about the direction and a specific rectangle that the focus 9053 * is coming from. The rectangle can help give larger views a finer grained hint 9054 * about where focus is coming from, and therefore, where to show selection, or 9055 * forward focus change internally. 9056 * 9057 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9058 * false), or if it is focusable and it is not focusable in touch mode 9059 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9060 * 9061 * A View will not take focus if it is not visible. 9062 * 9063 * A View will not take focus if one of its parents has 9064 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9065 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9066 * 9067 * See also {@link #focusSearch(int)}, which is what you call to say that you 9068 * have focus, and you want your parent to look for the next one. 9069 * 9070 * You may wish to override this method if your custom {@link View} has an internal 9071 * {@link View} that it wishes to forward the request to. 9072 * 9073 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9074 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9075 * to give a finer grained hint about where focus is coming from. May be null 9076 * if there is no hint. 9077 * @return Whether this view or one of its descendants actually took focus. 9078 */ 9079 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9080 return requestFocusNoSearch(direction, previouslyFocusedRect); 9081 } 9082 9083 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9084 // need to be focusable 9085 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9086 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9087 return false; 9088 } 9089 9090 // need to be focusable in touch mode if in touch mode 9091 if (isInTouchMode() && 9092 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9093 return false; 9094 } 9095 9096 // need to not have any parents blocking us 9097 if (hasAncestorThatBlocksDescendantFocus()) { 9098 return false; 9099 } 9100 9101 handleFocusGainInternal(direction, previouslyFocusedRect); 9102 return true; 9103 } 9104 9105 /** 9106 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9107 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9108 * touch mode to request focus when they are touched. 9109 * 9110 * @return Whether this view or one of its descendants actually took focus. 9111 * 9112 * @see #isInTouchMode() 9113 * 9114 */ 9115 public final boolean requestFocusFromTouch() { 9116 // Leave touch mode if we need to 9117 if (isInTouchMode()) { 9118 ViewRootImpl viewRoot = getViewRootImpl(); 9119 if (viewRoot != null) { 9120 viewRoot.ensureTouchMode(false); 9121 } 9122 } 9123 return requestFocus(View.FOCUS_DOWN); 9124 } 9125 9126 /** 9127 * @return Whether any ancestor of this view blocks descendant focus. 9128 */ 9129 private boolean hasAncestorThatBlocksDescendantFocus() { 9130 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9131 ViewParent ancestor = mParent; 9132 while (ancestor instanceof ViewGroup) { 9133 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9134 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9135 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9136 return true; 9137 } else { 9138 ancestor = vgAncestor.getParent(); 9139 } 9140 } 9141 return false; 9142 } 9143 9144 /** 9145 * Gets the mode for determining whether this View is important for accessibility. 9146 * A view is important for accessibility if it fires accessibility events and if it 9147 * is reported to accessibility services that query the screen. 9148 * 9149 * @return The mode for determining whether a view is important for accessibility, one 9150 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 9151 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 9152 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 9153 * 9154 * @attr ref android.R.styleable#View_importantForAccessibility 9155 * 9156 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9157 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9158 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9159 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9160 */ 9161 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9162 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9163 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9164 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9165 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9166 to = "noHideDescendants") 9167 }) 9168 public int getImportantForAccessibility() { 9169 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9170 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9171 } 9172 9173 /** 9174 * Sets the live region mode for this view. This indicates to accessibility 9175 * services whether they should automatically notify the user about changes 9176 * to the view's content description or text, or to the content descriptions 9177 * or text of the view's children (where applicable). 9178 * <p> 9179 * For example, in a login screen with a TextView that displays an "incorrect 9180 * password" notification, that view should be marked as a live region with 9181 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9182 * <p> 9183 * To disable change notifications for this view, use 9184 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9185 * mode for most views. 9186 * <p> 9187 * To indicate that the user should be notified of changes, use 9188 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9189 * <p> 9190 * If the view's changes should interrupt ongoing speech and notify the user 9191 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9192 * 9193 * @param mode The live region mode for this view, one of: 9194 * <ul> 9195 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9196 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9197 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9198 * </ul> 9199 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9200 */ 9201 public void setAccessibilityLiveRegion(int mode) { 9202 if (mode != getAccessibilityLiveRegion()) { 9203 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9204 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9205 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9206 notifyViewAccessibilityStateChangedIfNeeded( 9207 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9208 } 9209 } 9210 9211 /** 9212 * Gets the live region mode for this View. 9213 * 9214 * @return The live region mode for the view. 9215 * 9216 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9217 * 9218 * @see #setAccessibilityLiveRegion(int) 9219 */ 9220 public int getAccessibilityLiveRegion() { 9221 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9222 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9223 } 9224 9225 /** 9226 * Sets how to determine whether this view is important for accessibility 9227 * which is if it fires accessibility events and if it is reported to 9228 * accessibility services that query the screen. 9229 * 9230 * @param mode How to determine whether this view is important for accessibility. 9231 * 9232 * @attr ref android.R.styleable#View_importantForAccessibility 9233 * 9234 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9235 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9236 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9237 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9238 */ 9239 public void setImportantForAccessibility(int mode) { 9240 final int oldMode = getImportantForAccessibility(); 9241 if (mode != oldMode) { 9242 final boolean hideDescendants = 9243 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9244 9245 // If this node or its descendants are no longer important, try to 9246 // clear accessibility focus. 9247 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9248 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9249 if (focusHost != null) { 9250 focusHost.clearAccessibilityFocus(); 9251 } 9252 } 9253 9254 // If we're moving between AUTO and another state, we might not need 9255 // to send a subtree changed notification. We'll store the computed 9256 // importance, since we'll need to check it later to make sure. 9257 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9258 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9259 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9260 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9261 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9262 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9263 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9264 notifySubtreeAccessibilityStateChangedIfNeeded(); 9265 } else { 9266 notifyViewAccessibilityStateChangedIfNeeded( 9267 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9268 } 9269 } 9270 } 9271 9272 /** 9273 * Returns the view within this view's hierarchy that is hosting 9274 * accessibility focus. 9275 * 9276 * @param searchDescendants whether to search for focus in descendant views 9277 * @return the view hosting accessibility focus, or {@code null} 9278 */ 9279 private View findAccessibilityFocusHost(boolean searchDescendants) { 9280 if (isAccessibilityFocusedViewOrHost()) { 9281 return this; 9282 } 9283 9284 if (searchDescendants) { 9285 final ViewRootImpl viewRoot = getViewRootImpl(); 9286 if (viewRoot != null) { 9287 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9288 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9289 return focusHost; 9290 } 9291 } 9292 } 9293 9294 return null; 9295 } 9296 9297 /** 9298 * Computes whether this view should be exposed for accessibility. In 9299 * general, views that are interactive or provide information are exposed 9300 * while views that serve only as containers are hidden. 9301 * <p> 9302 * If an ancestor of this view has importance 9303 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9304 * returns <code>false</code>. 9305 * <p> 9306 * Otherwise, the value is computed according to the view's 9307 * {@link #getImportantForAccessibility()} value: 9308 * <ol> 9309 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9310 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9311 * </code> 9312 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9313 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9314 * view satisfies any of the following: 9315 * <ul> 9316 * <li>Is actionable, e.g. {@link #isClickable()}, 9317 * {@link #isLongClickable()}, or {@link #isFocusable()} 9318 * <li>Has an {@link AccessibilityDelegate} 9319 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9320 * {@link OnKeyListener}, etc. 9321 * <li>Is an accessibility live region, e.g. 9322 * {@link #getAccessibilityLiveRegion()} is not 9323 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9324 * </ul> 9325 * </ol> 9326 * 9327 * @return Whether the view is exposed for accessibility. 9328 * @see #setImportantForAccessibility(int) 9329 * @see #getImportantForAccessibility() 9330 */ 9331 public boolean isImportantForAccessibility() { 9332 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9333 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9334 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9335 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9336 return false; 9337 } 9338 9339 // Check parent mode to ensure we're not hidden. 9340 ViewParent parent = mParent; 9341 while (parent instanceof View) { 9342 if (((View) parent).getImportantForAccessibility() 9343 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9344 return false; 9345 } 9346 parent = parent.getParent(); 9347 } 9348 9349 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9350 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9351 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9352 } 9353 9354 /** 9355 * Gets the parent for accessibility purposes. Note that the parent for 9356 * accessibility is not necessary the immediate parent. It is the first 9357 * predecessor that is important for accessibility. 9358 * 9359 * @return The parent for accessibility purposes. 9360 */ 9361 public ViewParent getParentForAccessibility() { 9362 if (mParent instanceof View) { 9363 View parentView = (View) mParent; 9364 if (parentView.includeForAccessibility()) { 9365 return mParent; 9366 } else { 9367 return mParent.getParentForAccessibility(); 9368 } 9369 } 9370 return null; 9371 } 9372 9373 /** 9374 * Adds the children of this View relevant for accessibility to the given list 9375 * as output. Since some Views are not important for accessibility the added 9376 * child views are not necessarily direct children of this view, rather they are 9377 * the first level of descendants important for accessibility. 9378 * 9379 * @param outChildren The output list that will receive children for accessibility. 9380 */ 9381 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9382 9383 } 9384 9385 /** 9386 * Whether to regard this view for accessibility. A view is regarded for 9387 * accessibility if it is important for accessibility or the querying 9388 * accessibility service has explicitly requested that view not 9389 * important for accessibility are regarded. 9390 * 9391 * @return Whether to regard the view for accessibility. 9392 * 9393 * @hide 9394 */ 9395 public boolean includeForAccessibility() { 9396 if (mAttachInfo != null) { 9397 return (mAttachInfo.mAccessibilityFetchFlags 9398 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9399 || isImportantForAccessibility(); 9400 } 9401 return false; 9402 } 9403 9404 /** 9405 * Returns whether the View is considered actionable from 9406 * accessibility perspective. Such view are important for 9407 * accessibility. 9408 * 9409 * @return True if the view is actionable for accessibility. 9410 * 9411 * @hide 9412 */ 9413 public boolean isActionableForAccessibility() { 9414 return (isClickable() || isLongClickable() || isFocusable()); 9415 } 9416 9417 /** 9418 * Returns whether the View has registered callbacks which makes it 9419 * important for accessibility. 9420 * 9421 * @return True if the view is actionable for accessibility. 9422 */ 9423 private boolean hasListenersForAccessibility() { 9424 ListenerInfo info = getListenerInfo(); 9425 return mTouchDelegate != null || info.mOnKeyListener != null 9426 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9427 || info.mOnHoverListener != null || info.mOnDragListener != null; 9428 } 9429 9430 /** 9431 * Notifies that the accessibility state of this view changed. The change 9432 * is local to this view and does not represent structural changes such 9433 * as children and parent. For example, the view became focusable. The 9434 * notification is at at most once every 9435 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9436 * to avoid unnecessary load to the system. Also once a view has a pending 9437 * notification this method is a NOP until the notification has been sent. 9438 * 9439 * @hide 9440 */ 9441 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9442 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9443 return; 9444 } 9445 if (mSendViewStateChangedAccessibilityEvent == null) { 9446 mSendViewStateChangedAccessibilityEvent = 9447 new SendViewStateChangedAccessibilityEvent(); 9448 } 9449 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9450 } 9451 9452 /** 9453 * Notifies that the accessibility state of this view changed. The change 9454 * is *not* local to this view and does represent structural changes such 9455 * as children and parent. For example, the view size changed. The 9456 * notification is at at most once every 9457 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9458 * to avoid unnecessary load to the system. Also once a view has a pending 9459 * notification this method is a NOP until the notification has been sent. 9460 * 9461 * @hide 9462 */ 9463 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9464 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9465 return; 9466 } 9467 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9468 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9469 if (mParent != null) { 9470 try { 9471 mParent.notifySubtreeAccessibilityStateChanged( 9472 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9473 } catch (AbstractMethodError e) { 9474 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9475 " does not fully implement ViewParent", e); 9476 } 9477 } 9478 } 9479 } 9480 9481 /** 9482 * Change the visibility of the View without triggering any other changes. This is 9483 * important for transitions, where visibility changes should not adjust focus or 9484 * trigger a new layout. This is only used when the visibility has already been changed 9485 * and we need a transient value during an animation. When the animation completes, 9486 * the original visibility value is always restored. 9487 * 9488 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9489 * @hide 9490 */ 9491 public void setTransitionVisibility(@Visibility int visibility) { 9492 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9493 } 9494 9495 /** 9496 * Reset the flag indicating the accessibility state of the subtree rooted 9497 * at this view changed. 9498 */ 9499 void resetSubtreeAccessibilityStateChanged() { 9500 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9501 } 9502 9503 /** 9504 * Report an accessibility action to this view's parents for delegated processing. 9505 * 9506 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9507 * call this method to delegate an accessibility action to a supporting parent. If the parent 9508 * returns true from its 9509 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9510 * method this method will return true to signify that the action was consumed.</p> 9511 * 9512 * <p>This method is useful for implementing nested scrolling child views. If 9513 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9514 * a custom view implementation may invoke this method to allow a parent to consume the 9515 * scroll first. If this method returns true the custom view should skip its own scrolling 9516 * behavior.</p> 9517 * 9518 * @param action Accessibility action to delegate 9519 * @param arguments Optional action arguments 9520 * @return true if the action was consumed by a parent 9521 */ 9522 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9523 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9524 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9525 return true; 9526 } 9527 } 9528 return false; 9529 } 9530 9531 /** 9532 * Performs the specified accessibility action on the view. For 9533 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9534 * <p> 9535 * If an {@link AccessibilityDelegate} has been specified via calling 9536 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9537 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9538 * is responsible for handling this call. 9539 * </p> 9540 * 9541 * <p>The default implementation will delegate 9542 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9543 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9544 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9545 * 9546 * @param action The action to perform. 9547 * @param arguments Optional action arguments. 9548 * @return Whether the action was performed. 9549 */ 9550 public boolean performAccessibilityAction(int action, Bundle arguments) { 9551 if (mAccessibilityDelegate != null) { 9552 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9553 } else { 9554 return performAccessibilityActionInternal(action, arguments); 9555 } 9556 } 9557 9558 /** 9559 * @see #performAccessibilityAction(int, Bundle) 9560 * 9561 * Note: Called from the default {@link AccessibilityDelegate}. 9562 * 9563 * @hide 9564 */ 9565 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9566 if (isNestedScrollingEnabled() 9567 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9568 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9569 || action == R.id.accessibilityActionScrollUp 9570 || action == R.id.accessibilityActionScrollLeft 9571 || action == R.id.accessibilityActionScrollDown 9572 || action == R.id.accessibilityActionScrollRight)) { 9573 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9574 return true; 9575 } 9576 } 9577 9578 switch (action) { 9579 case AccessibilityNodeInfo.ACTION_CLICK: { 9580 if (isClickable()) { 9581 performClick(); 9582 return true; 9583 } 9584 } break; 9585 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9586 if (isLongClickable()) { 9587 performLongClick(); 9588 return true; 9589 } 9590 } break; 9591 case AccessibilityNodeInfo.ACTION_FOCUS: { 9592 if (!hasFocus()) { 9593 // Get out of touch mode since accessibility 9594 // wants to move focus around. 9595 getViewRootImpl().ensureTouchMode(false); 9596 return requestFocus(); 9597 } 9598 } break; 9599 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9600 if (hasFocus()) { 9601 clearFocus(); 9602 return !isFocused(); 9603 } 9604 } break; 9605 case AccessibilityNodeInfo.ACTION_SELECT: { 9606 if (!isSelected()) { 9607 setSelected(true); 9608 return isSelected(); 9609 } 9610 } break; 9611 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9612 if (isSelected()) { 9613 setSelected(false); 9614 return !isSelected(); 9615 } 9616 } break; 9617 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9618 if (!isAccessibilityFocused()) { 9619 return requestAccessibilityFocus(); 9620 } 9621 } break; 9622 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9623 if (isAccessibilityFocused()) { 9624 clearAccessibilityFocus(); 9625 return true; 9626 } 9627 } break; 9628 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9629 if (arguments != null) { 9630 final int granularity = arguments.getInt( 9631 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9632 final boolean extendSelection = arguments.getBoolean( 9633 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9634 return traverseAtGranularity(granularity, true, extendSelection); 9635 } 9636 } break; 9637 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9638 if (arguments != null) { 9639 final int granularity = arguments.getInt( 9640 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9641 final boolean extendSelection = arguments.getBoolean( 9642 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9643 return traverseAtGranularity(granularity, false, extendSelection); 9644 } 9645 } break; 9646 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9647 CharSequence text = getIterableTextForAccessibility(); 9648 if (text == null) { 9649 return false; 9650 } 9651 final int start = (arguments != null) ? arguments.getInt( 9652 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9653 final int end = (arguments != null) ? arguments.getInt( 9654 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9655 // Only cursor position can be specified (selection length == 0) 9656 if ((getAccessibilitySelectionStart() != start 9657 || getAccessibilitySelectionEnd() != end) 9658 && (start == end)) { 9659 setAccessibilitySelection(start, end); 9660 notifyViewAccessibilityStateChangedIfNeeded( 9661 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9662 return true; 9663 } 9664 } break; 9665 case R.id.accessibilityActionShowOnScreen: { 9666 if (mAttachInfo != null) { 9667 final Rect r = mAttachInfo.mTmpInvalRect; 9668 getDrawingRect(r); 9669 return requestRectangleOnScreen(r, true); 9670 } 9671 } break; 9672 case R.id.accessibilityActionContextClick: { 9673 if (isContextClickable()) { 9674 performContextClick(); 9675 return true; 9676 } 9677 } break; 9678 } 9679 return false; 9680 } 9681 9682 private boolean traverseAtGranularity(int granularity, boolean forward, 9683 boolean extendSelection) { 9684 CharSequence text = getIterableTextForAccessibility(); 9685 if (text == null || text.length() == 0) { 9686 return false; 9687 } 9688 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9689 if (iterator == null) { 9690 return false; 9691 } 9692 int current = getAccessibilitySelectionEnd(); 9693 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9694 current = forward ? 0 : text.length(); 9695 } 9696 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9697 if (range == null) { 9698 return false; 9699 } 9700 final int segmentStart = range[0]; 9701 final int segmentEnd = range[1]; 9702 int selectionStart; 9703 int selectionEnd; 9704 if (extendSelection && isAccessibilitySelectionExtendable()) { 9705 selectionStart = getAccessibilitySelectionStart(); 9706 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9707 selectionStart = forward ? segmentStart : segmentEnd; 9708 } 9709 selectionEnd = forward ? segmentEnd : segmentStart; 9710 } else { 9711 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9712 } 9713 setAccessibilitySelection(selectionStart, selectionEnd); 9714 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9715 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9716 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9717 return true; 9718 } 9719 9720 /** 9721 * Gets the text reported for accessibility purposes. 9722 * 9723 * @return The accessibility text. 9724 * 9725 * @hide 9726 */ 9727 public CharSequence getIterableTextForAccessibility() { 9728 return getContentDescription(); 9729 } 9730 9731 /** 9732 * Gets whether accessibility selection can be extended. 9733 * 9734 * @return If selection is extensible. 9735 * 9736 * @hide 9737 */ 9738 public boolean isAccessibilitySelectionExtendable() { 9739 return false; 9740 } 9741 9742 /** 9743 * @hide 9744 */ 9745 public int getAccessibilitySelectionStart() { 9746 return mAccessibilityCursorPosition; 9747 } 9748 9749 /** 9750 * @hide 9751 */ 9752 public int getAccessibilitySelectionEnd() { 9753 return getAccessibilitySelectionStart(); 9754 } 9755 9756 /** 9757 * @hide 9758 */ 9759 public void setAccessibilitySelection(int start, int end) { 9760 if (start == end && end == mAccessibilityCursorPosition) { 9761 return; 9762 } 9763 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9764 mAccessibilityCursorPosition = start; 9765 } else { 9766 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9767 } 9768 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9769 } 9770 9771 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9772 int fromIndex, int toIndex) { 9773 if (mParent == null) { 9774 return; 9775 } 9776 AccessibilityEvent event = AccessibilityEvent.obtain( 9777 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9778 onInitializeAccessibilityEvent(event); 9779 onPopulateAccessibilityEvent(event); 9780 event.setFromIndex(fromIndex); 9781 event.setToIndex(toIndex); 9782 event.setAction(action); 9783 event.setMovementGranularity(granularity); 9784 mParent.requestSendAccessibilityEvent(this, event); 9785 } 9786 9787 /** 9788 * @hide 9789 */ 9790 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9791 switch (granularity) { 9792 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9793 CharSequence text = getIterableTextForAccessibility(); 9794 if (text != null && text.length() > 0) { 9795 CharacterTextSegmentIterator iterator = 9796 CharacterTextSegmentIterator.getInstance( 9797 mContext.getResources().getConfiguration().locale); 9798 iterator.initialize(text.toString()); 9799 return iterator; 9800 } 9801 } break; 9802 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9803 CharSequence text = getIterableTextForAccessibility(); 9804 if (text != null && text.length() > 0) { 9805 WordTextSegmentIterator iterator = 9806 WordTextSegmentIterator.getInstance( 9807 mContext.getResources().getConfiguration().locale); 9808 iterator.initialize(text.toString()); 9809 return iterator; 9810 } 9811 } break; 9812 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9813 CharSequence text = getIterableTextForAccessibility(); 9814 if (text != null && text.length() > 0) { 9815 ParagraphTextSegmentIterator iterator = 9816 ParagraphTextSegmentIterator.getInstance(); 9817 iterator.initialize(text.toString()); 9818 return iterator; 9819 } 9820 } break; 9821 } 9822 return null; 9823 } 9824 9825 /** 9826 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 9827 * and {@link #onFinishTemporaryDetach()}. 9828 * 9829 * <p>This method always returns {@code true} when called directly or indirectly from 9830 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 9831 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 9832 * <ul> 9833 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 9834 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 9835 * </ul> 9836 * </p> 9837 * 9838 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9839 * and {@link #onFinishTemporaryDetach()}. 9840 */ 9841 public final boolean isTemporarilyDetached() { 9842 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9843 } 9844 9845 /** 9846 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9847 * a container View. 9848 */ 9849 @CallSuper 9850 public void dispatchStartTemporaryDetach() { 9851 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9852 onStartTemporaryDetach(); 9853 } 9854 9855 /** 9856 * This is called when a container is going to temporarily detach a child, with 9857 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9858 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9859 * {@link #onDetachedFromWindow()} when the container is done. 9860 */ 9861 public void onStartTemporaryDetach() { 9862 removeUnsetPressCallback(); 9863 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9864 } 9865 9866 /** 9867 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9868 * a container View. 9869 */ 9870 @CallSuper 9871 public void dispatchFinishTemporaryDetach() { 9872 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9873 onFinishTemporaryDetach(); 9874 if (hasWindowFocus() && hasFocus()) { 9875 InputMethodManager.getInstance().focusIn(this); 9876 } 9877 } 9878 9879 /** 9880 * Called after {@link #onStartTemporaryDetach} when the container is done 9881 * changing the view. 9882 */ 9883 public void onFinishTemporaryDetach() { 9884 } 9885 9886 /** 9887 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9888 * for this view's window. Returns null if the view is not currently attached 9889 * to the window. Normally you will not need to use this directly, but 9890 * just use the standard high-level event callbacks like 9891 * {@link #onKeyDown(int, KeyEvent)}. 9892 */ 9893 public KeyEvent.DispatcherState getKeyDispatcherState() { 9894 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9895 } 9896 9897 /** 9898 * Dispatch a key event before it is processed by any input method 9899 * associated with the view hierarchy. This can be used to intercept 9900 * key events in special situations before the IME consumes them; a 9901 * typical example would be handling the BACK key to update the application's 9902 * UI instead of allowing the IME to see it and close itself. 9903 * 9904 * @param event The key event to be dispatched. 9905 * @return True if the event was handled, false otherwise. 9906 */ 9907 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9908 return onKeyPreIme(event.getKeyCode(), event); 9909 } 9910 9911 /** 9912 * Dispatch a key event to the next view on the focus path. This path runs 9913 * from the top of the view tree down to the currently focused view. If this 9914 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9915 * the next node down the focus path. This method also fires any key 9916 * listeners. 9917 * 9918 * @param event The key event to be dispatched. 9919 * @return True if the event was handled, false otherwise. 9920 */ 9921 public boolean dispatchKeyEvent(KeyEvent event) { 9922 if (mInputEventConsistencyVerifier != null) { 9923 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9924 } 9925 9926 // Give any attached key listener a first crack at the event. 9927 //noinspection SimplifiableIfStatement 9928 ListenerInfo li = mListenerInfo; 9929 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9930 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9931 return true; 9932 } 9933 9934 if (event.dispatch(this, mAttachInfo != null 9935 ? mAttachInfo.mKeyDispatchState : null, this)) { 9936 return true; 9937 } 9938 9939 if (mInputEventConsistencyVerifier != null) { 9940 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9941 } 9942 return false; 9943 } 9944 9945 /** 9946 * Dispatches a key shortcut event. 9947 * 9948 * @param event The key event to be dispatched. 9949 * @return True if the event was handled by the view, false otherwise. 9950 */ 9951 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9952 return onKeyShortcut(event.getKeyCode(), event); 9953 } 9954 9955 /** 9956 * Pass the touch screen motion event down to the target view, or this 9957 * view if it is the target. 9958 * 9959 * @param event The motion event to be dispatched. 9960 * @return True if the event was handled by the view, false otherwise. 9961 */ 9962 public boolean dispatchTouchEvent(MotionEvent event) { 9963 // If the event should be handled by accessibility focus first. 9964 if (event.isTargetAccessibilityFocus()) { 9965 // We don't have focus or no virtual descendant has it, do not handle the event. 9966 if (!isAccessibilityFocusedViewOrHost()) { 9967 return false; 9968 } 9969 // We have focus and got the event, then use normal event dispatch. 9970 event.setTargetAccessibilityFocus(false); 9971 } 9972 9973 boolean result = false; 9974 9975 if (mInputEventConsistencyVerifier != null) { 9976 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9977 } 9978 9979 final int actionMasked = event.getActionMasked(); 9980 if (actionMasked == MotionEvent.ACTION_DOWN) { 9981 // Defensive cleanup for new gesture 9982 stopNestedScroll(); 9983 } 9984 9985 if (onFilterTouchEventForSecurity(event)) { 9986 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9987 result = true; 9988 } 9989 //noinspection SimplifiableIfStatement 9990 ListenerInfo li = mListenerInfo; 9991 if (li != null && li.mOnTouchListener != null 9992 && (mViewFlags & ENABLED_MASK) == ENABLED 9993 && li.mOnTouchListener.onTouch(this, event)) { 9994 result = true; 9995 } 9996 9997 if (!result && onTouchEvent(event)) { 9998 result = true; 9999 } 10000 } 10001 10002 if (!result && mInputEventConsistencyVerifier != null) { 10003 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10004 } 10005 10006 // Clean up after nested scrolls if this is the end of a gesture; 10007 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 10008 // of the gesture. 10009 if (actionMasked == MotionEvent.ACTION_UP || 10010 actionMasked == MotionEvent.ACTION_CANCEL || 10011 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 10012 stopNestedScroll(); 10013 } 10014 10015 return result; 10016 } 10017 10018 boolean isAccessibilityFocusedViewOrHost() { 10019 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 10020 .getAccessibilityFocusedHost() == this); 10021 } 10022 10023 /** 10024 * Filter the touch event to apply security policies. 10025 * 10026 * @param event The motion event to be filtered. 10027 * @return True if the event should be dispatched, false if the event should be dropped. 10028 * 10029 * @see #getFilterTouchesWhenObscured 10030 */ 10031 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 10032 //noinspection RedundantIfStatement 10033 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 10034 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 10035 // Window is obscured, drop this touch. 10036 return false; 10037 } 10038 return true; 10039 } 10040 10041 /** 10042 * Pass a trackball motion event down to the focused view. 10043 * 10044 * @param event The motion event to be dispatched. 10045 * @return True if the event was handled by the view, false otherwise. 10046 */ 10047 public boolean dispatchTrackballEvent(MotionEvent event) { 10048 if (mInputEventConsistencyVerifier != null) { 10049 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 10050 } 10051 10052 return onTrackballEvent(event); 10053 } 10054 10055 /** 10056 * Dispatch a generic motion event. 10057 * <p> 10058 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10059 * are delivered to the view under the pointer. All other generic motion events are 10060 * delivered to the focused view. Hover events are handled specially and are delivered 10061 * to {@link #onHoverEvent(MotionEvent)}. 10062 * </p> 10063 * 10064 * @param event The motion event to be dispatched. 10065 * @return True if the event was handled by the view, false otherwise. 10066 */ 10067 public boolean dispatchGenericMotionEvent(MotionEvent event) { 10068 if (mInputEventConsistencyVerifier != null) { 10069 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10070 } 10071 10072 final int source = event.getSource(); 10073 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10074 final int action = event.getAction(); 10075 if (action == MotionEvent.ACTION_HOVER_ENTER 10076 || action == MotionEvent.ACTION_HOVER_MOVE 10077 || action == MotionEvent.ACTION_HOVER_EXIT) { 10078 if (dispatchHoverEvent(event)) { 10079 return true; 10080 } 10081 } else if (dispatchGenericPointerEvent(event)) { 10082 return true; 10083 } 10084 } else if (dispatchGenericFocusedEvent(event)) { 10085 return true; 10086 } 10087 10088 if (dispatchGenericMotionEventInternal(event)) { 10089 return true; 10090 } 10091 10092 if (mInputEventConsistencyVerifier != null) { 10093 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10094 } 10095 return false; 10096 } 10097 10098 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10099 //noinspection SimplifiableIfStatement 10100 ListenerInfo li = mListenerInfo; 10101 if (li != null && li.mOnGenericMotionListener != null 10102 && (mViewFlags & ENABLED_MASK) == ENABLED 10103 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10104 return true; 10105 } 10106 10107 if (onGenericMotionEvent(event)) { 10108 return true; 10109 } 10110 10111 final int actionButton = event.getActionButton(); 10112 switch (event.getActionMasked()) { 10113 case MotionEvent.ACTION_BUTTON_PRESS: 10114 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10115 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10116 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10117 if (performContextClick(event.getX(), event.getY())) { 10118 mInContextButtonPress = true; 10119 setPressed(true, event.getX(), event.getY()); 10120 removeTapCallback(); 10121 removeLongPressCallback(); 10122 return true; 10123 } 10124 } 10125 break; 10126 10127 case MotionEvent.ACTION_BUTTON_RELEASE: 10128 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10129 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10130 mInContextButtonPress = false; 10131 mIgnoreNextUpEvent = true; 10132 } 10133 break; 10134 } 10135 10136 if (mInputEventConsistencyVerifier != null) { 10137 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10138 } 10139 return false; 10140 } 10141 10142 /** 10143 * Dispatch a hover event. 10144 * <p> 10145 * Do not call this method directly. 10146 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10147 * </p> 10148 * 10149 * @param event The motion event to be dispatched. 10150 * @return True if the event was handled by the view, false otherwise. 10151 */ 10152 protected boolean dispatchHoverEvent(MotionEvent event) { 10153 ListenerInfo li = mListenerInfo; 10154 //noinspection SimplifiableIfStatement 10155 if (li != null && li.mOnHoverListener != null 10156 && (mViewFlags & ENABLED_MASK) == ENABLED 10157 && li.mOnHoverListener.onHover(this, event)) { 10158 return true; 10159 } 10160 10161 return onHoverEvent(event); 10162 } 10163 10164 /** 10165 * Returns true if the view has a child to which it has recently sent 10166 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10167 * it does not have a hovered child, then it must be the innermost hovered view. 10168 * @hide 10169 */ 10170 protected boolean hasHoveredChild() { 10171 return false; 10172 } 10173 10174 /** 10175 * Dispatch a generic motion event to the view under the first pointer. 10176 * <p> 10177 * Do not call this method directly. 10178 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10179 * </p> 10180 * 10181 * @param event The motion event to be dispatched. 10182 * @return True if the event was handled by the view, false otherwise. 10183 */ 10184 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10185 return false; 10186 } 10187 10188 /** 10189 * Dispatch a generic motion event to the currently focused view. 10190 * <p> 10191 * Do not call this method directly. 10192 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10193 * </p> 10194 * 10195 * @param event The motion event to be dispatched. 10196 * @return True if the event was handled by the view, false otherwise. 10197 */ 10198 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10199 return false; 10200 } 10201 10202 /** 10203 * Dispatch a pointer event. 10204 * <p> 10205 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10206 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10207 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10208 * and should not be expected to handle other pointing device features. 10209 * </p> 10210 * 10211 * @param event The motion event to be dispatched. 10212 * @return True if the event was handled by the view, false otherwise. 10213 * @hide 10214 */ 10215 public final boolean dispatchPointerEvent(MotionEvent event) { 10216 if (event.isTouchEvent()) { 10217 return dispatchTouchEvent(event); 10218 } else { 10219 return dispatchGenericMotionEvent(event); 10220 } 10221 } 10222 10223 /** 10224 * Called when the window containing this view gains or loses window focus. 10225 * ViewGroups should override to route to their children. 10226 * 10227 * @param hasFocus True if the window containing this view now has focus, 10228 * false otherwise. 10229 */ 10230 public void dispatchWindowFocusChanged(boolean hasFocus) { 10231 onWindowFocusChanged(hasFocus); 10232 } 10233 10234 /** 10235 * Called when the window containing this view gains or loses focus. Note 10236 * that this is separate from view focus: to receive key events, both 10237 * your view and its window must have focus. If a window is displayed 10238 * on top of yours that takes input focus, then your own window will lose 10239 * focus but the view focus will remain unchanged. 10240 * 10241 * @param hasWindowFocus True if the window containing this view now has 10242 * focus, false otherwise. 10243 */ 10244 public void onWindowFocusChanged(boolean hasWindowFocus) { 10245 InputMethodManager imm = InputMethodManager.peekInstance(); 10246 if (!hasWindowFocus) { 10247 if (isPressed()) { 10248 setPressed(false); 10249 } 10250 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10251 imm.focusOut(this); 10252 } 10253 removeLongPressCallback(); 10254 removeTapCallback(); 10255 onFocusLost(); 10256 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10257 imm.focusIn(this); 10258 } 10259 refreshDrawableState(); 10260 } 10261 10262 /** 10263 * Returns true if this view is in a window that currently has window focus. 10264 * Note that this is not the same as the view itself having focus. 10265 * 10266 * @return True if this view is in a window that currently has window focus. 10267 */ 10268 public boolean hasWindowFocus() { 10269 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10270 } 10271 10272 /** 10273 * Dispatch a view visibility change down the view hierarchy. 10274 * ViewGroups should override to route to their children. 10275 * @param changedView The view whose visibility changed. Could be 'this' or 10276 * an ancestor view. 10277 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10278 * {@link #INVISIBLE} or {@link #GONE}. 10279 */ 10280 protected void dispatchVisibilityChanged(@NonNull View changedView, 10281 @Visibility int visibility) { 10282 onVisibilityChanged(changedView, visibility); 10283 } 10284 10285 /** 10286 * Called when the visibility of the view or an ancestor of the view has 10287 * changed. 10288 * 10289 * @param changedView The view whose visibility changed. May be 10290 * {@code this} or an ancestor view. 10291 * @param visibility The new visibility, one of {@link #VISIBLE}, 10292 * {@link #INVISIBLE} or {@link #GONE}. 10293 */ 10294 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10295 } 10296 10297 /** 10298 * Dispatch a hint about whether this view is displayed. For instance, when 10299 * a View moves out of the screen, it might receives a display hint indicating 10300 * the view is not displayed. Applications should not <em>rely</em> on this hint 10301 * as there is no guarantee that they will receive one. 10302 * 10303 * @param hint A hint about whether or not this view is displayed: 10304 * {@link #VISIBLE} or {@link #INVISIBLE}. 10305 */ 10306 public void dispatchDisplayHint(@Visibility int hint) { 10307 onDisplayHint(hint); 10308 } 10309 10310 /** 10311 * Gives this view a hint about whether is displayed or not. For instance, when 10312 * a View moves out of the screen, it might receives a display hint indicating 10313 * the view is not displayed. Applications should not <em>rely</em> on this hint 10314 * as there is no guarantee that they will receive one. 10315 * 10316 * @param hint A hint about whether or not this view is displayed: 10317 * {@link #VISIBLE} or {@link #INVISIBLE}. 10318 */ 10319 protected void onDisplayHint(@Visibility int hint) { 10320 } 10321 10322 /** 10323 * Dispatch a window visibility change down the view hierarchy. 10324 * ViewGroups should override to route to their children. 10325 * 10326 * @param visibility The new visibility of the window. 10327 * 10328 * @see #onWindowVisibilityChanged(int) 10329 */ 10330 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10331 onWindowVisibilityChanged(visibility); 10332 } 10333 10334 /** 10335 * Called when the window containing has change its visibility 10336 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10337 * that this tells you whether or not your window is being made visible 10338 * to the window manager; this does <em>not</em> tell you whether or not 10339 * your window is obscured by other windows on the screen, even if it 10340 * is itself visible. 10341 * 10342 * @param visibility The new visibility of the window. 10343 */ 10344 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10345 if (visibility == VISIBLE) { 10346 initialAwakenScrollBars(); 10347 } 10348 } 10349 10350 /** 10351 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10352 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10353 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10354 * 10355 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10356 * ancestors or by window visibility 10357 * @return true if this view is visible to the user, not counting clipping or overlapping 10358 */ 10359 boolean dispatchVisibilityAggregated(boolean isVisible) { 10360 final boolean thisVisible = getVisibility() == VISIBLE; 10361 // If we're not visible but something is telling us we are, ignore it. 10362 if (thisVisible || !isVisible) { 10363 onVisibilityAggregated(isVisible); 10364 } 10365 return thisVisible && isVisible; 10366 } 10367 10368 /** 10369 * Called when the user-visibility of this View is potentially affected by a change 10370 * to this view itself, an ancestor view or the window this view is attached to. 10371 * 10372 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10373 * and this view's window is also visible 10374 */ 10375 @CallSuper 10376 public void onVisibilityAggregated(boolean isVisible) { 10377 if (isVisible && mAttachInfo != null) { 10378 initialAwakenScrollBars(); 10379 } 10380 10381 final Drawable dr = mBackground; 10382 if (dr != null && isVisible != dr.isVisible()) { 10383 dr.setVisible(isVisible, false); 10384 } 10385 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10386 if (fg != null && isVisible != fg.isVisible()) { 10387 fg.setVisible(isVisible, false); 10388 } 10389 } 10390 10391 /** 10392 * Returns the current visibility of the window this view is attached to 10393 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10394 * 10395 * @return Returns the current visibility of the view's window. 10396 */ 10397 @Visibility 10398 public int getWindowVisibility() { 10399 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10400 } 10401 10402 /** 10403 * Retrieve the overall visible display size in which the window this view is 10404 * attached to has been positioned in. This takes into account screen 10405 * decorations above the window, for both cases where the window itself 10406 * is being position inside of them or the window is being placed under 10407 * then and covered insets are used for the window to position its content 10408 * inside. In effect, this tells you the available area where content can 10409 * be placed and remain visible to users. 10410 * 10411 * <p>This function requires an IPC back to the window manager to retrieve 10412 * the requested information, so should not be used in performance critical 10413 * code like drawing. 10414 * 10415 * @param outRect Filled in with the visible display frame. If the view 10416 * is not attached to a window, this is simply the raw display size. 10417 */ 10418 public void getWindowVisibleDisplayFrame(Rect outRect) { 10419 if (mAttachInfo != null) { 10420 try { 10421 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10422 } catch (RemoteException e) { 10423 return; 10424 } 10425 // XXX This is really broken, and probably all needs to be done 10426 // in the window manager, and we need to know more about whether 10427 // we want the area behind or in front of the IME. 10428 final Rect insets = mAttachInfo.mVisibleInsets; 10429 outRect.left += insets.left; 10430 outRect.top += insets.top; 10431 outRect.right -= insets.right; 10432 outRect.bottom -= insets.bottom; 10433 return; 10434 } 10435 // The view is not attached to a display so we don't have a context. 10436 // Make a best guess about the display size. 10437 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10438 d.getRectSize(outRect); 10439 } 10440 10441 /** 10442 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10443 * is currently in without any insets. 10444 * 10445 * @hide 10446 */ 10447 public void getWindowDisplayFrame(Rect outRect) { 10448 if (mAttachInfo != null) { 10449 try { 10450 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10451 } catch (RemoteException e) { 10452 return; 10453 } 10454 return; 10455 } 10456 // The view is not attached to a display so we don't have a context. 10457 // Make a best guess about the display size. 10458 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10459 d.getRectSize(outRect); 10460 } 10461 10462 /** 10463 * Dispatch a notification about a resource configuration change down 10464 * the view hierarchy. 10465 * ViewGroups should override to route to their children. 10466 * 10467 * @param newConfig The new resource configuration. 10468 * 10469 * @see #onConfigurationChanged(android.content.res.Configuration) 10470 */ 10471 public void dispatchConfigurationChanged(Configuration newConfig) { 10472 onConfigurationChanged(newConfig); 10473 } 10474 10475 /** 10476 * Called when the current configuration of the resources being used 10477 * by the application have changed. You can use this to decide when 10478 * to reload resources that can changed based on orientation and other 10479 * configuration characteristics. You only need to use this if you are 10480 * not relying on the normal {@link android.app.Activity} mechanism of 10481 * recreating the activity instance upon a configuration change. 10482 * 10483 * @param newConfig The new resource configuration. 10484 */ 10485 protected void onConfigurationChanged(Configuration newConfig) { 10486 } 10487 10488 /** 10489 * Private function to aggregate all per-view attributes in to the view 10490 * root. 10491 */ 10492 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10493 performCollectViewAttributes(attachInfo, visibility); 10494 } 10495 10496 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10497 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10498 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10499 attachInfo.mKeepScreenOn = true; 10500 } 10501 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10502 ListenerInfo li = mListenerInfo; 10503 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10504 attachInfo.mHasSystemUiListeners = true; 10505 } 10506 } 10507 } 10508 10509 void needGlobalAttributesUpdate(boolean force) { 10510 final AttachInfo ai = mAttachInfo; 10511 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10512 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10513 || ai.mHasSystemUiListeners) { 10514 ai.mRecomputeGlobalAttributes = true; 10515 } 10516 } 10517 } 10518 10519 /** 10520 * Returns whether the device is currently in touch mode. Touch mode is entered 10521 * once the user begins interacting with the device by touch, and affects various 10522 * things like whether focus is always visible to the user. 10523 * 10524 * @return Whether the device is in touch mode. 10525 */ 10526 @ViewDebug.ExportedProperty 10527 public boolean isInTouchMode() { 10528 if (mAttachInfo != null) { 10529 return mAttachInfo.mInTouchMode; 10530 } else { 10531 return ViewRootImpl.isInTouchMode(); 10532 } 10533 } 10534 10535 /** 10536 * Returns the context the view is running in, through which it can 10537 * access the current theme, resources, etc. 10538 * 10539 * @return The view's Context. 10540 */ 10541 @ViewDebug.CapturedViewProperty 10542 public final Context getContext() { 10543 return mContext; 10544 } 10545 10546 /** 10547 * Handle a key event before it is processed by any input method 10548 * associated with the view hierarchy. This can be used to intercept 10549 * key events in special situations before the IME consumes them; a 10550 * typical example would be handling the BACK key to update the application's 10551 * UI instead of allowing the IME to see it and close itself. 10552 * 10553 * @param keyCode The value in event.getKeyCode(). 10554 * @param event Description of the key event. 10555 * @return If you handled the event, return true. If you want to allow the 10556 * event to be handled by the next receiver, return false. 10557 */ 10558 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10559 return false; 10560 } 10561 10562 /** 10563 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10564 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10565 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10566 * is released, if the view is enabled and clickable. 10567 * <p> 10568 * Key presses in software keyboards will generally NOT trigger this 10569 * listener, although some may elect to do so in some situations. Do not 10570 * rely on this to catch software key presses. 10571 * 10572 * @param keyCode a key code that represents the button pressed, from 10573 * {@link android.view.KeyEvent} 10574 * @param event the KeyEvent object that defines the button action 10575 */ 10576 public boolean onKeyDown(int keyCode, KeyEvent event) { 10577 if (KeyEvent.isConfirmKey(keyCode)) { 10578 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10579 return true; 10580 } 10581 10582 // Long clickable items don't necessarily have to be clickable. 10583 if (((mViewFlags & CLICKABLE) == CLICKABLE 10584 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10585 && (event.getRepeatCount() == 0)) { 10586 // For the purposes of menu anchoring and drawable hotspots, 10587 // key events are considered to be at the center of the view. 10588 final float x = getWidth() / 2f; 10589 final float y = getHeight() / 2f; 10590 setPressed(true, x, y); 10591 checkForLongClick(0, x, y); 10592 return true; 10593 } 10594 } 10595 10596 return false; 10597 } 10598 10599 /** 10600 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10601 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10602 * the event). 10603 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10604 * although some may elect to do so in some situations. Do not rely on this to 10605 * catch software key presses. 10606 */ 10607 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10608 return false; 10609 } 10610 10611 /** 10612 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10613 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10614 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10615 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10616 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10617 * although some may elect to do so in some situations. Do not rely on this to 10618 * catch software key presses. 10619 * 10620 * @param keyCode A key code that represents the button pressed, from 10621 * {@link android.view.KeyEvent}. 10622 * @param event The KeyEvent object that defines the button action. 10623 */ 10624 public boolean onKeyUp(int keyCode, KeyEvent event) { 10625 if (KeyEvent.isConfirmKey(keyCode)) { 10626 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10627 return true; 10628 } 10629 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10630 setPressed(false); 10631 10632 if (!mHasPerformedLongPress) { 10633 // This is a tap, so remove the longpress check 10634 removeLongPressCallback(); 10635 return performClick(); 10636 } 10637 } 10638 } 10639 return false; 10640 } 10641 10642 /** 10643 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10644 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10645 * the event). 10646 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10647 * although some may elect to do so in some situations. Do not rely on this to 10648 * catch software key presses. 10649 * 10650 * @param keyCode A key code that represents the button pressed, from 10651 * {@link android.view.KeyEvent}. 10652 * @param repeatCount The number of times the action was made. 10653 * @param event The KeyEvent object that defines the button action. 10654 */ 10655 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10656 return false; 10657 } 10658 10659 /** 10660 * Called on the focused view when a key shortcut event is not handled. 10661 * Override this method to implement local key shortcuts for the View. 10662 * Key shortcuts can also be implemented by setting the 10663 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10664 * 10665 * @param keyCode The value in event.getKeyCode(). 10666 * @param event Description of the key event. 10667 * @return If you handled the event, return true. If you want to allow the 10668 * event to be handled by the next receiver, return false. 10669 */ 10670 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10671 return false; 10672 } 10673 10674 /** 10675 * Check whether the called view is a text editor, in which case it 10676 * would make sense to automatically display a soft input window for 10677 * it. Subclasses should override this if they implement 10678 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10679 * a call on that method would return a non-null InputConnection, and 10680 * they are really a first-class editor that the user would normally 10681 * start typing on when the go into a window containing your view. 10682 * 10683 * <p>The default implementation always returns false. This does 10684 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10685 * will not be called or the user can not otherwise perform edits on your 10686 * view; it is just a hint to the system that this is not the primary 10687 * purpose of this view. 10688 * 10689 * @return Returns true if this view is a text editor, else false. 10690 */ 10691 public boolean onCheckIsTextEditor() { 10692 return false; 10693 } 10694 10695 /** 10696 * Create a new InputConnection for an InputMethod to interact 10697 * with the view. The default implementation returns null, since it doesn't 10698 * support input methods. You can override this to implement such support. 10699 * This is only needed for views that take focus and text input. 10700 * 10701 * <p>When implementing this, you probably also want to implement 10702 * {@link #onCheckIsTextEditor()} to indicate you will return a 10703 * non-null InputConnection.</p> 10704 * 10705 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10706 * object correctly and in its entirety, so that the connected IME can rely 10707 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10708 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10709 * must be filled in with the correct cursor position for IMEs to work correctly 10710 * with your application.</p> 10711 * 10712 * @param outAttrs Fill in with attribute information about the connection. 10713 */ 10714 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10715 return null; 10716 } 10717 10718 /** 10719 * Called by the {@link android.view.inputmethod.InputMethodManager} 10720 * when a view who is not the current 10721 * input connection target is trying to make a call on the manager. The 10722 * default implementation returns false; you can override this to return 10723 * true for certain views if you are performing InputConnection proxying 10724 * to them. 10725 * @param view The View that is making the InputMethodManager call. 10726 * @return Return true to allow the call, false to reject. 10727 */ 10728 public boolean checkInputConnectionProxy(View view) { 10729 return false; 10730 } 10731 10732 /** 10733 * Show the context menu for this view. It is not safe to hold on to the 10734 * menu after returning from this method. 10735 * 10736 * You should normally not overload this method. Overload 10737 * {@link #onCreateContextMenu(ContextMenu)} or define an 10738 * {@link OnCreateContextMenuListener} to add items to the context menu. 10739 * 10740 * @param menu The context menu to populate 10741 */ 10742 public void createContextMenu(ContextMenu menu) { 10743 ContextMenuInfo menuInfo = getContextMenuInfo(); 10744 10745 // Sets the current menu info so all items added to menu will have 10746 // my extra info set. 10747 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10748 10749 onCreateContextMenu(menu); 10750 ListenerInfo li = mListenerInfo; 10751 if (li != null && li.mOnCreateContextMenuListener != null) { 10752 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10753 } 10754 10755 // Clear the extra information so subsequent items that aren't mine don't 10756 // have my extra info. 10757 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10758 10759 if (mParent != null) { 10760 mParent.createContextMenu(menu); 10761 } 10762 } 10763 10764 /** 10765 * Views should implement this if they have extra information to associate 10766 * with the context menu. The return result is supplied as a parameter to 10767 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10768 * callback. 10769 * 10770 * @return Extra information about the item for which the context menu 10771 * should be shown. This information will vary across different 10772 * subclasses of View. 10773 */ 10774 protected ContextMenuInfo getContextMenuInfo() { 10775 return null; 10776 } 10777 10778 /** 10779 * Views should implement this if the view itself is going to add items to 10780 * the context menu. 10781 * 10782 * @param menu the context menu to populate 10783 */ 10784 protected void onCreateContextMenu(ContextMenu menu) { 10785 } 10786 10787 /** 10788 * Implement this method to handle trackball motion events. The 10789 * <em>relative</em> movement of the trackball since the last event 10790 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10791 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10792 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10793 * they will often be fractional values, representing the more fine-grained 10794 * movement information available from a trackball). 10795 * 10796 * @param event The motion event. 10797 * @return True if the event was handled, false otherwise. 10798 */ 10799 public boolean onTrackballEvent(MotionEvent event) { 10800 return false; 10801 } 10802 10803 /** 10804 * Implement this method to handle generic motion events. 10805 * <p> 10806 * Generic motion events describe joystick movements, mouse hovers, track pad 10807 * touches, scroll wheel movements and other input events. The 10808 * {@link MotionEvent#getSource() source} of the motion event specifies 10809 * the class of input that was received. Implementations of this method 10810 * must examine the bits in the source before processing the event. 10811 * The following code example shows how this is done. 10812 * </p><p> 10813 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10814 * are delivered to the view under the pointer. All other generic motion events are 10815 * delivered to the focused view. 10816 * </p> 10817 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10818 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10819 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10820 * // process the joystick movement... 10821 * return true; 10822 * } 10823 * } 10824 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10825 * switch (event.getAction()) { 10826 * case MotionEvent.ACTION_HOVER_MOVE: 10827 * // process the mouse hover movement... 10828 * return true; 10829 * case MotionEvent.ACTION_SCROLL: 10830 * // process the scroll wheel movement... 10831 * return true; 10832 * } 10833 * } 10834 * return super.onGenericMotionEvent(event); 10835 * }</pre> 10836 * 10837 * @param event The generic motion event being processed. 10838 * @return True if the event was handled, false otherwise. 10839 */ 10840 public boolean onGenericMotionEvent(MotionEvent event) { 10841 return false; 10842 } 10843 10844 /** 10845 * Implement this method to handle hover events. 10846 * <p> 10847 * This method is called whenever a pointer is hovering into, over, or out of the 10848 * bounds of a view and the view is not currently being touched. 10849 * Hover events are represented as pointer events with action 10850 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10851 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10852 * </p> 10853 * <ul> 10854 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10855 * when the pointer enters the bounds of the view.</li> 10856 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10857 * when the pointer has already entered the bounds of the view and has moved.</li> 10858 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10859 * when the pointer has exited the bounds of the view or when the pointer is 10860 * about to go down due to a button click, tap, or similar user action that 10861 * causes the view to be touched.</li> 10862 * </ul> 10863 * <p> 10864 * The view should implement this method to return true to indicate that it is 10865 * handling the hover event, such as by changing its drawable state. 10866 * </p><p> 10867 * The default implementation calls {@link #setHovered} to update the hovered state 10868 * of the view when a hover enter or hover exit event is received, if the view 10869 * is enabled and is clickable. The default implementation also sends hover 10870 * accessibility events. 10871 * </p> 10872 * 10873 * @param event The motion event that describes the hover. 10874 * @return True if the view handled the hover event. 10875 * 10876 * @see #isHovered 10877 * @see #setHovered 10878 * @see #onHoverChanged 10879 */ 10880 public boolean onHoverEvent(MotionEvent event) { 10881 // The root view may receive hover (or touch) events that are outside the bounds of 10882 // the window. This code ensures that we only send accessibility events for 10883 // hovers that are actually within the bounds of the root view. 10884 final int action = event.getActionMasked(); 10885 if (!mSendingHoverAccessibilityEvents) { 10886 if ((action == MotionEvent.ACTION_HOVER_ENTER 10887 || action == MotionEvent.ACTION_HOVER_MOVE) 10888 && !hasHoveredChild() 10889 && pointInView(event.getX(), event.getY())) { 10890 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10891 mSendingHoverAccessibilityEvents = true; 10892 } 10893 } else { 10894 if (action == MotionEvent.ACTION_HOVER_EXIT 10895 || (action == MotionEvent.ACTION_MOVE 10896 && !pointInView(event.getX(), event.getY()))) { 10897 mSendingHoverAccessibilityEvents = false; 10898 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10899 } 10900 } 10901 10902 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10903 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10904 && isOnScrollbar(event.getX(), event.getY())) { 10905 awakenScrollBars(); 10906 } 10907 if (isHoverable()) { 10908 switch (action) { 10909 case MotionEvent.ACTION_HOVER_ENTER: 10910 setHovered(true); 10911 break; 10912 case MotionEvent.ACTION_HOVER_EXIT: 10913 setHovered(false); 10914 break; 10915 } 10916 10917 // Dispatch the event to onGenericMotionEvent before returning true. 10918 // This is to provide compatibility with existing applications that 10919 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10920 // break because of the new default handling for hoverable views 10921 // in onHoverEvent. 10922 // Note that onGenericMotionEvent will be called by default when 10923 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10924 dispatchGenericMotionEventInternal(event); 10925 // The event was already handled by calling setHovered(), so always 10926 // return true. 10927 return true; 10928 } 10929 10930 return false; 10931 } 10932 10933 /** 10934 * Returns true if the view should handle {@link #onHoverEvent} 10935 * by calling {@link #setHovered} to change its hovered state. 10936 * 10937 * @return True if the view is hoverable. 10938 */ 10939 private boolean isHoverable() { 10940 final int viewFlags = mViewFlags; 10941 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10942 return false; 10943 } 10944 10945 return (viewFlags & CLICKABLE) == CLICKABLE 10946 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10947 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10948 } 10949 10950 /** 10951 * Returns true if the view is currently hovered. 10952 * 10953 * @return True if the view is currently hovered. 10954 * 10955 * @see #setHovered 10956 * @see #onHoverChanged 10957 */ 10958 @ViewDebug.ExportedProperty 10959 public boolean isHovered() { 10960 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10961 } 10962 10963 /** 10964 * Sets whether the view is currently hovered. 10965 * <p> 10966 * Calling this method also changes the drawable state of the view. This 10967 * enables the view to react to hover by using different drawable resources 10968 * to change its appearance. 10969 * </p><p> 10970 * The {@link #onHoverChanged} method is called when the hovered state changes. 10971 * </p> 10972 * 10973 * @param hovered True if the view is hovered. 10974 * 10975 * @see #isHovered 10976 * @see #onHoverChanged 10977 */ 10978 public void setHovered(boolean hovered) { 10979 if (hovered) { 10980 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10981 mPrivateFlags |= PFLAG_HOVERED; 10982 refreshDrawableState(); 10983 onHoverChanged(true); 10984 } 10985 } else { 10986 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10987 mPrivateFlags &= ~PFLAG_HOVERED; 10988 refreshDrawableState(); 10989 onHoverChanged(false); 10990 } 10991 } 10992 } 10993 10994 /** 10995 * Implement this method to handle hover state changes. 10996 * <p> 10997 * This method is called whenever the hover state changes as a result of a 10998 * call to {@link #setHovered}. 10999 * </p> 11000 * 11001 * @param hovered The current hover state, as returned by {@link #isHovered}. 11002 * 11003 * @see #isHovered 11004 * @see #setHovered 11005 */ 11006 public void onHoverChanged(boolean hovered) { 11007 } 11008 11009 /** 11010 * Handles scroll bar dragging by mouse input. 11011 * 11012 * @hide 11013 * @param event The motion event. 11014 * 11015 * @return true if the event was handled as a scroll bar dragging, false otherwise. 11016 */ 11017 protected boolean handleScrollBarDragging(MotionEvent event) { 11018 if (mScrollCache == null) { 11019 return false; 11020 } 11021 final float x = event.getX(); 11022 final float y = event.getY(); 11023 final int action = event.getAction(); 11024 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 11025 && action != MotionEvent.ACTION_DOWN) 11026 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 11027 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 11028 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11029 return false; 11030 } 11031 11032 switch (action) { 11033 case MotionEvent.ACTION_MOVE: 11034 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 11035 return false; 11036 } 11037 if (mScrollCache.mScrollBarDraggingState 11038 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 11039 final Rect bounds = mScrollCache.mScrollBarBounds; 11040 getVerticalScrollBarBounds(bounds); 11041 final int range = computeVerticalScrollRange(); 11042 final int offset = computeVerticalScrollOffset(); 11043 final int extent = computeVerticalScrollExtent(); 11044 11045 final int thumbLength = ScrollBarUtils.getThumbLength( 11046 bounds.height(), bounds.width(), extent, range); 11047 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11048 bounds.height(), thumbLength, extent, range, offset); 11049 11050 final float diff = y - mScrollCache.mScrollBarDraggingPos; 11051 final float maxThumbOffset = bounds.height() - thumbLength; 11052 final float newThumbOffset = 11053 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11054 final int height = getHeight(); 11055 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11056 && height > 0 && extent > 0) { 11057 final int newY = Math.round((range - extent) 11058 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 11059 if (newY != getScrollY()) { 11060 mScrollCache.mScrollBarDraggingPos = y; 11061 setScrollY(newY); 11062 } 11063 } 11064 return true; 11065 } 11066 if (mScrollCache.mScrollBarDraggingState 11067 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 11068 final Rect bounds = mScrollCache.mScrollBarBounds; 11069 getHorizontalScrollBarBounds(bounds); 11070 final int range = computeHorizontalScrollRange(); 11071 final int offset = computeHorizontalScrollOffset(); 11072 final int extent = computeHorizontalScrollExtent(); 11073 11074 final int thumbLength = ScrollBarUtils.getThumbLength( 11075 bounds.width(), bounds.height(), extent, range); 11076 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11077 bounds.width(), thumbLength, extent, range, offset); 11078 11079 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11080 final float maxThumbOffset = bounds.width() - thumbLength; 11081 final float newThumbOffset = 11082 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11083 final int width = getWidth(); 11084 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11085 && width > 0 && extent > 0) { 11086 final int newX = Math.round((range - extent) 11087 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11088 if (newX != getScrollX()) { 11089 mScrollCache.mScrollBarDraggingPos = x; 11090 setScrollX(newX); 11091 } 11092 } 11093 return true; 11094 } 11095 case MotionEvent.ACTION_DOWN: 11096 if (mScrollCache.state == ScrollabilityCache.OFF) { 11097 return false; 11098 } 11099 if (isOnVerticalScrollbarThumb(x, y)) { 11100 mScrollCache.mScrollBarDraggingState = 11101 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11102 mScrollCache.mScrollBarDraggingPos = y; 11103 return true; 11104 } 11105 if (isOnHorizontalScrollbarThumb(x, y)) { 11106 mScrollCache.mScrollBarDraggingState = 11107 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11108 mScrollCache.mScrollBarDraggingPos = x; 11109 return true; 11110 } 11111 } 11112 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11113 return false; 11114 } 11115 11116 /** 11117 * Implement this method to handle touch screen motion events. 11118 * <p> 11119 * If this method is used to detect click actions, it is recommended that 11120 * the actions be performed by implementing and calling 11121 * {@link #performClick()}. This will ensure consistent system behavior, 11122 * including: 11123 * <ul> 11124 * <li>obeying click sound preferences 11125 * <li>dispatching OnClickListener calls 11126 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11127 * accessibility features are enabled 11128 * </ul> 11129 * 11130 * @param event The motion event. 11131 * @return True if the event was handled, false otherwise. 11132 */ 11133 public boolean onTouchEvent(MotionEvent event) { 11134 final float x = event.getX(); 11135 final float y = event.getY(); 11136 final int viewFlags = mViewFlags; 11137 final int action = event.getAction(); 11138 11139 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11140 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11141 setPressed(false); 11142 } 11143 // A disabled view that is clickable still consumes the touch 11144 // events, it just doesn't respond to them. 11145 return (((viewFlags & CLICKABLE) == CLICKABLE 11146 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11147 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11148 } 11149 if (mTouchDelegate != null) { 11150 if (mTouchDelegate.onTouchEvent(event)) { 11151 return true; 11152 } 11153 } 11154 11155 if (((viewFlags & CLICKABLE) == CLICKABLE || 11156 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11157 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11158 switch (action) { 11159 case MotionEvent.ACTION_UP: 11160 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11161 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11162 // take focus if we don't have it already and we should in 11163 // touch mode. 11164 boolean focusTaken = false; 11165 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11166 focusTaken = requestFocus(); 11167 } 11168 11169 if (prepressed) { 11170 // The button is being released before we actually 11171 // showed it as pressed. Make it show the pressed 11172 // state now (before scheduling the click) to ensure 11173 // the user sees it. 11174 setPressed(true, x, y); 11175 } 11176 11177 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11178 // This is a tap, so remove the longpress check 11179 removeLongPressCallback(); 11180 11181 // Only perform take click actions if we were in the pressed state 11182 if (!focusTaken) { 11183 // Use a Runnable and post this rather than calling 11184 // performClick directly. This lets other visual state 11185 // of the view update before click actions start. 11186 if (mPerformClick == null) { 11187 mPerformClick = new PerformClick(); 11188 } 11189 if (!post(mPerformClick)) { 11190 performClick(); 11191 } 11192 } 11193 } 11194 11195 if (mUnsetPressedState == null) { 11196 mUnsetPressedState = new UnsetPressedState(); 11197 } 11198 11199 if (prepressed) { 11200 postDelayed(mUnsetPressedState, 11201 ViewConfiguration.getPressedStateDuration()); 11202 } else if (!post(mUnsetPressedState)) { 11203 // If the post failed, unpress right now 11204 mUnsetPressedState.run(); 11205 } 11206 11207 removeTapCallback(); 11208 } 11209 mIgnoreNextUpEvent = false; 11210 break; 11211 11212 case MotionEvent.ACTION_DOWN: 11213 mHasPerformedLongPress = false; 11214 11215 if (performButtonActionOnTouchDown(event)) { 11216 break; 11217 } 11218 11219 // Walk up the hierarchy to determine if we're inside a scrolling container. 11220 boolean isInScrollingContainer = isInScrollingContainer(); 11221 11222 // For views inside a scrolling container, delay the pressed feedback for 11223 // a short period in case this is a scroll. 11224 if (isInScrollingContainer) { 11225 mPrivateFlags |= PFLAG_PREPRESSED; 11226 if (mPendingCheckForTap == null) { 11227 mPendingCheckForTap = new CheckForTap(); 11228 } 11229 mPendingCheckForTap.x = event.getX(); 11230 mPendingCheckForTap.y = event.getY(); 11231 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11232 } else { 11233 // Not inside a scrolling container, so show the feedback right away 11234 setPressed(true, x, y); 11235 checkForLongClick(0, x, y); 11236 } 11237 break; 11238 11239 case MotionEvent.ACTION_CANCEL: 11240 setPressed(false); 11241 removeTapCallback(); 11242 removeLongPressCallback(); 11243 mInContextButtonPress = false; 11244 mHasPerformedLongPress = false; 11245 mIgnoreNextUpEvent = false; 11246 break; 11247 11248 case MotionEvent.ACTION_MOVE: 11249 drawableHotspotChanged(x, y); 11250 11251 // Be lenient about moving outside of buttons 11252 if (!pointInView(x, y, mTouchSlop)) { 11253 // Outside button 11254 removeTapCallback(); 11255 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11256 // Remove any future long press/tap checks 11257 removeLongPressCallback(); 11258 11259 setPressed(false); 11260 } 11261 } 11262 break; 11263 } 11264 11265 return true; 11266 } 11267 11268 return false; 11269 } 11270 11271 /** 11272 * @hide 11273 */ 11274 public boolean isInScrollingContainer() { 11275 ViewParent p = getParent(); 11276 while (p != null && p instanceof ViewGroup) { 11277 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11278 return true; 11279 } 11280 p = p.getParent(); 11281 } 11282 return false; 11283 } 11284 11285 /** 11286 * Remove the longpress detection timer. 11287 */ 11288 private void removeLongPressCallback() { 11289 if (mPendingCheckForLongPress != null) { 11290 removeCallbacks(mPendingCheckForLongPress); 11291 } 11292 } 11293 11294 /** 11295 * Remove the pending click action 11296 */ 11297 private void removePerformClickCallback() { 11298 if (mPerformClick != null) { 11299 removeCallbacks(mPerformClick); 11300 } 11301 } 11302 11303 /** 11304 * Remove the prepress detection timer. 11305 */ 11306 private void removeUnsetPressCallback() { 11307 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11308 setPressed(false); 11309 removeCallbacks(mUnsetPressedState); 11310 } 11311 } 11312 11313 /** 11314 * Remove the tap detection timer. 11315 */ 11316 private void removeTapCallback() { 11317 if (mPendingCheckForTap != null) { 11318 mPrivateFlags &= ~PFLAG_PREPRESSED; 11319 removeCallbacks(mPendingCheckForTap); 11320 } 11321 } 11322 11323 /** 11324 * Cancels a pending long press. Your subclass can use this if you 11325 * want the context menu to come up if the user presses and holds 11326 * at the same place, but you don't want it to come up if they press 11327 * and then move around enough to cause scrolling. 11328 */ 11329 public void cancelLongPress() { 11330 removeLongPressCallback(); 11331 11332 /* 11333 * The prepressed state handled by the tap callback is a display 11334 * construct, but the tap callback will post a long press callback 11335 * less its own timeout. Remove it here. 11336 */ 11337 removeTapCallback(); 11338 } 11339 11340 /** 11341 * Remove the pending callback for sending a 11342 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11343 */ 11344 private void removeSendViewScrolledAccessibilityEventCallback() { 11345 if (mSendViewScrolledAccessibilityEvent != null) { 11346 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11347 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11348 } 11349 } 11350 11351 /** 11352 * Sets the TouchDelegate for this View. 11353 */ 11354 public void setTouchDelegate(TouchDelegate delegate) { 11355 mTouchDelegate = delegate; 11356 } 11357 11358 /** 11359 * Gets the TouchDelegate for this View. 11360 */ 11361 public TouchDelegate getTouchDelegate() { 11362 return mTouchDelegate; 11363 } 11364 11365 /** 11366 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11367 * 11368 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11369 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11370 * available. This method should only be called for touch events. 11371 * 11372 * <p class="note">This api is not intended for most applications. Buffered dispatch 11373 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11374 * streams will not improve your input latency. Side effects include: increased latency, 11375 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11376 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11377 * you.</p> 11378 */ 11379 public final void requestUnbufferedDispatch(MotionEvent event) { 11380 final int action = event.getAction(); 11381 if (mAttachInfo == null 11382 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11383 || !event.isTouchEvent()) { 11384 return; 11385 } 11386 mAttachInfo.mUnbufferedDispatchRequested = true; 11387 } 11388 11389 /** 11390 * Set flags controlling behavior of this view. 11391 * 11392 * @param flags Constant indicating the value which should be set 11393 * @param mask Constant indicating the bit range that should be changed 11394 */ 11395 void setFlags(int flags, int mask) { 11396 final boolean accessibilityEnabled = 11397 AccessibilityManager.getInstance(mContext).isEnabled(); 11398 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11399 11400 int old = mViewFlags; 11401 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11402 11403 int changed = mViewFlags ^ old; 11404 if (changed == 0) { 11405 return; 11406 } 11407 int privateFlags = mPrivateFlags; 11408 11409 /* Check if the FOCUSABLE bit has changed */ 11410 if (((changed & FOCUSABLE_MASK) != 0) && 11411 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11412 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11413 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11414 /* Give up focus if we are no longer focusable */ 11415 clearFocus(); 11416 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11417 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11418 /* 11419 * Tell the view system that we are now available to take focus 11420 * if no one else already has it. 11421 */ 11422 if (mParent != null) mParent.focusableViewAvailable(this); 11423 } 11424 } 11425 11426 final int newVisibility = flags & VISIBILITY_MASK; 11427 if (newVisibility == VISIBLE) { 11428 if ((changed & VISIBILITY_MASK) != 0) { 11429 /* 11430 * If this view is becoming visible, invalidate it in case it changed while 11431 * it was not visible. Marking it drawn ensures that the invalidation will 11432 * go through. 11433 */ 11434 mPrivateFlags |= PFLAG_DRAWN; 11435 invalidate(true); 11436 11437 needGlobalAttributesUpdate(true); 11438 11439 // a view becoming visible is worth notifying the parent 11440 // about in case nothing has focus. even if this specific view 11441 // isn't focusable, it may contain something that is, so let 11442 // the root view try to give this focus if nothing else does. 11443 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11444 mParent.focusableViewAvailable(this); 11445 } 11446 } 11447 } 11448 11449 /* Check if the GONE bit has changed */ 11450 if ((changed & GONE) != 0) { 11451 needGlobalAttributesUpdate(false); 11452 requestLayout(); 11453 11454 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11455 if (hasFocus()) clearFocus(); 11456 clearAccessibilityFocus(); 11457 destroyDrawingCache(); 11458 if (mParent instanceof View) { 11459 // GONE views noop invalidation, so invalidate the parent 11460 ((View) mParent).invalidate(true); 11461 } 11462 // Mark the view drawn to ensure that it gets invalidated properly the next 11463 // time it is visible and gets invalidated 11464 mPrivateFlags |= PFLAG_DRAWN; 11465 } 11466 if (mAttachInfo != null) { 11467 mAttachInfo.mViewVisibilityChanged = true; 11468 } 11469 } 11470 11471 /* Check if the VISIBLE bit has changed */ 11472 if ((changed & INVISIBLE) != 0) { 11473 needGlobalAttributesUpdate(false); 11474 /* 11475 * If this view is becoming invisible, set the DRAWN flag so that 11476 * the next invalidate() will not be skipped. 11477 */ 11478 mPrivateFlags |= PFLAG_DRAWN; 11479 11480 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11481 // root view becoming invisible shouldn't clear focus and accessibility focus 11482 if (getRootView() != this) { 11483 if (hasFocus()) clearFocus(); 11484 clearAccessibilityFocus(); 11485 } 11486 } 11487 if (mAttachInfo != null) { 11488 mAttachInfo.mViewVisibilityChanged = true; 11489 } 11490 } 11491 11492 if ((changed & VISIBILITY_MASK) != 0) { 11493 // If the view is invisible, cleanup its display list to free up resources 11494 if (newVisibility != VISIBLE && mAttachInfo != null) { 11495 cleanupDraw(); 11496 } 11497 11498 if (mParent instanceof ViewGroup) { 11499 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11500 (changed & VISIBILITY_MASK), newVisibility); 11501 ((View) mParent).invalidate(true); 11502 } else if (mParent != null) { 11503 mParent.invalidateChild(this, null); 11504 } 11505 11506 if (mAttachInfo != null) { 11507 dispatchVisibilityChanged(this, newVisibility); 11508 11509 // Aggregated visibility changes are dispatched to attached views 11510 // in visible windows where the parent is currently shown/drawn 11511 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11512 // discounting clipping or overlapping. This makes it a good place 11513 // to change animation states. 11514 if (mParent != null && getWindowVisibility() == VISIBLE && 11515 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11516 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11517 } 11518 notifySubtreeAccessibilityStateChangedIfNeeded(); 11519 } 11520 } 11521 11522 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11523 destroyDrawingCache(); 11524 } 11525 11526 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11527 destroyDrawingCache(); 11528 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11529 invalidateParentCaches(); 11530 } 11531 11532 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11533 destroyDrawingCache(); 11534 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11535 } 11536 11537 if ((changed & DRAW_MASK) != 0) { 11538 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11539 if (mBackground != null 11540 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11541 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11542 } else { 11543 mPrivateFlags |= PFLAG_SKIP_DRAW; 11544 } 11545 } else { 11546 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11547 } 11548 requestLayout(); 11549 invalidate(true); 11550 } 11551 11552 if ((changed & KEEP_SCREEN_ON) != 0) { 11553 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11554 mParent.recomputeViewAttributes(this); 11555 } 11556 } 11557 11558 if (accessibilityEnabled) { 11559 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11560 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11561 || (changed & CONTEXT_CLICKABLE) != 0) { 11562 if (oldIncludeForAccessibility != includeForAccessibility()) { 11563 notifySubtreeAccessibilityStateChangedIfNeeded(); 11564 } else { 11565 notifyViewAccessibilityStateChangedIfNeeded( 11566 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11567 } 11568 } else if ((changed & ENABLED_MASK) != 0) { 11569 notifyViewAccessibilityStateChangedIfNeeded( 11570 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11571 } 11572 } 11573 } 11574 11575 /** 11576 * Change the view's z order in the tree, so it's on top of other sibling 11577 * views. This ordering change may affect layout, if the parent container 11578 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11579 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11580 * method should be followed by calls to {@link #requestLayout()} and 11581 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11582 * with the new child ordering. 11583 * 11584 * @see ViewGroup#bringChildToFront(View) 11585 */ 11586 public void bringToFront() { 11587 if (mParent != null) { 11588 mParent.bringChildToFront(this); 11589 } 11590 } 11591 11592 /** 11593 * This is called in response to an internal scroll in this view (i.e., the 11594 * view scrolled its own contents). This is typically as a result of 11595 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11596 * called. 11597 * 11598 * @param l Current horizontal scroll origin. 11599 * @param t Current vertical scroll origin. 11600 * @param oldl Previous horizontal scroll origin. 11601 * @param oldt Previous vertical scroll origin. 11602 */ 11603 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11604 notifySubtreeAccessibilityStateChangedIfNeeded(); 11605 11606 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11607 postSendViewScrolledAccessibilityEventCallback(); 11608 } 11609 11610 mBackgroundSizeChanged = true; 11611 if (mForegroundInfo != null) { 11612 mForegroundInfo.mBoundsChanged = true; 11613 } 11614 11615 final AttachInfo ai = mAttachInfo; 11616 if (ai != null) { 11617 ai.mViewScrollChanged = true; 11618 } 11619 11620 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11621 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11622 } 11623 } 11624 11625 /** 11626 * Interface definition for a callback to be invoked when the scroll 11627 * X or Y positions of a view change. 11628 * <p> 11629 * <b>Note:</b> Some views handle scrolling independently from View and may 11630 * have their own separate listeners for scroll-type events. For example, 11631 * {@link android.widget.ListView ListView} allows clients to register an 11632 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11633 * to listen for changes in list scroll position. 11634 * 11635 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11636 */ 11637 public interface OnScrollChangeListener { 11638 /** 11639 * Called when the scroll position of a view changes. 11640 * 11641 * @param v The view whose scroll position has changed. 11642 * @param scrollX Current horizontal scroll origin. 11643 * @param scrollY Current vertical scroll origin. 11644 * @param oldScrollX Previous horizontal scroll origin. 11645 * @param oldScrollY Previous vertical scroll origin. 11646 */ 11647 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11648 } 11649 11650 /** 11651 * Interface definition for a callback to be invoked when the layout bounds of a view 11652 * changes due to layout processing. 11653 */ 11654 public interface OnLayoutChangeListener { 11655 /** 11656 * Called when the layout bounds of a view changes due to layout processing. 11657 * 11658 * @param v The view whose bounds have changed. 11659 * @param left The new value of the view's left property. 11660 * @param top The new value of the view's top property. 11661 * @param right The new value of the view's right property. 11662 * @param bottom The new value of the view's bottom property. 11663 * @param oldLeft The previous value of the view's left property. 11664 * @param oldTop The previous value of the view's top property. 11665 * @param oldRight The previous value of the view's right property. 11666 * @param oldBottom The previous value of the view's bottom property. 11667 */ 11668 void onLayoutChange(View v, int left, int top, int right, int bottom, 11669 int oldLeft, int oldTop, int oldRight, int oldBottom); 11670 } 11671 11672 /** 11673 * This is called during layout when the size of this view has changed. If 11674 * you were just added to the view hierarchy, you're called with the old 11675 * values of 0. 11676 * 11677 * @param w Current width of this view. 11678 * @param h Current height of this view. 11679 * @param oldw Old width of this view. 11680 * @param oldh Old height of this view. 11681 */ 11682 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11683 } 11684 11685 /** 11686 * Called by draw to draw the child views. This may be overridden 11687 * by derived classes to gain control just before its children are drawn 11688 * (but after its own view has been drawn). 11689 * @param canvas the canvas on which to draw the view 11690 */ 11691 protected void dispatchDraw(Canvas canvas) { 11692 11693 } 11694 11695 /** 11696 * Gets the parent of this view. Note that the parent is a 11697 * ViewParent and not necessarily a View. 11698 * 11699 * @return Parent of this view. 11700 */ 11701 public final ViewParent getParent() { 11702 return mParent; 11703 } 11704 11705 /** 11706 * Set the horizontal scrolled position of your view. This will cause a call to 11707 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11708 * invalidated. 11709 * @param value the x position to scroll to 11710 */ 11711 public void setScrollX(int value) { 11712 scrollTo(value, mScrollY); 11713 } 11714 11715 /** 11716 * Set the vertical scrolled position of your view. This will cause a call to 11717 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11718 * invalidated. 11719 * @param value the y position to scroll to 11720 */ 11721 public void setScrollY(int value) { 11722 scrollTo(mScrollX, value); 11723 } 11724 11725 /** 11726 * Return the scrolled left position of this view. This is the left edge of 11727 * the displayed part of your view. You do not need to draw any pixels 11728 * farther left, since those are outside of the frame of your view on 11729 * screen. 11730 * 11731 * @return The left edge of the displayed part of your view, in pixels. 11732 */ 11733 public final int getScrollX() { 11734 return mScrollX; 11735 } 11736 11737 /** 11738 * Return the scrolled top position of this view. This is the top edge of 11739 * the displayed part of your view. You do not need to draw any pixels above 11740 * it, since those are outside of the frame of your view on screen. 11741 * 11742 * @return The top edge of the displayed part of your view, in pixels. 11743 */ 11744 public final int getScrollY() { 11745 return mScrollY; 11746 } 11747 11748 /** 11749 * Return the width of the your view. 11750 * 11751 * @return The width of your view, in pixels. 11752 */ 11753 @ViewDebug.ExportedProperty(category = "layout") 11754 public final int getWidth() { 11755 return mRight - mLeft; 11756 } 11757 11758 /** 11759 * Return the height of your view. 11760 * 11761 * @return The height of your view, in pixels. 11762 */ 11763 @ViewDebug.ExportedProperty(category = "layout") 11764 public final int getHeight() { 11765 return mBottom - mTop; 11766 } 11767 11768 /** 11769 * Return the visible drawing bounds of your view. Fills in the output 11770 * rectangle with the values from getScrollX(), getScrollY(), 11771 * getWidth(), and getHeight(). These bounds do not account for any 11772 * transformation properties currently set on the view, such as 11773 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11774 * 11775 * @param outRect The (scrolled) drawing bounds of the view. 11776 */ 11777 public void getDrawingRect(Rect outRect) { 11778 outRect.left = mScrollX; 11779 outRect.top = mScrollY; 11780 outRect.right = mScrollX + (mRight - mLeft); 11781 outRect.bottom = mScrollY + (mBottom - mTop); 11782 } 11783 11784 /** 11785 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11786 * raw width component (that is the result is masked by 11787 * {@link #MEASURED_SIZE_MASK}). 11788 * 11789 * @return The raw measured width of this view. 11790 */ 11791 public final int getMeasuredWidth() { 11792 return mMeasuredWidth & MEASURED_SIZE_MASK; 11793 } 11794 11795 /** 11796 * Return the full width measurement information for this view as computed 11797 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11798 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11799 * This should be used during measurement and layout calculations only. Use 11800 * {@link #getWidth()} to see how wide a view is after layout. 11801 * 11802 * @return The measured width of this view as a bit mask. 11803 */ 11804 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11805 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11806 name = "MEASURED_STATE_TOO_SMALL"), 11807 }) 11808 public final int getMeasuredWidthAndState() { 11809 return mMeasuredWidth; 11810 } 11811 11812 /** 11813 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11814 * raw height component (that is the result is masked by 11815 * {@link #MEASURED_SIZE_MASK}). 11816 * 11817 * @return The raw measured height of this view. 11818 */ 11819 public final int getMeasuredHeight() { 11820 return mMeasuredHeight & MEASURED_SIZE_MASK; 11821 } 11822 11823 /** 11824 * Return the full height measurement information for this view as computed 11825 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11826 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11827 * This should be used during measurement and layout calculations only. Use 11828 * {@link #getHeight()} to see how wide a view is after layout. 11829 * 11830 * @return The measured height of this view as a bit mask. 11831 */ 11832 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11833 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11834 name = "MEASURED_STATE_TOO_SMALL"), 11835 }) 11836 public final int getMeasuredHeightAndState() { 11837 return mMeasuredHeight; 11838 } 11839 11840 /** 11841 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11842 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11843 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11844 * and the height component is at the shifted bits 11845 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11846 */ 11847 public final int getMeasuredState() { 11848 return (mMeasuredWidth&MEASURED_STATE_MASK) 11849 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11850 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11851 } 11852 11853 /** 11854 * The transform matrix of this view, which is calculated based on the current 11855 * rotation, scale, and pivot properties. 11856 * 11857 * @see #getRotation() 11858 * @see #getScaleX() 11859 * @see #getScaleY() 11860 * @see #getPivotX() 11861 * @see #getPivotY() 11862 * @return The current transform matrix for the view 11863 */ 11864 public Matrix getMatrix() { 11865 ensureTransformationInfo(); 11866 final Matrix matrix = mTransformationInfo.mMatrix; 11867 mRenderNode.getMatrix(matrix); 11868 return matrix; 11869 } 11870 11871 /** 11872 * Returns true if the transform matrix is the identity matrix. 11873 * Recomputes the matrix if necessary. 11874 * 11875 * @return True if the transform matrix is the identity matrix, false otherwise. 11876 */ 11877 final boolean hasIdentityMatrix() { 11878 return mRenderNode.hasIdentityMatrix(); 11879 } 11880 11881 void ensureTransformationInfo() { 11882 if (mTransformationInfo == null) { 11883 mTransformationInfo = new TransformationInfo(); 11884 } 11885 } 11886 11887 /** 11888 * Utility method to retrieve the inverse of the current mMatrix property. 11889 * We cache the matrix to avoid recalculating it when transform properties 11890 * have not changed. 11891 * 11892 * @return The inverse of the current matrix of this view. 11893 * @hide 11894 */ 11895 public final Matrix getInverseMatrix() { 11896 ensureTransformationInfo(); 11897 if (mTransformationInfo.mInverseMatrix == null) { 11898 mTransformationInfo.mInverseMatrix = new Matrix(); 11899 } 11900 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11901 mRenderNode.getInverseMatrix(matrix); 11902 return matrix; 11903 } 11904 11905 /** 11906 * Gets the distance along the Z axis from the camera to this view. 11907 * 11908 * @see #setCameraDistance(float) 11909 * 11910 * @return The distance along the Z axis. 11911 */ 11912 public float getCameraDistance() { 11913 final float dpi = mResources.getDisplayMetrics().densityDpi; 11914 return -(mRenderNode.getCameraDistance() * dpi); 11915 } 11916 11917 /** 11918 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11919 * views are drawn) from the camera to this view. The camera's distance 11920 * affects 3D transformations, for instance rotations around the X and Y 11921 * axis. If the rotationX or rotationY properties are changed and this view is 11922 * large (more than half the size of the screen), it is recommended to always 11923 * use a camera distance that's greater than the height (X axis rotation) or 11924 * the width (Y axis rotation) of this view.</p> 11925 * 11926 * <p>The distance of the camera from the view plane can have an affect on the 11927 * perspective distortion of the view when it is rotated around the x or y axis. 11928 * For example, a large distance will result in a large viewing angle, and there 11929 * will not be much perspective distortion of the view as it rotates. A short 11930 * distance may cause much more perspective distortion upon rotation, and can 11931 * also result in some drawing artifacts if the rotated view ends up partially 11932 * behind the camera (which is why the recommendation is to use a distance at 11933 * least as far as the size of the view, if the view is to be rotated.)</p> 11934 * 11935 * <p>The distance is expressed in "depth pixels." The default distance depends 11936 * on the screen density. For instance, on a medium density display, the 11937 * default distance is 1280. On a high density display, the default distance 11938 * is 1920.</p> 11939 * 11940 * <p>If you want to specify a distance that leads to visually consistent 11941 * results across various densities, use the following formula:</p> 11942 * <pre> 11943 * float scale = context.getResources().getDisplayMetrics().density; 11944 * view.setCameraDistance(distance * scale); 11945 * </pre> 11946 * 11947 * <p>The density scale factor of a high density display is 1.5, 11948 * and 1920 = 1280 * 1.5.</p> 11949 * 11950 * @param distance The distance in "depth pixels", if negative the opposite 11951 * value is used 11952 * 11953 * @see #setRotationX(float) 11954 * @see #setRotationY(float) 11955 */ 11956 public void setCameraDistance(float distance) { 11957 final float dpi = mResources.getDisplayMetrics().densityDpi; 11958 11959 invalidateViewProperty(true, false); 11960 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11961 invalidateViewProperty(false, false); 11962 11963 invalidateParentIfNeededAndWasQuickRejected(); 11964 } 11965 11966 /** 11967 * The degrees that the view is rotated around the pivot point. 11968 * 11969 * @see #setRotation(float) 11970 * @see #getPivotX() 11971 * @see #getPivotY() 11972 * 11973 * @return The degrees of rotation. 11974 */ 11975 @ViewDebug.ExportedProperty(category = "drawing") 11976 public float getRotation() { 11977 return mRenderNode.getRotation(); 11978 } 11979 11980 /** 11981 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11982 * result in clockwise rotation. 11983 * 11984 * @param rotation The degrees of rotation. 11985 * 11986 * @see #getRotation() 11987 * @see #getPivotX() 11988 * @see #getPivotY() 11989 * @see #setRotationX(float) 11990 * @see #setRotationY(float) 11991 * 11992 * @attr ref android.R.styleable#View_rotation 11993 */ 11994 public void setRotation(float rotation) { 11995 if (rotation != getRotation()) { 11996 // Double-invalidation is necessary to capture view's old and new areas 11997 invalidateViewProperty(true, false); 11998 mRenderNode.setRotation(rotation); 11999 invalidateViewProperty(false, true); 12000 12001 invalidateParentIfNeededAndWasQuickRejected(); 12002 notifySubtreeAccessibilityStateChangedIfNeeded(); 12003 } 12004 } 12005 12006 /** 12007 * The degrees that the view is rotated around the vertical axis through the pivot point. 12008 * 12009 * @see #getPivotX() 12010 * @see #getPivotY() 12011 * @see #setRotationY(float) 12012 * 12013 * @return The degrees of Y rotation. 12014 */ 12015 @ViewDebug.ExportedProperty(category = "drawing") 12016 public float getRotationY() { 12017 return mRenderNode.getRotationY(); 12018 } 12019 12020 /** 12021 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 12022 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 12023 * down the y axis. 12024 * 12025 * When rotating large views, it is recommended to adjust the camera distance 12026 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12027 * 12028 * @param rotationY The degrees of Y rotation. 12029 * 12030 * @see #getRotationY() 12031 * @see #getPivotX() 12032 * @see #getPivotY() 12033 * @see #setRotation(float) 12034 * @see #setRotationX(float) 12035 * @see #setCameraDistance(float) 12036 * 12037 * @attr ref android.R.styleable#View_rotationY 12038 */ 12039 public void setRotationY(float rotationY) { 12040 if (rotationY != getRotationY()) { 12041 invalidateViewProperty(true, false); 12042 mRenderNode.setRotationY(rotationY); 12043 invalidateViewProperty(false, true); 12044 12045 invalidateParentIfNeededAndWasQuickRejected(); 12046 notifySubtreeAccessibilityStateChangedIfNeeded(); 12047 } 12048 } 12049 12050 /** 12051 * The degrees that the view is rotated around the horizontal axis through the pivot point. 12052 * 12053 * @see #getPivotX() 12054 * @see #getPivotY() 12055 * @see #setRotationX(float) 12056 * 12057 * @return The degrees of X rotation. 12058 */ 12059 @ViewDebug.ExportedProperty(category = "drawing") 12060 public float getRotationX() { 12061 return mRenderNode.getRotationX(); 12062 } 12063 12064 /** 12065 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 12066 * Increasing values result in clockwise rotation from the viewpoint of looking down the 12067 * x axis. 12068 * 12069 * When rotating large views, it is recommended to adjust the camera distance 12070 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12071 * 12072 * @param rotationX The degrees of X rotation. 12073 * 12074 * @see #getRotationX() 12075 * @see #getPivotX() 12076 * @see #getPivotY() 12077 * @see #setRotation(float) 12078 * @see #setRotationY(float) 12079 * @see #setCameraDistance(float) 12080 * 12081 * @attr ref android.R.styleable#View_rotationX 12082 */ 12083 public void setRotationX(float rotationX) { 12084 if (rotationX != getRotationX()) { 12085 invalidateViewProperty(true, false); 12086 mRenderNode.setRotationX(rotationX); 12087 invalidateViewProperty(false, true); 12088 12089 invalidateParentIfNeededAndWasQuickRejected(); 12090 notifySubtreeAccessibilityStateChangedIfNeeded(); 12091 } 12092 } 12093 12094 /** 12095 * The amount that the view is scaled in x around the pivot point, as a proportion of 12096 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12097 * 12098 * <p>By default, this is 1.0f. 12099 * 12100 * @see #getPivotX() 12101 * @see #getPivotY() 12102 * @return The scaling factor. 12103 */ 12104 @ViewDebug.ExportedProperty(category = "drawing") 12105 public float getScaleX() { 12106 return mRenderNode.getScaleX(); 12107 } 12108 12109 /** 12110 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12111 * the view's unscaled width. A value of 1 means that no scaling is applied. 12112 * 12113 * @param scaleX The scaling factor. 12114 * @see #getPivotX() 12115 * @see #getPivotY() 12116 * 12117 * @attr ref android.R.styleable#View_scaleX 12118 */ 12119 public void setScaleX(float scaleX) { 12120 if (scaleX != getScaleX()) { 12121 invalidateViewProperty(true, false); 12122 mRenderNode.setScaleX(scaleX); 12123 invalidateViewProperty(false, true); 12124 12125 invalidateParentIfNeededAndWasQuickRejected(); 12126 notifySubtreeAccessibilityStateChangedIfNeeded(); 12127 } 12128 } 12129 12130 /** 12131 * The amount that the view is scaled in y around the pivot point, as a proportion of 12132 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12133 * 12134 * <p>By default, this is 1.0f. 12135 * 12136 * @see #getPivotX() 12137 * @see #getPivotY() 12138 * @return The scaling factor. 12139 */ 12140 @ViewDebug.ExportedProperty(category = "drawing") 12141 public float getScaleY() { 12142 return mRenderNode.getScaleY(); 12143 } 12144 12145 /** 12146 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12147 * the view's unscaled width. A value of 1 means that no scaling is applied. 12148 * 12149 * @param scaleY The scaling factor. 12150 * @see #getPivotX() 12151 * @see #getPivotY() 12152 * 12153 * @attr ref android.R.styleable#View_scaleY 12154 */ 12155 public void setScaleY(float scaleY) { 12156 if (scaleY != getScaleY()) { 12157 invalidateViewProperty(true, false); 12158 mRenderNode.setScaleY(scaleY); 12159 invalidateViewProperty(false, true); 12160 12161 invalidateParentIfNeededAndWasQuickRejected(); 12162 notifySubtreeAccessibilityStateChangedIfNeeded(); 12163 } 12164 } 12165 12166 /** 12167 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12168 * and {@link #setScaleX(float) scaled}. 12169 * 12170 * @see #getRotation() 12171 * @see #getScaleX() 12172 * @see #getScaleY() 12173 * @see #getPivotY() 12174 * @return The x location of the pivot point. 12175 * 12176 * @attr ref android.R.styleable#View_transformPivotX 12177 */ 12178 @ViewDebug.ExportedProperty(category = "drawing") 12179 public float getPivotX() { 12180 return mRenderNode.getPivotX(); 12181 } 12182 12183 /** 12184 * Sets the x location of the point around which the view is 12185 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12186 * By default, the pivot point is centered on the object. 12187 * Setting this property disables this behavior and causes the view to use only the 12188 * explicitly set pivotX and pivotY values. 12189 * 12190 * @param pivotX The x location of the pivot point. 12191 * @see #getRotation() 12192 * @see #getScaleX() 12193 * @see #getScaleY() 12194 * @see #getPivotY() 12195 * 12196 * @attr ref android.R.styleable#View_transformPivotX 12197 */ 12198 public void setPivotX(float pivotX) { 12199 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12200 invalidateViewProperty(true, false); 12201 mRenderNode.setPivotX(pivotX); 12202 invalidateViewProperty(false, true); 12203 12204 invalidateParentIfNeededAndWasQuickRejected(); 12205 } 12206 } 12207 12208 /** 12209 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12210 * and {@link #setScaleY(float) scaled}. 12211 * 12212 * @see #getRotation() 12213 * @see #getScaleX() 12214 * @see #getScaleY() 12215 * @see #getPivotY() 12216 * @return The y location of the pivot point. 12217 * 12218 * @attr ref android.R.styleable#View_transformPivotY 12219 */ 12220 @ViewDebug.ExportedProperty(category = "drawing") 12221 public float getPivotY() { 12222 return mRenderNode.getPivotY(); 12223 } 12224 12225 /** 12226 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12227 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12228 * Setting this property disables this behavior and causes the view to use only the 12229 * explicitly set pivotX and pivotY values. 12230 * 12231 * @param pivotY The y location of the pivot point. 12232 * @see #getRotation() 12233 * @see #getScaleX() 12234 * @see #getScaleY() 12235 * @see #getPivotY() 12236 * 12237 * @attr ref android.R.styleable#View_transformPivotY 12238 */ 12239 public void setPivotY(float pivotY) { 12240 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12241 invalidateViewProperty(true, false); 12242 mRenderNode.setPivotY(pivotY); 12243 invalidateViewProperty(false, true); 12244 12245 invalidateParentIfNeededAndWasQuickRejected(); 12246 } 12247 } 12248 12249 /** 12250 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12251 * completely transparent and 1 means the view is completely opaque. 12252 * 12253 * <p>By default this is 1.0f. 12254 * @return The opacity of the view. 12255 */ 12256 @ViewDebug.ExportedProperty(category = "drawing") 12257 public float getAlpha() { 12258 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12259 } 12260 12261 /** 12262 * Sets the behavior for overlapping rendering for this view (see {@link 12263 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12264 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12265 * providing the value which is then used internally. That is, when {@link 12266 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12267 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12268 * instead. 12269 * 12270 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12271 * instead of that returned by {@link #hasOverlappingRendering()}. 12272 * 12273 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12274 */ 12275 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12276 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12277 if (hasOverlappingRendering) { 12278 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12279 } else { 12280 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12281 } 12282 } 12283 12284 /** 12285 * Returns the value for overlapping rendering that is used internally. This is either 12286 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12287 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12288 * 12289 * @return The value for overlapping rendering being used internally. 12290 */ 12291 public final boolean getHasOverlappingRendering() { 12292 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12293 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12294 hasOverlappingRendering(); 12295 } 12296 12297 /** 12298 * Returns whether this View has content which overlaps. 12299 * 12300 * <p>This function, intended to be overridden by specific View types, is an optimization when 12301 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12302 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12303 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12304 * directly. An example of overlapping rendering is a TextView with a background image, such as 12305 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12306 * ImageView with only the foreground image. The default implementation returns true; subclasses 12307 * should override if they have cases which can be optimized.</p> 12308 * 12309 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12310 * necessitates that a View return true if it uses the methods internally without passing the 12311 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12312 * 12313 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12314 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12315 * 12316 * @return true if the content in this view might overlap, false otherwise. 12317 */ 12318 @ViewDebug.ExportedProperty(category = "drawing") 12319 public boolean hasOverlappingRendering() { 12320 return true; 12321 } 12322 12323 /** 12324 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12325 * completely transparent and 1 means the view is completely opaque. 12326 * 12327 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12328 * can have significant performance implications, especially for large views. It is best to use 12329 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12330 * 12331 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12332 * strongly recommended for performance reasons to either override 12333 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12334 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12335 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12336 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12337 * of rendering cost, even for simple or small views. Starting with 12338 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12339 * applied to the view at the rendering level.</p> 12340 * 12341 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12342 * responsible for applying the opacity itself.</p> 12343 * 12344 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12345 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12346 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12347 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12348 * 12349 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12350 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12351 * {@link #hasOverlappingRendering}.</p> 12352 * 12353 * @param alpha The opacity of the view. 12354 * 12355 * @see #hasOverlappingRendering() 12356 * @see #setLayerType(int, android.graphics.Paint) 12357 * 12358 * @attr ref android.R.styleable#View_alpha 12359 */ 12360 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12361 ensureTransformationInfo(); 12362 if (mTransformationInfo.mAlpha != alpha) { 12363 // Report visibility changes, which can affect children, to accessibility 12364 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 12365 notifySubtreeAccessibilityStateChangedIfNeeded(); 12366 } 12367 mTransformationInfo.mAlpha = alpha; 12368 if (onSetAlpha((int) (alpha * 255))) { 12369 mPrivateFlags |= PFLAG_ALPHA_SET; 12370 // subclass is handling alpha - don't optimize rendering cache invalidation 12371 invalidateParentCaches(); 12372 invalidate(true); 12373 } else { 12374 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12375 invalidateViewProperty(true, false); 12376 mRenderNode.setAlpha(getFinalAlpha()); 12377 } 12378 } 12379 } 12380 12381 /** 12382 * Faster version of setAlpha() which performs the same steps except there are 12383 * no calls to invalidate(). The caller of this function should perform proper invalidation 12384 * on the parent and this object. The return value indicates whether the subclass handles 12385 * alpha (the return value for onSetAlpha()). 12386 * 12387 * @param alpha The new value for the alpha property 12388 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12389 * the new value for the alpha property is different from the old value 12390 */ 12391 boolean setAlphaNoInvalidation(float alpha) { 12392 ensureTransformationInfo(); 12393 if (mTransformationInfo.mAlpha != alpha) { 12394 mTransformationInfo.mAlpha = alpha; 12395 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12396 if (subclassHandlesAlpha) { 12397 mPrivateFlags |= PFLAG_ALPHA_SET; 12398 return true; 12399 } else { 12400 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12401 mRenderNode.setAlpha(getFinalAlpha()); 12402 } 12403 } 12404 return false; 12405 } 12406 12407 /** 12408 * This property is hidden and intended only for use by the Fade transition, which 12409 * animates it to produce a visual translucency that does not side-effect (or get 12410 * affected by) the real alpha property. This value is composited with the other 12411 * alpha value (and the AlphaAnimation value, when that is present) to produce 12412 * a final visual translucency result, which is what is passed into the DisplayList. 12413 * 12414 * @hide 12415 */ 12416 public void setTransitionAlpha(float alpha) { 12417 ensureTransformationInfo(); 12418 if (mTransformationInfo.mTransitionAlpha != alpha) { 12419 mTransformationInfo.mTransitionAlpha = alpha; 12420 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12421 invalidateViewProperty(true, false); 12422 mRenderNode.setAlpha(getFinalAlpha()); 12423 } 12424 } 12425 12426 /** 12427 * Calculates the visual alpha of this view, which is a combination of the actual 12428 * alpha value and the transitionAlpha value (if set). 12429 */ 12430 private float getFinalAlpha() { 12431 if (mTransformationInfo != null) { 12432 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12433 } 12434 return 1; 12435 } 12436 12437 /** 12438 * This property is hidden and intended only for use by the Fade transition, which 12439 * animates it to produce a visual translucency that does not side-effect (or get 12440 * affected by) the real alpha property. This value is composited with the other 12441 * alpha value (and the AlphaAnimation value, when that is present) to produce 12442 * a final visual translucency result, which is what is passed into the DisplayList. 12443 * 12444 * @hide 12445 */ 12446 @ViewDebug.ExportedProperty(category = "drawing") 12447 public float getTransitionAlpha() { 12448 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12449 } 12450 12451 /** 12452 * Top position of this view relative to its parent. 12453 * 12454 * @return The top of this view, in pixels. 12455 */ 12456 @ViewDebug.CapturedViewProperty 12457 public final int getTop() { 12458 return mTop; 12459 } 12460 12461 /** 12462 * Sets the top position of this view relative to its parent. This method is meant to be called 12463 * by the layout system and should not generally be called otherwise, because the property 12464 * may be changed at any time by the layout. 12465 * 12466 * @param top The top of this view, in pixels. 12467 */ 12468 public final void setTop(int top) { 12469 if (top != mTop) { 12470 final boolean matrixIsIdentity = hasIdentityMatrix(); 12471 if (matrixIsIdentity) { 12472 if (mAttachInfo != null) { 12473 int minTop; 12474 int yLoc; 12475 if (top < mTop) { 12476 minTop = top; 12477 yLoc = top - mTop; 12478 } else { 12479 minTop = mTop; 12480 yLoc = 0; 12481 } 12482 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12483 } 12484 } else { 12485 // Double-invalidation is necessary to capture view's old and new areas 12486 invalidate(true); 12487 } 12488 12489 int width = mRight - mLeft; 12490 int oldHeight = mBottom - mTop; 12491 12492 mTop = top; 12493 mRenderNode.setTop(mTop); 12494 12495 sizeChange(width, mBottom - mTop, width, oldHeight); 12496 12497 if (!matrixIsIdentity) { 12498 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12499 invalidate(true); 12500 } 12501 mBackgroundSizeChanged = true; 12502 if (mForegroundInfo != null) { 12503 mForegroundInfo.mBoundsChanged = true; 12504 } 12505 invalidateParentIfNeeded(); 12506 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12507 // View was rejected last time it was drawn by its parent; this may have changed 12508 invalidateParentIfNeeded(); 12509 } 12510 } 12511 } 12512 12513 /** 12514 * Bottom position of this view relative to its parent. 12515 * 12516 * @return The bottom of this view, in pixels. 12517 */ 12518 @ViewDebug.CapturedViewProperty 12519 public final int getBottom() { 12520 return mBottom; 12521 } 12522 12523 /** 12524 * True if this view has changed since the last time being drawn. 12525 * 12526 * @return The dirty state of this view. 12527 */ 12528 public boolean isDirty() { 12529 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12530 } 12531 12532 /** 12533 * Sets the bottom position of this view relative to its parent. This method is meant to be 12534 * called by the layout system and should not generally be called otherwise, because the 12535 * property may be changed at any time by the layout. 12536 * 12537 * @param bottom The bottom of this view, in pixels. 12538 */ 12539 public final void setBottom(int bottom) { 12540 if (bottom != mBottom) { 12541 final boolean matrixIsIdentity = hasIdentityMatrix(); 12542 if (matrixIsIdentity) { 12543 if (mAttachInfo != null) { 12544 int maxBottom; 12545 if (bottom < mBottom) { 12546 maxBottom = mBottom; 12547 } else { 12548 maxBottom = bottom; 12549 } 12550 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12551 } 12552 } else { 12553 // Double-invalidation is necessary to capture view's old and new areas 12554 invalidate(true); 12555 } 12556 12557 int width = mRight - mLeft; 12558 int oldHeight = mBottom - mTop; 12559 12560 mBottom = bottom; 12561 mRenderNode.setBottom(mBottom); 12562 12563 sizeChange(width, mBottom - mTop, width, oldHeight); 12564 12565 if (!matrixIsIdentity) { 12566 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12567 invalidate(true); 12568 } 12569 mBackgroundSizeChanged = true; 12570 if (mForegroundInfo != null) { 12571 mForegroundInfo.mBoundsChanged = true; 12572 } 12573 invalidateParentIfNeeded(); 12574 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12575 // View was rejected last time it was drawn by its parent; this may have changed 12576 invalidateParentIfNeeded(); 12577 } 12578 } 12579 } 12580 12581 /** 12582 * Left position of this view relative to its parent. 12583 * 12584 * @return The left edge of this view, in pixels. 12585 */ 12586 @ViewDebug.CapturedViewProperty 12587 public final int getLeft() { 12588 return mLeft; 12589 } 12590 12591 /** 12592 * Sets the left position of this view relative to its parent. This method is meant to be called 12593 * by the layout system and should not generally be called otherwise, because the property 12594 * may be changed at any time by the layout. 12595 * 12596 * @param left The left of this view, in pixels. 12597 */ 12598 public final void setLeft(int left) { 12599 if (left != mLeft) { 12600 final boolean matrixIsIdentity = hasIdentityMatrix(); 12601 if (matrixIsIdentity) { 12602 if (mAttachInfo != null) { 12603 int minLeft; 12604 int xLoc; 12605 if (left < mLeft) { 12606 minLeft = left; 12607 xLoc = left - mLeft; 12608 } else { 12609 minLeft = mLeft; 12610 xLoc = 0; 12611 } 12612 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12613 } 12614 } else { 12615 // Double-invalidation is necessary to capture view's old and new areas 12616 invalidate(true); 12617 } 12618 12619 int oldWidth = mRight - mLeft; 12620 int height = mBottom - mTop; 12621 12622 mLeft = left; 12623 mRenderNode.setLeft(left); 12624 12625 sizeChange(mRight - mLeft, height, oldWidth, height); 12626 12627 if (!matrixIsIdentity) { 12628 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12629 invalidate(true); 12630 } 12631 mBackgroundSizeChanged = true; 12632 if (mForegroundInfo != null) { 12633 mForegroundInfo.mBoundsChanged = true; 12634 } 12635 invalidateParentIfNeeded(); 12636 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12637 // View was rejected last time it was drawn by its parent; this may have changed 12638 invalidateParentIfNeeded(); 12639 } 12640 } 12641 } 12642 12643 /** 12644 * Right position of this view relative to its parent. 12645 * 12646 * @return The right edge of this view, in pixels. 12647 */ 12648 @ViewDebug.CapturedViewProperty 12649 public final int getRight() { 12650 return mRight; 12651 } 12652 12653 /** 12654 * Sets the right position of this view relative to its parent. This method is meant to be called 12655 * by the layout system and should not generally be called otherwise, because the property 12656 * may be changed at any time by the layout. 12657 * 12658 * @param right The right of this view, in pixels. 12659 */ 12660 public final void setRight(int right) { 12661 if (right != mRight) { 12662 final boolean matrixIsIdentity = hasIdentityMatrix(); 12663 if (matrixIsIdentity) { 12664 if (mAttachInfo != null) { 12665 int maxRight; 12666 if (right < mRight) { 12667 maxRight = mRight; 12668 } else { 12669 maxRight = right; 12670 } 12671 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12672 } 12673 } else { 12674 // Double-invalidation is necessary to capture view's old and new areas 12675 invalidate(true); 12676 } 12677 12678 int oldWidth = mRight - mLeft; 12679 int height = mBottom - mTop; 12680 12681 mRight = right; 12682 mRenderNode.setRight(mRight); 12683 12684 sizeChange(mRight - mLeft, height, oldWidth, height); 12685 12686 if (!matrixIsIdentity) { 12687 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12688 invalidate(true); 12689 } 12690 mBackgroundSizeChanged = true; 12691 if (mForegroundInfo != null) { 12692 mForegroundInfo.mBoundsChanged = true; 12693 } 12694 invalidateParentIfNeeded(); 12695 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12696 // View was rejected last time it was drawn by its parent; this may have changed 12697 invalidateParentIfNeeded(); 12698 } 12699 } 12700 } 12701 12702 /** 12703 * The visual x position of this view, in pixels. This is equivalent to the 12704 * {@link #setTranslationX(float) translationX} property plus the current 12705 * {@link #getLeft() left} property. 12706 * 12707 * @return The visual x position of this view, in pixels. 12708 */ 12709 @ViewDebug.ExportedProperty(category = "drawing") 12710 public float getX() { 12711 return mLeft + getTranslationX(); 12712 } 12713 12714 /** 12715 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12716 * {@link #setTranslationX(float) translationX} property to be the difference between 12717 * the x value passed in and the current {@link #getLeft() left} property. 12718 * 12719 * @param x The visual x position of this view, in pixels. 12720 */ 12721 public void setX(float x) { 12722 setTranslationX(x - mLeft); 12723 } 12724 12725 /** 12726 * The visual y position of this view, in pixels. This is equivalent to the 12727 * {@link #setTranslationY(float) translationY} property plus the current 12728 * {@link #getTop() top} property. 12729 * 12730 * @return The visual y position of this view, in pixels. 12731 */ 12732 @ViewDebug.ExportedProperty(category = "drawing") 12733 public float getY() { 12734 return mTop + getTranslationY(); 12735 } 12736 12737 /** 12738 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12739 * {@link #setTranslationY(float) translationY} property to be the difference between 12740 * the y value passed in and the current {@link #getTop() top} property. 12741 * 12742 * @param y The visual y position of this view, in pixels. 12743 */ 12744 public void setY(float y) { 12745 setTranslationY(y - mTop); 12746 } 12747 12748 /** 12749 * The visual z position of this view, in pixels. This is equivalent to the 12750 * {@link #setTranslationZ(float) translationZ} property plus the current 12751 * {@link #getElevation() elevation} property. 12752 * 12753 * @return The visual z position of this view, in pixels. 12754 */ 12755 @ViewDebug.ExportedProperty(category = "drawing") 12756 public float getZ() { 12757 return getElevation() + getTranslationZ(); 12758 } 12759 12760 /** 12761 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12762 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12763 * the x value passed in and the current {@link #getElevation() elevation} property. 12764 * 12765 * @param z The visual z position of this view, in pixels. 12766 */ 12767 public void setZ(float z) { 12768 setTranslationZ(z - getElevation()); 12769 } 12770 12771 /** 12772 * The base elevation of this view relative to its parent, in pixels. 12773 * 12774 * @return The base depth position of the view, in pixels. 12775 */ 12776 @ViewDebug.ExportedProperty(category = "drawing") 12777 public float getElevation() { 12778 return mRenderNode.getElevation(); 12779 } 12780 12781 /** 12782 * Sets the base elevation of this view, in pixels. 12783 * 12784 * @attr ref android.R.styleable#View_elevation 12785 */ 12786 public void setElevation(float elevation) { 12787 if (elevation != getElevation()) { 12788 invalidateViewProperty(true, false); 12789 mRenderNode.setElevation(elevation); 12790 invalidateViewProperty(false, true); 12791 12792 invalidateParentIfNeededAndWasQuickRejected(); 12793 } 12794 } 12795 12796 /** 12797 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12798 * This position is post-layout, in addition to wherever the object's 12799 * layout placed it. 12800 * 12801 * @return The horizontal position of this view relative to its left position, in pixels. 12802 */ 12803 @ViewDebug.ExportedProperty(category = "drawing") 12804 public float getTranslationX() { 12805 return mRenderNode.getTranslationX(); 12806 } 12807 12808 /** 12809 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12810 * This effectively positions the object post-layout, in addition to wherever the object's 12811 * layout placed it. 12812 * 12813 * @param translationX The horizontal position of this view relative to its left position, 12814 * in pixels. 12815 * 12816 * @attr ref android.R.styleable#View_translationX 12817 */ 12818 public void setTranslationX(float translationX) { 12819 if (translationX != getTranslationX()) { 12820 invalidateViewProperty(true, false); 12821 mRenderNode.setTranslationX(translationX); 12822 invalidateViewProperty(false, true); 12823 12824 invalidateParentIfNeededAndWasQuickRejected(); 12825 notifySubtreeAccessibilityStateChangedIfNeeded(); 12826 } 12827 } 12828 12829 /** 12830 * The vertical location of this view relative to its {@link #getTop() top} position. 12831 * This position is post-layout, in addition to wherever the object's 12832 * layout placed it. 12833 * 12834 * @return The vertical position of this view relative to its top position, 12835 * in pixels. 12836 */ 12837 @ViewDebug.ExportedProperty(category = "drawing") 12838 public float getTranslationY() { 12839 return mRenderNode.getTranslationY(); 12840 } 12841 12842 /** 12843 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12844 * This effectively positions the object post-layout, in addition to wherever the object's 12845 * layout placed it. 12846 * 12847 * @param translationY The vertical position of this view relative to its top position, 12848 * in pixels. 12849 * 12850 * @attr ref android.R.styleable#View_translationY 12851 */ 12852 public void setTranslationY(float translationY) { 12853 if (translationY != getTranslationY()) { 12854 invalidateViewProperty(true, false); 12855 mRenderNode.setTranslationY(translationY); 12856 invalidateViewProperty(false, true); 12857 12858 invalidateParentIfNeededAndWasQuickRejected(); 12859 notifySubtreeAccessibilityStateChangedIfNeeded(); 12860 } 12861 } 12862 12863 /** 12864 * The depth location of this view relative to its {@link #getElevation() elevation}. 12865 * 12866 * @return The depth of this view relative to its elevation. 12867 */ 12868 @ViewDebug.ExportedProperty(category = "drawing") 12869 public float getTranslationZ() { 12870 return mRenderNode.getTranslationZ(); 12871 } 12872 12873 /** 12874 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12875 * 12876 * @attr ref android.R.styleable#View_translationZ 12877 */ 12878 public void setTranslationZ(float translationZ) { 12879 if (translationZ != getTranslationZ()) { 12880 invalidateViewProperty(true, false); 12881 mRenderNode.setTranslationZ(translationZ); 12882 invalidateViewProperty(false, true); 12883 12884 invalidateParentIfNeededAndWasQuickRejected(); 12885 } 12886 } 12887 12888 /** @hide */ 12889 public void setAnimationMatrix(Matrix matrix) { 12890 invalidateViewProperty(true, false); 12891 mRenderNode.setAnimationMatrix(matrix); 12892 invalidateViewProperty(false, true); 12893 12894 invalidateParentIfNeededAndWasQuickRejected(); 12895 } 12896 12897 /** 12898 * Returns the current StateListAnimator if exists. 12899 * 12900 * @return StateListAnimator or null if it does not exists 12901 * @see #setStateListAnimator(android.animation.StateListAnimator) 12902 */ 12903 public StateListAnimator getStateListAnimator() { 12904 return mStateListAnimator; 12905 } 12906 12907 /** 12908 * Attaches the provided StateListAnimator to this View. 12909 * <p> 12910 * Any previously attached StateListAnimator will be detached. 12911 * 12912 * @param stateListAnimator The StateListAnimator to update the view 12913 * @see {@link android.animation.StateListAnimator} 12914 */ 12915 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12916 if (mStateListAnimator == stateListAnimator) { 12917 return; 12918 } 12919 if (mStateListAnimator != null) { 12920 mStateListAnimator.setTarget(null); 12921 } 12922 mStateListAnimator = stateListAnimator; 12923 if (stateListAnimator != null) { 12924 stateListAnimator.setTarget(this); 12925 if (isAttachedToWindow()) { 12926 stateListAnimator.setState(getDrawableState()); 12927 } 12928 } 12929 } 12930 12931 /** 12932 * Returns whether the Outline should be used to clip the contents of the View. 12933 * <p> 12934 * Note that this flag will only be respected if the View's Outline returns true from 12935 * {@link Outline#canClip()}. 12936 * 12937 * @see #setOutlineProvider(ViewOutlineProvider) 12938 * @see #setClipToOutline(boolean) 12939 */ 12940 public final boolean getClipToOutline() { 12941 return mRenderNode.getClipToOutline(); 12942 } 12943 12944 /** 12945 * Sets whether the View's Outline should be used to clip the contents of the View. 12946 * <p> 12947 * Only a single non-rectangular clip can be applied on a View at any time. 12948 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12949 * circular reveal} animation take priority over Outline clipping, and 12950 * child Outline clipping takes priority over Outline clipping done by a 12951 * parent. 12952 * <p> 12953 * Note that this flag will only be respected if the View's Outline returns true from 12954 * {@link Outline#canClip()}. 12955 * 12956 * @see #setOutlineProvider(ViewOutlineProvider) 12957 * @see #getClipToOutline() 12958 */ 12959 public void setClipToOutline(boolean clipToOutline) { 12960 damageInParent(); 12961 if (getClipToOutline() != clipToOutline) { 12962 mRenderNode.setClipToOutline(clipToOutline); 12963 } 12964 } 12965 12966 // correspond to the enum values of View_outlineProvider 12967 private static final int PROVIDER_BACKGROUND = 0; 12968 private static final int PROVIDER_NONE = 1; 12969 private static final int PROVIDER_BOUNDS = 2; 12970 private static final int PROVIDER_PADDED_BOUNDS = 3; 12971 private void setOutlineProviderFromAttribute(int providerInt) { 12972 switch (providerInt) { 12973 case PROVIDER_BACKGROUND: 12974 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12975 break; 12976 case PROVIDER_NONE: 12977 setOutlineProvider(null); 12978 break; 12979 case PROVIDER_BOUNDS: 12980 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12981 break; 12982 case PROVIDER_PADDED_BOUNDS: 12983 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12984 break; 12985 } 12986 } 12987 12988 /** 12989 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12990 * the shape of the shadow it casts, and enables outline clipping. 12991 * <p> 12992 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12993 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12994 * outline provider with this method allows this behavior to be overridden. 12995 * <p> 12996 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12997 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12998 * <p> 12999 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 13000 * 13001 * @see #setClipToOutline(boolean) 13002 * @see #getClipToOutline() 13003 * @see #getOutlineProvider() 13004 */ 13005 public void setOutlineProvider(ViewOutlineProvider provider) { 13006 mOutlineProvider = provider; 13007 invalidateOutline(); 13008 } 13009 13010 /** 13011 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 13012 * that defines the shape of the shadow it casts, and enables outline clipping. 13013 * 13014 * @see #setOutlineProvider(ViewOutlineProvider) 13015 */ 13016 public ViewOutlineProvider getOutlineProvider() { 13017 return mOutlineProvider; 13018 } 13019 13020 /** 13021 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 13022 * 13023 * @see #setOutlineProvider(ViewOutlineProvider) 13024 */ 13025 public void invalidateOutline() { 13026 rebuildOutline(); 13027 13028 notifySubtreeAccessibilityStateChangedIfNeeded(); 13029 invalidateViewProperty(false, false); 13030 } 13031 13032 /** 13033 * Internal version of {@link #invalidateOutline()} which invalidates the 13034 * outline without invalidating the view itself. This is intended to be called from 13035 * within methods in the View class itself which are the result of the view being 13036 * invalidated already. For example, when we are drawing the background of a View, 13037 * we invalidate the outline in case it changed in the meantime, but we do not 13038 * need to invalidate the view because we're already drawing the background as part 13039 * of drawing the view in response to an earlier invalidation of the view. 13040 */ 13041 private void rebuildOutline() { 13042 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 13043 if (mAttachInfo == null) return; 13044 13045 if (mOutlineProvider == null) { 13046 // no provider, remove outline 13047 mRenderNode.setOutline(null); 13048 } else { 13049 final Outline outline = mAttachInfo.mTmpOutline; 13050 outline.setEmpty(); 13051 outline.setAlpha(1.0f); 13052 13053 mOutlineProvider.getOutline(this, outline); 13054 mRenderNode.setOutline(outline); 13055 } 13056 } 13057 13058 /** 13059 * HierarchyViewer only 13060 * 13061 * @hide 13062 */ 13063 @ViewDebug.ExportedProperty(category = "drawing") 13064 public boolean hasShadow() { 13065 return mRenderNode.hasShadow(); 13066 } 13067 13068 13069 /** @hide */ 13070 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13071 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13072 invalidateViewProperty(false, false); 13073 } 13074 13075 /** 13076 * Hit rectangle in parent's coordinates 13077 * 13078 * @param outRect The hit rectangle of the view. 13079 */ 13080 public void getHitRect(Rect outRect) { 13081 if (hasIdentityMatrix() || mAttachInfo == null) { 13082 outRect.set(mLeft, mTop, mRight, mBottom); 13083 } else { 13084 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13085 tmpRect.set(0, 0, getWidth(), getHeight()); 13086 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13087 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13088 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13089 } 13090 } 13091 13092 /** 13093 * Determines whether the given point, in local coordinates is inside the view. 13094 */ 13095 /*package*/ final boolean pointInView(float localX, float localY) { 13096 return pointInView(localX, localY, 0); 13097 } 13098 13099 /** 13100 * Utility method to determine whether the given point, in local coordinates, 13101 * is inside the view, where the area of the view is expanded by the slop factor. 13102 * This method is called while processing touch-move events to determine if the event 13103 * is still within the view. 13104 * 13105 * @hide 13106 */ 13107 public boolean pointInView(float localX, float localY, float slop) { 13108 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13109 localY < ((mBottom - mTop) + slop); 13110 } 13111 13112 /** 13113 * When a view has focus and the user navigates away from it, the next view is searched for 13114 * starting from the rectangle filled in by this method. 13115 * 13116 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13117 * of the view. However, if your view maintains some idea of internal selection, 13118 * such as a cursor, or a selected row or column, you should override this method and 13119 * fill in a more specific rectangle. 13120 * 13121 * @param r The rectangle to fill in, in this view's coordinates. 13122 */ 13123 public void getFocusedRect(Rect r) { 13124 getDrawingRect(r); 13125 } 13126 13127 /** 13128 * If some part of this view is not clipped by any of its parents, then 13129 * return that area in r in global (root) coordinates. To convert r to local 13130 * coordinates (without taking possible View rotations into account), offset 13131 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13132 * If the view is completely clipped or translated out, return false. 13133 * 13134 * @param r If true is returned, r holds the global coordinates of the 13135 * visible portion of this view. 13136 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13137 * between this view and its root. globalOffet may be null. 13138 * @return true if r is non-empty (i.e. part of the view is visible at the 13139 * root level. 13140 */ 13141 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13142 int width = mRight - mLeft; 13143 int height = mBottom - mTop; 13144 if (width > 0 && height > 0) { 13145 r.set(0, 0, width, height); 13146 if (globalOffset != null) { 13147 globalOffset.set(-mScrollX, -mScrollY); 13148 } 13149 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13150 } 13151 return false; 13152 } 13153 13154 public final boolean getGlobalVisibleRect(Rect r) { 13155 return getGlobalVisibleRect(r, null); 13156 } 13157 13158 public final boolean getLocalVisibleRect(Rect r) { 13159 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13160 if (getGlobalVisibleRect(r, offset)) { 13161 r.offset(-offset.x, -offset.y); // make r local 13162 return true; 13163 } 13164 return false; 13165 } 13166 13167 /** 13168 * Offset this view's vertical location by the specified number of pixels. 13169 * 13170 * @param offset the number of pixels to offset the view by 13171 */ 13172 public void offsetTopAndBottom(int offset) { 13173 if (offset != 0) { 13174 final boolean matrixIsIdentity = hasIdentityMatrix(); 13175 if (matrixIsIdentity) { 13176 if (isHardwareAccelerated()) { 13177 invalidateViewProperty(false, false); 13178 } else { 13179 final ViewParent p = mParent; 13180 if (p != null && mAttachInfo != null) { 13181 final Rect r = mAttachInfo.mTmpInvalRect; 13182 int minTop; 13183 int maxBottom; 13184 int yLoc; 13185 if (offset < 0) { 13186 minTop = mTop + offset; 13187 maxBottom = mBottom; 13188 yLoc = offset; 13189 } else { 13190 minTop = mTop; 13191 maxBottom = mBottom + offset; 13192 yLoc = 0; 13193 } 13194 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13195 p.invalidateChild(this, r); 13196 } 13197 } 13198 } else { 13199 invalidateViewProperty(false, false); 13200 } 13201 13202 mTop += offset; 13203 mBottom += offset; 13204 mRenderNode.offsetTopAndBottom(offset); 13205 if (isHardwareAccelerated()) { 13206 invalidateViewProperty(false, false); 13207 invalidateParentIfNeededAndWasQuickRejected(); 13208 } else { 13209 if (!matrixIsIdentity) { 13210 invalidateViewProperty(false, true); 13211 } 13212 invalidateParentIfNeeded(); 13213 } 13214 notifySubtreeAccessibilityStateChangedIfNeeded(); 13215 } 13216 } 13217 13218 /** 13219 * Offset this view's horizontal location by the specified amount of pixels. 13220 * 13221 * @param offset the number of pixels to offset the view by 13222 */ 13223 public void offsetLeftAndRight(int offset) { 13224 if (offset != 0) { 13225 final boolean matrixIsIdentity = hasIdentityMatrix(); 13226 if (matrixIsIdentity) { 13227 if (isHardwareAccelerated()) { 13228 invalidateViewProperty(false, false); 13229 } else { 13230 final ViewParent p = mParent; 13231 if (p != null && mAttachInfo != null) { 13232 final Rect r = mAttachInfo.mTmpInvalRect; 13233 int minLeft; 13234 int maxRight; 13235 if (offset < 0) { 13236 minLeft = mLeft + offset; 13237 maxRight = mRight; 13238 } else { 13239 minLeft = mLeft; 13240 maxRight = mRight + offset; 13241 } 13242 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13243 p.invalidateChild(this, r); 13244 } 13245 } 13246 } else { 13247 invalidateViewProperty(false, false); 13248 } 13249 13250 mLeft += offset; 13251 mRight += offset; 13252 mRenderNode.offsetLeftAndRight(offset); 13253 if (isHardwareAccelerated()) { 13254 invalidateViewProperty(false, false); 13255 invalidateParentIfNeededAndWasQuickRejected(); 13256 } else { 13257 if (!matrixIsIdentity) { 13258 invalidateViewProperty(false, true); 13259 } 13260 invalidateParentIfNeeded(); 13261 } 13262 notifySubtreeAccessibilityStateChangedIfNeeded(); 13263 } 13264 } 13265 13266 /** 13267 * Get the LayoutParams associated with this view. All views should have 13268 * layout parameters. These supply parameters to the <i>parent</i> of this 13269 * view specifying how it should be arranged. There are many subclasses of 13270 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13271 * of ViewGroup that are responsible for arranging their children. 13272 * 13273 * This method may return null if this View is not attached to a parent 13274 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13275 * was not invoked successfully. When a View is attached to a parent 13276 * ViewGroup, this method must not return null. 13277 * 13278 * @return The LayoutParams associated with this view, or null if no 13279 * parameters have been set yet 13280 */ 13281 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13282 public ViewGroup.LayoutParams getLayoutParams() { 13283 return mLayoutParams; 13284 } 13285 13286 /** 13287 * Set the layout parameters associated with this view. These supply 13288 * parameters to the <i>parent</i> of this view specifying how it should be 13289 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13290 * correspond to the different subclasses of ViewGroup that are responsible 13291 * for arranging their children. 13292 * 13293 * @param params The layout parameters for this view, cannot be null 13294 */ 13295 public void setLayoutParams(ViewGroup.LayoutParams params) { 13296 if (params == null) { 13297 throw new NullPointerException("Layout parameters cannot be null"); 13298 } 13299 mLayoutParams = params; 13300 resolveLayoutParams(); 13301 if (mParent instanceof ViewGroup) { 13302 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13303 } 13304 requestLayout(); 13305 } 13306 13307 /** 13308 * Resolve the layout parameters depending on the resolved layout direction 13309 * 13310 * @hide 13311 */ 13312 public void resolveLayoutParams() { 13313 if (mLayoutParams != null) { 13314 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13315 } 13316 } 13317 13318 /** 13319 * Set the scrolled position of your view. This will cause a call to 13320 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13321 * invalidated. 13322 * @param x the x position to scroll to 13323 * @param y the y position to scroll to 13324 */ 13325 public void scrollTo(int x, int y) { 13326 if (mScrollX != x || mScrollY != y) { 13327 int oldX = mScrollX; 13328 int oldY = mScrollY; 13329 mScrollX = x; 13330 mScrollY = y; 13331 invalidateParentCaches(); 13332 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13333 if (!awakenScrollBars()) { 13334 postInvalidateOnAnimation(); 13335 } 13336 } 13337 } 13338 13339 /** 13340 * Move the scrolled position of your view. This will cause a call to 13341 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13342 * invalidated. 13343 * @param x the amount of pixels to scroll by horizontally 13344 * @param y the amount of pixels to scroll by vertically 13345 */ 13346 public void scrollBy(int x, int y) { 13347 scrollTo(mScrollX + x, mScrollY + y); 13348 } 13349 13350 /** 13351 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13352 * animation to fade the scrollbars out after a default delay. If a subclass 13353 * provides animated scrolling, the start delay should equal the duration 13354 * of the scrolling animation.</p> 13355 * 13356 * <p>The animation starts only if at least one of the scrollbars is 13357 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13358 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13359 * this method returns true, and false otherwise. If the animation is 13360 * started, this method calls {@link #invalidate()}; in that case the 13361 * caller should not call {@link #invalidate()}.</p> 13362 * 13363 * <p>This method should be invoked every time a subclass directly updates 13364 * the scroll parameters.</p> 13365 * 13366 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13367 * and {@link #scrollTo(int, int)}.</p> 13368 * 13369 * @return true if the animation is played, false otherwise 13370 * 13371 * @see #awakenScrollBars(int) 13372 * @see #scrollBy(int, int) 13373 * @see #scrollTo(int, int) 13374 * @see #isHorizontalScrollBarEnabled() 13375 * @see #isVerticalScrollBarEnabled() 13376 * @see #setHorizontalScrollBarEnabled(boolean) 13377 * @see #setVerticalScrollBarEnabled(boolean) 13378 */ 13379 protected boolean awakenScrollBars() { 13380 return mScrollCache != null && 13381 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13382 } 13383 13384 /** 13385 * Trigger the scrollbars to draw. 13386 * This method differs from awakenScrollBars() only in its default duration. 13387 * initialAwakenScrollBars() will show the scroll bars for longer than 13388 * usual to give the user more of a chance to notice them. 13389 * 13390 * @return true if the animation is played, false otherwise. 13391 */ 13392 private boolean initialAwakenScrollBars() { 13393 return mScrollCache != null && 13394 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13395 } 13396 13397 /** 13398 * <p> 13399 * Trigger the scrollbars to draw. When invoked this method starts an 13400 * animation to fade the scrollbars out after a fixed delay. If a subclass 13401 * provides animated scrolling, the start delay should equal the duration of 13402 * the scrolling animation. 13403 * </p> 13404 * 13405 * <p> 13406 * The animation starts only if at least one of the scrollbars is enabled, 13407 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13408 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13409 * this method returns true, and false otherwise. If the animation is 13410 * started, this method calls {@link #invalidate()}; in that case the caller 13411 * should not call {@link #invalidate()}. 13412 * </p> 13413 * 13414 * <p> 13415 * This method should be invoked every time a subclass directly updates the 13416 * scroll parameters. 13417 * </p> 13418 * 13419 * @param startDelay the delay, in milliseconds, after which the animation 13420 * should start; when the delay is 0, the animation starts 13421 * immediately 13422 * @return true if the animation is played, false otherwise 13423 * 13424 * @see #scrollBy(int, int) 13425 * @see #scrollTo(int, int) 13426 * @see #isHorizontalScrollBarEnabled() 13427 * @see #isVerticalScrollBarEnabled() 13428 * @see #setHorizontalScrollBarEnabled(boolean) 13429 * @see #setVerticalScrollBarEnabled(boolean) 13430 */ 13431 protected boolean awakenScrollBars(int startDelay) { 13432 return awakenScrollBars(startDelay, true); 13433 } 13434 13435 /** 13436 * <p> 13437 * Trigger the scrollbars to draw. When invoked this method starts an 13438 * animation to fade the scrollbars out after a fixed delay. If a subclass 13439 * provides animated scrolling, the start delay should equal the duration of 13440 * the scrolling animation. 13441 * </p> 13442 * 13443 * <p> 13444 * The animation starts only if at least one of the scrollbars is enabled, 13445 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13446 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13447 * this method returns true, and false otherwise. If the animation is 13448 * started, this method calls {@link #invalidate()} if the invalidate parameter 13449 * is set to true; in that case the caller 13450 * should not call {@link #invalidate()}. 13451 * </p> 13452 * 13453 * <p> 13454 * This method should be invoked every time a subclass directly updates the 13455 * scroll parameters. 13456 * </p> 13457 * 13458 * @param startDelay the delay, in milliseconds, after which the animation 13459 * should start; when the delay is 0, the animation starts 13460 * immediately 13461 * 13462 * @param invalidate Whether this method should call invalidate 13463 * 13464 * @return true if the animation is played, false otherwise 13465 * 13466 * @see #scrollBy(int, int) 13467 * @see #scrollTo(int, int) 13468 * @see #isHorizontalScrollBarEnabled() 13469 * @see #isVerticalScrollBarEnabled() 13470 * @see #setHorizontalScrollBarEnabled(boolean) 13471 * @see #setVerticalScrollBarEnabled(boolean) 13472 */ 13473 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13474 final ScrollabilityCache scrollCache = mScrollCache; 13475 13476 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13477 return false; 13478 } 13479 13480 if (scrollCache.scrollBar == null) { 13481 scrollCache.scrollBar = new ScrollBarDrawable(); 13482 scrollCache.scrollBar.setState(getDrawableState()); 13483 scrollCache.scrollBar.setCallback(this); 13484 } 13485 13486 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13487 13488 if (invalidate) { 13489 // Invalidate to show the scrollbars 13490 postInvalidateOnAnimation(); 13491 } 13492 13493 if (scrollCache.state == ScrollabilityCache.OFF) { 13494 // FIXME: this is copied from WindowManagerService. 13495 // We should get this value from the system when it 13496 // is possible to do so. 13497 final int KEY_REPEAT_FIRST_DELAY = 750; 13498 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13499 } 13500 13501 // Tell mScrollCache when we should start fading. This may 13502 // extend the fade start time if one was already scheduled 13503 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13504 scrollCache.fadeStartTime = fadeStartTime; 13505 scrollCache.state = ScrollabilityCache.ON; 13506 13507 // Schedule our fader to run, unscheduling any old ones first 13508 if (mAttachInfo != null) { 13509 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13510 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13511 } 13512 13513 return true; 13514 } 13515 13516 return false; 13517 } 13518 13519 /** 13520 * Do not invalidate views which are not visible and which are not running an animation. They 13521 * will not get drawn and they should not set dirty flags as if they will be drawn 13522 */ 13523 private boolean skipInvalidate() { 13524 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13525 (!(mParent instanceof ViewGroup) || 13526 !((ViewGroup) mParent).isViewTransitioning(this)); 13527 } 13528 13529 /** 13530 * Mark the area defined by dirty as needing to be drawn. If the view is 13531 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13532 * point in the future. 13533 * <p> 13534 * This must be called from a UI thread. To call from a non-UI thread, call 13535 * {@link #postInvalidate()}. 13536 * <p> 13537 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13538 * {@code dirty}. 13539 * 13540 * @param dirty the rectangle representing the bounds of the dirty region 13541 */ 13542 public void invalidate(Rect dirty) { 13543 final int scrollX = mScrollX; 13544 final int scrollY = mScrollY; 13545 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13546 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13547 } 13548 13549 /** 13550 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13551 * coordinates of the dirty rect are relative to the view. If the view is 13552 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13553 * point in the future. 13554 * <p> 13555 * This must be called from a UI thread. To call from a non-UI thread, call 13556 * {@link #postInvalidate()}. 13557 * 13558 * @param l the left position of the dirty region 13559 * @param t the top position of the dirty region 13560 * @param r the right position of the dirty region 13561 * @param b the bottom position of the dirty region 13562 */ 13563 public void invalidate(int l, int t, int r, int b) { 13564 final int scrollX = mScrollX; 13565 final int scrollY = mScrollY; 13566 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13567 } 13568 13569 /** 13570 * Invalidate the whole view. If the view is visible, 13571 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13572 * the future. 13573 * <p> 13574 * This must be called from a UI thread. To call from a non-UI thread, call 13575 * {@link #postInvalidate()}. 13576 */ 13577 public void invalidate() { 13578 invalidate(true); 13579 } 13580 13581 /** 13582 * This is where the invalidate() work actually happens. A full invalidate() 13583 * causes the drawing cache to be invalidated, but this function can be 13584 * called with invalidateCache set to false to skip that invalidation step 13585 * for cases that do not need it (for example, a component that remains at 13586 * the same dimensions with the same content). 13587 * 13588 * @param invalidateCache Whether the drawing cache for this view should be 13589 * invalidated as well. This is usually true for a full 13590 * invalidate, but may be set to false if the View's contents or 13591 * dimensions have not changed. 13592 */ 13593 void invalidate(boolean invalidateCache) { 13594 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13595 } 13596 13597 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13598 boolean fullInvalidate) { 13599 if (mGhostView != null) { 13600 mGhostView.invalidate(true); 13601 return; 13602 } 13603 13604 if (skipInvalidate()) { 13605 return; 13606 } 13607 13608 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13609 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13610 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13611 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13612 if (fullInvalidate) { 13613 mLastIsOpaque = isOpaque(); 13614 mPrivateFlags &= ~PFLAG_DRAWN; 13615 } 13616 13617 mPrivateFlags |= PFLAG_DIRTY; 13618 13619 if (invalidateCache) { 13620 mPrivateFlags |= PFLAG_INVALIDATED; 13621 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13622 } 13623 13624 // Propagate the damage rectangle to the parent view. 13625 final AttachInfo ai = mAttachInfo; 13626 final ViewParent p = mParent; 13627 if (p != null && ai != null && l < r && t < b) { 13628 final Rect damage = ai.mTmpInvalRect; 13629 damage.set(l, t, r, b); 13630 p.invalidateChild(this, damage); 13631 } 13632 13633 // Damage the entire projection receiver, if necessary. 13634 if (mBackground != null && mBackground.isProjected()) { 13635 final View receiver = getProjectionReceiver(); 13636 if (receiver != null) { 13637 receiver.damageInParent(); 13638 } 13639 } 13640 13641 // Damage the entire IsolatedZVolume receiving this view's shadow. 13642 if (isHardwareAccelerated() && getZ() != 0) { 13643 damageShadowReceiver(); 13644 } 13645 } 13646 } 13647 13648 /** 13649 * @return this view's projection receiver, or {@code null} if none exists 13650 */ 13651 private View getProjectionReceiver() { 13652 ViewParent p = getParent(); 13653 while (p != null && p instanceof View) { 13654 final View v = (View) p; 13655 if (v.isProjectionReceiver()) { 13656 return v; 13657 } 13658 p = p.getParent(); 13659 } 13660 13661 return null; 13662 } 13663 13664 /** 13665 * @return whether the view is a projection receiver 13666 */ 13667 private boolean isProjectionReceiver() { 13668 return mBackground != null; 13669 } 13670 13671 /** 13672 * Damage area of the screen that can be covered by this View's shadow. 13673 * 13674 * This method will guarantee that any changes to shadows cast by a View 13675 * are damaged on the screen for future redraw. 13676 */ 13677 private void damageShadowReceiver() { 13678 final AttachInfo ai = mAttachInfo; 13679 if (ai != null) { 13680 ViewParent p = getParent(); 13681 if (p != null && p instanceof ViewGroup) { 13682 final ViewGroup vg = (ViewGroup) p; 13683 vg.damageInParent(); 13684 } 13685 } 13686 } 13687 13688 /** 13689 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13690 * set any flags or handle all of the cases handled by the default invalidation methods. 13691 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13692 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13693 * walk up the hierarchy, transforming the dirty rect as necessary. 13694 * 13695 * The method also handles normal invalidation logic if display list properties are not 13696 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13697 * backup approach, to handle these cases used in the various property-setting methods. 13698 * 13699 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13700 * are not being used in this view 13701 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13702 * list properties are not being used in this view 13703 */ 13704 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13705 if (!isHardwareAccelerated() 13706 || !mRenderNode.isValid() 13707 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13708 if (invalidateParent) { 13709 invalidateParentCaches(); 13710 } 13711 if (forceRedraw) { 13712 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13713 } 13714 invalidate(false); 13715 } else { 13716 damageInParent(); 13717 } 13718 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13719 damageShadowReceiver(); 13720 } 13721 } 13722 13723 /** 13724 * Tells the parent view to damage this view's bounds. 13725 * 13726 * @hide 13727 */ 13728 protected void damageInParent() { 13729 final AttachInfo ai = mAttachInfo; 13730 final ViewParent p = mParent; 13731 if (p != null && ai != null) { 13732 final Rect r = ai.mTmpInvalRect; 13733 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13734 if (mParent instanceof ViewGroup) { 13735 ((ViewGroup) mParent).damageChild(this, r); 13736 } else { 13737 mParent.invalidateChild(this, r); 13738 } 13739 } 13740 } 13741 13742 /** 13743 * Utility method to transform a given Rect by the current matrix of this view. 13744 */ 13745 void transformRect(final Rect rect) { 13746 if (!getMatrix().isIdentity()) { 13747 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13748 boundingRect.set(rect); 13749 getMatrix().mapRect(boundingRect); 13750 rect.set((int) Math.floor(boundingRect.left), 13751 (int) Math.floor(boundingRect.top), 13752 (int) Math.ceil(boundingRect.right), 13753 (int) Math.ceil(boundingRect.bottom)); 13754 } 13755 } 13756 13757 /** 13758 * Used to indicate that the parent of this view should clear its caches. This functionality 13759 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13760 * which is necessary when various parent-managed properties of the view change, such as 13761 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13762 * clears the parent caches and does not causes an invalidate event. 13763 * 13764 * @hide 13765 */ 13766 protected void invalidateParentCaches() { 13767 if (mParent instanceof View) { 13768 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13769 } 13770 } 13771 13772 /** 13773 * Used to indicate that the parent of this view should be invalidated. This functionality 13774 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13775 * which is necessary when various parent-managed properties of the view change, such as 13776 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13777 * an invalidation event to the parent. 13778 * 13779 * @hide 13780 */ 13781 protected void invalidateParentIfNeeded() { 13782 if (isHardwareAccelerated() && mParent instanceof View) { 13783 ((View) mParent).invalidate(true); 13784 } 13785 } 13786 13787 /** 13788 * @hide 13789 */ 13790 protected void invalidateParentIfNeededAndWasQuickRejected() { 13791 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13792 // View was rejected last time it was drawn by its parent; this may have changed 13793 invalidateParentIfNeeded(); 13794 } 13795 } 13796 13797 /** 13798 * Indicates whether this View is opaque. An opaque View guarantees that it will 13799 * draw all the pixels overlapping its bounds using a fully opaque color. 13800 * 13801 * Subclasses of View should override this method whenever possible to indicate 13802 * whether an instance is opaque. Opaque Views are treated in a special way by 13803 * the View hierarchy, possibly allowing it to perform optimizations during 13804 * invalidate/draw passes. 13805 * 13806 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13807 */ 13808 @ViewDebug.ExportedProperty(category = "drawing") 13809 public boolean isOpaque() { 13810 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13811 getFinalAlpha() >= 1.0f; 13812 } 13813 13814 /** 13815 * @hide 13816 */ 13817 protected void computeOpaqueFlags() { 13818 // Opaque if: 13819 // - Has a background 13820 // - Background is opaque 13821 // - Doesn't have scrollbars or scrollbars overlay 13822 13823 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13824 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13825 } else { 13826 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13827 } 13828 13829 final int flags = mViewFlags; 13830 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13831 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13832 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13833 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13834 } else { 13835 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13836 } 13837 } 13838 13839 /** 13840 * @hide 13841 */ 13842 protected boolean hasOpaqueScrollbars() { 13843 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13844 } 13845 13846 /** 13847 * @return A handler associated with the thread running the View. This 13848 * handler can be used to pump events in the UI events queue. 13849 */ 13850 public Handler getHandler() { 13851 final AttachInfo attachInfo = mAttachInfo; 13852 if (attachInfo != null) { 13853 return attachInfo.mHandler; 13854 } 13855 return null; 13856 } 13857 13858 /** 13859 * Returns the queue of runnable for this view. 13860 * 13861 * @return the queue of runnables for this view 13862 */ 13863 private HandlerActionQueue getRunQueue() { 13864 if (mRunQueue == null) { 13865 mRunQueue = new HandlerActionQueue(); 13866 } 13867 return mRunQueue; 13868 } 13869 13870 /** 13871 * Gets the view root associated with the View. 13872 * @return The view root, or null if none. 13873 * @hide 13874 */ 13875 public ViewRootImpl getViewRootImpl() { 13876 if (mAttachInfo != null) { 13877 return mAttachInfo.mViewRootImpl; 13878 } 13879 return null; 13880 } 13881 13882 /** 13883 * @hide 13884 */ 13885 public ThreadedRenderer getThreadedRenderer() { 13886 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 13887 } 13888 13889 /** 13890 * <p>Causes the Runnable to be added to the message queue. 13891 * The runnable will be run on the user interface thread.</p> 13892 * 13893 * @param action The Runnable that will be executed. 13894 * 13895 * @return Returns true if the Runnable was successfully placed in to the 13896 * message queue. Returns false on failure, usually because the 13897 * looper processing the message queue is exiting. 13898 * 13899 * @see #postDelayed 13900 * @see #removeCallbacks 13901 */ 13902 public boolean post(Runnable action) { 13903 final AttachInfo attachInfo = mAttachInfo; 13904 if (attachInfo != null) { 13905 return attachInfo.mHandler.post(action); 13906 } 13907 13908 // Postpone the runnable until we know on which thread it needs to run. 13909 // Assume that the runnable will be successfully placed after attach. 13910 getRunQueue().post(action); 13911 return true; 13912 } 13913 13914 /** 13915 * <p>Causes the Runnable to be added to the message queue, to be run 13916 * after the specified amount of time elapses. 13917 * The runnable will be run on the user interface thread.</p> 13918 * 13919 * @param action The Runnable that will be executed. 13920 * @param delayMillis The delay (in milliseconds) until the Runnable 13921 * will be executed. 13922 * 13923 * @return true if the Runnable was successfully placed in to the 13924 * message queue. Returns false on failure, usually because the 13925 * looper processing the message queue is exiting. Note that a 13926 * result of true does not mean the Runnable will be processed -- 13927 * if the looper is quit before the delivery time of the message 13928 * occurs then the message will be dropped. 13929 * 13930 * @see #post 13931 * @see #removeCallbacks 13932 */ 13933 public boolean postDelayed(Runnable action, long delayMillis) { 13934 final AttachInfo attachInfo = mAttachInfo; 13935 if (attachInfo != null) { 13936 return attachInfo.mHandler.postDelayed(action, delayMillis); 13937 } 13938 13939 // Postpone the runnable until we know on which thread it needs to run. 13940 // Assume that the runnable will be successfully placed after attach. 13941 getRunQueue().postDelayed(action, delayMillis); 13942 return true; 13943 } 13944 13945 /** 13946 * <p>Causes the Runnable to execute on the next animation time step. 13947 * The runnable will be run on the user interface thread.</p> 13948 * 13949 * @param action The Runnable that will be executed. 13950 * 13951 * @see #postOnAnimationDelayed 13952 * @see #removeCallbacks 13953 */ 13954 public void postOnAnimation(Runnable action) { 13955 final AttachInfo attachInfo = mAttachInfo; 13956 if (attachInfo != null) { 13957 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13958 Choreographer.CALLBACK_ANIMATION, action, null); 13959 } else { 13960 // Postpone the runnable until we know 13961 // on which thread it needs to run. 13962 getRunQueue().post(action); 13963 } 13964 } 13965 13966 /** 13967 * <p>Causes the Runnable to execute on the next animation time step, 13968 * after the specified amount of time elapses. 13969 * The runnable will be run on the user interface thread.</p> 13970 * 13971 * @param action The Runnable that will be executed. 13972 * @param delayMillis The delay (in milliseconds) until the Runnable 13973 * will be executed. 13974 * 13975 * @see #postOnAnimation 13976 * @see #removeCallbacks 13977 */ 13978 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13979 final AttachInfo attachInfo = mAttachInfo; 13980 if (attachInfo != null) { 13981 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13982 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13983 } else { 13984 // Postpone the runnable until we know 13985 // on which thread it needs to run. 13986 getRunQueue().postDelayed(action, delayMillis); 13987 } 13988 } 13989 13990 /** 13991 * <p>Removes the specified Runnable from the message queue.</p> 13992 * 13993 * @param action The Runnable to remove from the message handling queue 13994 * 13995 * @return true if this view could ask the Handler to remove the Runnable, 13996 * false otherwise. When the returned value is true, the Runnable 13997 * may or may not have been actually removed from the message queue 13998 * (for instance, if the Runnable was not in the queue already.) 13999 * 14000 * @see #post 14001 * @see #postDelayed 14002 * @see #postOnAnimation 14003 * @see #postOnAnimationDelayed 14004 */ 14005 public boolean removeCallbacks(Runnable action) { 14006 if (action != null) { 14007 final AttachInfo attachInfo = mAttachInfo; 14008 if (attachInfo != null) { 14009 attachInfo.mHandler.removeCallbacks(action); 14010 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14011 Choreographer.CALLBACK_ANIMATION, action, null); 14012 } 14013 getRunQueue().removeCallbacks(action); 14014 } 14015 return true; 14016 } 14017 14018 /** 14019 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 14020 * Use this to invalidate the View from a non-UI thread.</p> 14021 * 14022 * <p>This method can be invoked from outside of the UI thread 14023 * only when this View is attached to a window.</p> 14024 * 14025 * @see #invalidate() 14026 * @see #postInvalidateDelayed(long) 14027 */ 14028 public void postInvalidate() { 14029 postInvalidateDelayed(0); 14030 } 14031 14032 /** 14033 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14034 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 14035 * 14036 * <p>This method can be invoked from outside of the UI thread 14037 * only when this View is attached to a window.</p> 14038 * 14039 * @param left The left coordinate of the rectangle to invalidate. 14040 * @param top The top coordinate of the rectangle to invalidate. 14041 * @param right The right coordinate of the rectangle to invalidate. 14042 * @param bottom The bottom coordinate of the rectangle to invalidate. 14043 * 14044 * @see #invalidate(int, int, int, int) 14045 * @see #invalidate(Rect) 14046 * @see #postInvalidateDelayed(long, int, int, int, int) 14047 */ 14048 public void postInvalidate(int left, int top, int right, int bottom) { 14049 postInvalidateDelayed(0, left, top, right, bottom); 14050 } 14051 14052 /** 14053 * <p>Cause an invalidate to happen on a subsequent cycle through the event 14054 * loop. Waits for the specified amount of time.</p> 14055 * 14056 * <p>This method can be invoked from outside of the UI thread 14057 * only when this View is attached to a window.</p> 14058 * 14059 * @param delayMilliseconds the duration in milliseconds to delay the 14060 * invalidation by 14061 * 14062 * @see #invalidate() 14063 * @see #postInvalidate() 14064 */ 14065 public void postInvalidateDelayed(long delayMilliseconds) { 14066 // We try only with the AttachInfo because there's no point in invalidating 14067 // if we are not attached to our window 14068 final AttachInfo attachInfo = mAttachInfo; 14069 if (attachInfo != null) { 14070 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14071 } 14072 } 14073 14074 /** 14075 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14076 * through the event loop. Waits for the specified amount of time.</p> 14077 * 14078 * <p>This method can be invoked from outside of the UI thread 14079 * only when this View is attached to a window.</p> 14080 * 14081 * @param delayMilliseconds the duration in milliseconds to delay the 14082 * invalidation by 14083 * @param left The left coordinate of the rectangle to invalidate. 14084 * @param top The top coordinate of the rectangle to invalidate. 14085 * @param right The right coordinate of the rectangle to invalidate. 14086 * @param bottom The bottom coordinate of the rectangle to invalidate. 14087 * 14088 * @see #invalidate(int, int, int, int) 14089 * @see #invalidate(Rect) 14090 * @see #postInvalidate(int, int, int, int) 14091 */ 14092 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14093 int right, int bottom) { 14094 14095 // We try only with the AttachInfo because there's no point in invalidating 14096 // if we are not attached to our window 14097 final AttachInfo attachInfo = mAttachInfo; 14098 if (attachInfo != null) { 14099 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14100 info.target = this; 14101 info.left = left; 14102 info.top = top; 14103 info.right = right; 14104 info.bottom = bottom; 14105 14106 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14107 } 14108 } 14109 14110 /** 14111 * <p>Cause an invalidate to happen on the next animation time step, typically the 14112 * next display frame.</p> 14113 * 14114 * <p>This method can be invoked from outside of the UI thread 14115 * only when this View is attached to a window.</p> 14116 * 14117 * @see #invalidate() 14118 */ 14119 public void postInvalidateOnAnimation() { 14120 // We try only with the AttachInfo because there's no point in invalidating 14121 // if we are not attached to our window 14122 final AttachInfo attachInfo = mAttachInfo; 14123 if (attachInfo != null) { 14124 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14125 } 14126 } 14127 14128 /** 14129 * <p>Cause an invalidate of the specified area to happen on the next animation 14130 * time step, typically the next display frame.</p> 14131 * 14132 * <p>This method can be invoked from outside of the UI thread 14133 * only when this View is attached to a window.</p> 14134 * 14135 * @param left The left coordinate of the rectangle to invalidate. 14136 * @param top The top coordinate of the rectangle to invalidate. 14137 * @param right The right coordinate of the rectangle to invalidate. 14138 * @param bottom The bottom coordinate of the rectangle to invalidate. 14139 * 14140 * @see #invalidate(int, int, int, int) 14141 * @see #invalidate(Rect) 14142 */ 14143 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14144 // We try only with the AttachInfo because there's no point in invalidating 14145 // if we are not attached to our window 14146 final AttachInfo attachInfo = mAttachInfo; 14147 if (attachInfo != null) { 14148 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14149 info.target = this; 14150 info.left = left; 14151 info.top = top; 14152 info.right = right; 14153 info.bottom = bottom; 14154 14155 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14156 } 14157 } 14158 14159 /** 14160 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14161 * This event is sent at most once every 14162 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14163 */ 14164 private void postSendViewScrolledAccessibilityEventCallback() { 14165 if (mSendViewScrolledAccessibilityEvent == null) { 14166 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14167 } 14168 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14169 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14170 postDelayed(mSendViewScrolledAccessibilityEvent, 14171 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14172 } 14173 } 14174 14175 /** 14176 * Called by a parent to request that a child update its values for mScrollX 14177 * and mScrollY if necessary. This will typically be done if the child is 14178 * animating a scroll using a {@link android.widget.Scroller Scroller} 14179 * object. 14180 */ 14181 public void computeScroll() { 14182 } 14183 14184 /** 14185 * <p>Indicate whether the horizontal edges are faded when the view is 14186 * scrolled horizontally.</p> 14187 * 14188 * @return true if the horizontal edges should are faded on scroll, false 14189 * otherwise 14190 * 14191 * @see #setHorizontalFadingEdgeEnabled(boolean) 14192 * 14193 * @attr ref android.R.styleable#View_requiresFadingEdge 14194 */ 14195 public boolean isHorizontalFadingEdgeEnabled() { 14196 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14197 } 14198 14199 /** 14200 * <p>Define whether the horizontal edges should be faded when this view 14201 * is scrolled horizontally.</p> 14202 * 14203 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14204 * be faded when the view is scrolled 14205 * horizontally 14206 * 14207 * @see #isHorizontalFadingEdgeEnabled() 14208 * 14209 * @attr ref android.R.styleable#View_requiresFadingEdge 14210 */ 14211 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14212 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14213 if (horizontalFadingEdgeEnabled) { 14214 initScrollCache(); 14215 } 14216 14217 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14218 } 14219 } 14220 14221 /** 14222 * <p>Indicate whether the vertical edges are faded when the view is 14223 * scrolled horizontally.</p> 14224 * 14225 * @return true if the vertical edges should are faded on scroll, false 14226 * otherwise 14227 * 14228 * @see #setVerticalFadingEdgeEnabled(boolean) 14229 * 14230 * @attr ref android.R.styleable#View_requiresFadingEdge 14231 */ 14232 public boolean isVerticalFadingEdgeEnabled() { 14233 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14234 } 14235 14236 /** 14237 * <p>Define whether the vertical edges should be faded when this view 14238 * is scrolled vertically.</p> 14239 * 14240 * @param verticalFadingEdgeEnabled true if the vertical edges should 14241 * be faded when the view is scrolled 14242 * vertically 14243 * 14244 * @see #isVerticalFadingEdgeEnabled() 14245 * 14246 * @attr ref android.R.styleable#View_requiresFadingEdge 14247 */ 14248 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14249 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14250 if (verticalFadingEdgeEnabled) { 14251 initScrollCache(); 14252 } 14253 14254 mViewFlags ^= FADING_EDGE_VERTICAL; 14255 } 14256 } 14257 14258 /** 14259 * Returns the strength, or intensity, of the top faded edge. The strength is 14260 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14261 * returns 0.0 or 1.0 but no value in between. 14262 * 14263 * Subclasses should override this method to provide a smoother fade transition 14264 * when scrolling occurs. 14265 * 14266 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14267 */ 14268 protected float getTopFadingEdgeStrength() { 14269 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14270 } 14271 14272 /** 14273 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14274 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14275 * returns 0.0 or 1.0 but no value in between. 14276 * 14277 * Subclasses should override this method to provide a smoother fade transition 14278 * when scrolling occurs. 14279 * 14280 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14281 */ 14282 protected float getBottomFadingEdgeStrength() { 14283 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14284 computeVerticalScrollRange() ? 1.0f : 0.0f; 14285 } 14286 14287 /** 14288 * Returns the strength, or intensity, of the left faded edge. The strength is 14289 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14290 * returns 0.0 or 1.0 but no value in between. 14291 * 14292 * Subclasses should override this method to provide a smoother fade transition 14293 * when scrolling occurs. 14294 * 14295 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14296 */ 14297 protected float getLeftFadingEdgeStrength() { 14298 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14299 } 14300 14301 /** 14302 * Returns the strength, or intensity, of the right faded edge. The strength is 14303 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14304 * returns 0.0 or 1.0 but no value in between. 14305 * 14306 * Subclasses should override this method to provide a smoother fade transition 14307 * when scrolling occurs. 14308 * 14309 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14310 */ 14311 protected float getRightFadingEdgeStrength() { 14312 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14313 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14314 } 14315 14316 /** 14317 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14318 * scrollbar is not drawn by default.</p> 14319 * 14320 * @return true if the horizontal scrollbar should be painted, false 14321 * otherwise 14322 * 14323 * @see #setHorizontalScrollBarEnabled(boolean) 14324 */ 14325 public boolean isHorizontalScrollBarEnabled() { 14326 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14327 } 14328 14329 /** 14330 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14331 * scrollbar is not drawn by default.</p> 14332 * 14333 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14334 * be painted 14335 * 14336 * @see #isHorizontalScrollBarEnabled() 14337 */ 14338 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14339 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14340 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14341 computeOpaqueFlags(); 14342 resolvePadding(); 14343 } 14344 } 14345 14346 /** 14347 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14348 * scrollbar is not drawn by default.</p> 14349 * 14350 * @return true if the vertical scrollbar should be painted, false 14351 * otherwise 14352 * 14353 * @see #setVerticalScrollBarEnabled(boolean) 14354 */ 14355 public boolean isVerticalScrollBarEnabled() { 14356 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14357 } 14358 14359 /** 14360 * <p>Define whether the vertical scrollbar should be drawn or not. The 14361 * scrollbar is not drawn by default.</p> 14362 * 14363 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14364 * be painted 14365 * 14366 * @see #isVerticalScrollBarEnabled() 14367 */ 14368 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14369 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14370 mViewFlags ^= SCROLLBARS_VERTICAL; 14371 computeOpaqueFlags(); 14372 resolvePadding(); 14373 } 14374 } 14375 14376 /** 14377 * @hide 14378 */ 14379 protected void recomputePadding() { 14380 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14381 } 14382 14383 /** 14384 * Define whether scrollbars will fade when the view is not scrolling. 14385 * 14386 * @param fadeScrollbars whether to enable fading 14387 * 14388 * @attr ref android.R.styleable#View_fadeScrollbars 14389 */ 14390 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14391 initScrollCache(); 14392 final ScrollabilityCache scrollabilityCache = mScrollCache; 14393 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14394 if (fadeScrollbars) { 14395 scrollabilityCache.state = ScrollabilityCache.OFF; 14396 } else { 14397 scrollabilityCache.state = ScrollabilityCache.ON; 14398 } 14399 } 14400 14401 /** 14402 * 14403 * Returns true if scrollbars will fade when this view is not scrolling 14404 * 14405 * @return true if scrollbar fading is enabled 14406 * 14407 * @attr ref android.R.styleable#View_fadeScrollbars 14408 */ 14409 public boolean isScrollbarFadingEnabled() { 14410 return mScrollCache != null && mScrollCache.fadeScrollBars; 14411 } 14412 14413 /** 14414 * 14415 * Returns the delay before scrollbars fade. 14416 * 14417 * @return the delay before scrollbars fade 14418 * 14419 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14420 */ 14421 public int getScrollBarDefaultDelayBeforeFade() { 14422 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14423 mScrollCache.scrollBarDefaultDelayBeforeFade; 14424 } 14425 14426 /** 14427 * Define the delay before scrollbars fade. 14428 * 14429 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14430 * 14431 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14432 */ 14433 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14434 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14435 } 14436 14437 /** 14438 * 14439 * Returns the scrollbar fade duration. 14440 * 14441 * @return the scrollbar fade duration, in milliseconds 14442 * 14443 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14444 */ 14445 public int getScrollBarFadeDuration() { 14446 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14447 mScrollCache.scrollBarFadeDuration; 14448 } 14449 14450 /** 14451 * Define the scrollbar fade duration. 14452 * 14453 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 14454 * 14455 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14456 */ 14457 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14458 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14459 } 14460 14461 /** 14462 * 14463 * Returns the scrollbar size. 14464 * 14465 * @return the scrollbar size 14466 * 14467 * @attr ref android.R.styleable#View_scrollbarSize 14468 */ 14469 public int getScrollBarSize() { 14470 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14471 mScrollCache.scrollBarSize; 14472 } 14473 14474 /** 14475 * Define the scrollbar size. 14476 * 14477 * @param scrollBarSize - the scrollbar size 14478 * 14479 * @attr ref android.R.styleable#View_scrollbarSize 14480 */ 14481 public void setScrollBarSize(int scrollBarSize) { 14482 getScrollCache().scrollBarSize = scrollBarSize; 14483 } 14484 14485 /** 14486 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14487 * inset. When inset, they add to the padding of the view. And the scrollbars 14488 * can be drawn inside the padding area or on the edge of the view. For example, 14489 * if a view has a background drawable and you want to draw the scrollbars 14490 * inside the padding specified by the drawable, you can use 14491 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14492 * appear at the edge of the view, ignoring the padding, then you can use 14493 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14494 * @param style the style of the scrollbars. Should be one of 14495 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14496 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14497 * @see #SCROLLBARS_INSIDE_OVERLAY 14498 * @see #SCROLLBARS_INSIDE_INSET 14499 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14500 * @see #SCROLLBARS_OUTSIDE_INSET 14501 * 14502 * @attr ref android.R.styleable#View_scrollbarStyle 14503 */ 14504 public void setScrollBarStyle(@ScrollBarStyle int style) { 14505 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14506 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14507 computeOpaqueFlags(); 14508 resolvePadding(); 14509 } 14510 } 14511 14512 /** 14513 * <p>Returns the current scrollbar style.</p> 14514 * @return the current scrollbar style 14515 * @see #SCROLLBARS_INSIDE_OVERLAY 14516 * @see #SCROLLBARS_INSIDE_INSET 14517 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14518 * @see #SCROLLBARS_OUTSIDE_INSET 14519 * 14520 * @attr ref android.R.styleable#View_scrollbarStyle 14521 */ 14522 @ViewDebug.ExportedProperty(mapping = { 14523 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14524 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14525 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14526 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14527 }) 14528 @ScrollBarStyle 14529 public int getScrollBarStyle() { 14530 return mViewFlags & SCROLLBARS_STYLE_MASK; 14531 } 14532 14533 /** 14534 * <p>Compute the horizontal range that the horizontal scrollbar 14535 * represents.</p> 14536 * 14537 * <p>The range is expressed in arbitrary units that must be the same as the 14538 * units used by {@link #computeHorizontalScrollExtent()} and 14539 * {@link #computeHorizontalScrollOffset()}.</p> 14540 * 14541 * <p>The default range is the drawing width of this view.</p> 14542 * 14543 * @return the total horizontal range represented by the horizontal 14544 * scrollbar 14545 * 14546 * @see #computeHorizontalScrollExtent() 14547 * @see #computeHorizontalScrollOffset() 14548 * @see android.widget.ScrollBarDrawable 14549 */ 14550 protected int computeHorizontalScrollRange() { 14551 return getWidth(); 14552 } 14553 14554 /** 14555 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14556 * within the horizontal range. This value is used to compute the position 14557 * of the thumb within the scrollbar's track.</p> 14558 * 14559 * <p>The range is expressed in arbitrary units that must be the same as the 14560 * units used by {@link #computeHorizontalScrollRange()} and 14561 * {@link #computeHorizontalScrollExtent()}.</p> 14562 * 14563 * <p>The default offset is the scroll offset of this view.</p> 14564 * 14565 * @return the horizontal offset of the scrollbar's thumb 14566 * 14567 * @see #computeHorizontalScrollRange() 14568 * @see #computeHorizontalScrollExtent() 14569 * @see android.widget.ScrollBarDrawable 14570 */ 14571 protected int computeHorizontalScrollOffset() { 14572 return mScrollX; 14573 } 14574 14575 /** 14576 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14577 * within the horizontal range. This value is used to compute the length 14578 * of the thumb within the scrollbar's track.</p> 14579 * 14580 * <p>The range is expressed in arbitrary units that must be the same as the 14581 * units used by {@link #computeHorizontalScrollRange()} and 14582 * {@link #computeHorizontalScrollOffset()}.</p> 14583 * 14584 * <p>The default extent is the drawing width of this view.</p> 14585 * 14586 * @return the horizontal extent of the scrollbar's thumb 14587 * 14588 * @see #computeHorizontalScrollRange() 14589 * @see #computeHorizontalScrollOffset() 14590 * @see android.widget.ScrollBarDrawable 14591 */ 14592 protected int computeHorizontalScrollExtent() { 14593 return getWidth(); 14594 } 14595 14596 /** 14597 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14598 * 14599 * <p>The range is expressed in arbitrary units that must be the same as the 14600 * units used by {@link #computeVerticalScrollExtent()} and 14601 * {@link #computeVerticalScrollOffset()}.</p> 14602 * 14603 * @return the total vertical range represented by the vertical scrollbar 14604 * 14605 * <p>The default range is the drawing height of this view.</p> 14606 * 14607 * @see #computeVerticalScrollExtent() 14608 * @see #computeVerticalScrollOffset() 14609 * @see android.widget.ScrollBarDrawable 14610 */ 14611 protected int computeVerticalScrollRange() { 14612 return getHeight(); 14613 } 14614 14615 /** 14616 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14617 * within the horizontal range. This value is used to compute the position 14618 * of the thumb within the scrollbar's track.</p> 14619 * 14620 * <p>The range is expressed in arbitrary units that must be the same as the 14621 * units used by {@link #computeVerticalScrollRange()} and 14622 * {@link #computeVerticalScrollExtent()}.</p> 14623 * 14624 * <p>The default offset is the scroll offset of this view.</p> 14625 * 14626 * @return the vertical offset of the scrollbar's thumb 14627 * 14628 * @see #computeVerticalScrollRange() 14629 * @see #computeVerticalScrollExtent() 14630 * @see android.widget.ScrollBarDrawable 14631 */ 14632 protected int computeVerticalScrollOffset() { 14633 return mScrollY; 14634 } 14635 14636 /** 14637 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14638 * within the vertical range. This value is used to compute the length 14639 * of the thumb within the scrollbar's track.</p> 14640 * 14641 * <p>The range is expressed in arbitrary units that must be the same as the 14642 * units used by {@link #computeVerticalScrollRange()} and 14643 * {@link #computeVerticalScrollOffset()}.</p> 14644 * 14645 * <p>The default extent is the drawing height of this view.</p> 14646 * 14647 * @return the vertical extent of the scrollbar's thumb 14648 * 14649 * @see #computeVerticalScrollRange() 14650 * @see #computeVerticalScrollOffset() 14651 * @see android.widget.ScrollBarDrawable 14652 */ 14653 protected int computeVerticalScrollExtent() { 14654 return getHeight(); 14655 } 14656 14657 /** 14658 * Check if this view can be scrolled horizontally in a certain direction. 14659 * 14660 * @param direction Negative to check scrolling left, positive to check scrolling right. 14661 * @return true if this view can be scrolled in the specified direction, false otherwise. 14662 */ 14663 public boolean canScrollHorizontally(int direction) { 14664 final int offset = computeHorizontalScrollOffset(); 14665 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14666 if (range == 0) return false; 14667 if (direction < 0) { 14668 return offset > 0; 14669 } else { 14670 return offset < range - 1; 14671 } 14672 } 14673 14674 /** 14675 * Check if this view can be scrolled vertically in a certain direction. 14676 * 14677 * @param direction Negative to check scrolling up, positive to check scrolling down. 14678 * @return true if this view can be scrolled in the specified direction, false otherwise. 14679 */ 14680 public boolean canScrollVertically(int direction) { 14681 final int offset = computeVerticalScrollOffset(); 14682 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14683 if (range == 0) return false; 14684 if (direction < 0) { 14685 return offset > 0; 14686 } else { 14687 return offset < range - 1; 14688 } 14689 } 14690 14691 void getScrollIndicatorBounds(@NonNull Rect out) { 14692 out.left = mScrollX; 14693 out.right = mScrollX + mRight - mLeft; 14694 out.top = mScrollY; 14695 out.bottom = mScrollY + mBottom - mTop; 14696 } 14697 14698 private void onDrawScrollIndicators(Canvas c) { 14699 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14700 // No scroll indicators enabled. 14701 return; 14702 } 14703 14704 final Drawable dr = mScrollIndicatorDrawable; 14705 if (dr == null) { 14706 // Scroll indicators aren't supported here. 14707 return; 14708 } 14709 14710 final int h = dr.getIntrinsicHeight(); 14711 final int w = dr.getIntrinsicWidth(); 14712 final Rect rect = mAttachInfo.mTmpInvalRect; 14713 getScrollIndicatorBounds(rect); 14714 14715 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14716 final boolean canScrollUp = canScrollVertically(-1); 14717 if (canScrollUp) { 14718 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14719 dr.draw(c); 14720 } 14721 } 14722 14723 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14724 final boolean canScrollDown = canScrollVertically(1); 14725 if (canScrollDown) { 14726 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14727 dr.draw(c); 14728 } 14729 } 14730 14731 final int leftRtl; 14732 final int rightRtl; 14733 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14734 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14735 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14736 } else { 14737 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14738 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14739 } 14740 14741 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14742 if ((mPrivateFlags3 & leftMask) != 0) { 14743 final boolean canScrollLeft = canScrollHorizontally(-1); 14744 if (canScrollLeft) { 14745 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14746 dr.draw(c); 14747 } 14748 } 14749 14750 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14751 if ((mPrivateFlags3 & rightMask) != 0) { 14752 final boolean canScrollRight = canScrollHorizontally(1); 14753 if (canScrollRight) { 14754 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14755 dr.draw(c); 14756 } 14757 } 14758 } 14759 14760 private void getHorizontalScrollBarBounds(Rect bounds) { 14761 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14762 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14763 && !isVerticalScrollBarHidden(); 14764 final int size = getHorizontalScrollbarHeight(); 14765 final int verticalScrollBarGap = drawVerticalScrollBar ? 14766 getVerticalScrollbarWidth() : 0; 14767 final int width = mRight - mLeft; 14768 final int height = mBottom - mTop; 14769 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14770 bounds.left = mScrollX + (mPaddingLeft & inside); 14771 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14772 bounds.bottom = bounds.top + size; 14773 } 14774 14775 private void getVerticalScrollBarBounds(Rect bounds) { 14776 if (mRoundScrollbarRenderer == null) { 14777 getStraightVerticalScrollBarBounds(bounds); 14778 } else { 14779 getRoundVerticalScrollBarBounds(bounds); 14780 } 14781 } 14782 14783 private void getRoundVerticalScrollBarBounds(Rect bounds) { 14784 final int width = mRight - mLeft; 14785 final int height = mBottom - mTop; 14786 // Do not take padding into account as we always want the scrollbars 14787 // to hug the screen for round wearable devices. 14788 bounds.left = mScrollX; 14789 bounds.top = mScrollY; 14790 bounds.right = bounds.left + width; 14791 bounds.bottom = mScrollY + height; 14792 } 14793 14794 private void getStraightVerticalScrollBarBounds(Rect bounds) { 14795 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14796 final int size = getVerticalScrollbarWidth(); 14797 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14798 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14799 verticalScrollbarPosition = isLayoutRtl() ? 14800 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14801 } 14802 final int width = mRight - mLeft; 14803 final int height = mBottom - mTop; 14804 switch (verticalScrollbarPosition) { 14805 default: 14806 case SCROLLBAR_POSITION_RIGHT: 14807 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14808 break; 14809 case SCROLLBAR_POSITION_LEFT: 14810 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14811 break; 14812 } 14813 bounds.top = mScrollY + (mPaddingTop & inside); 14814 bounds.right = bounds.left + size; 14815 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14816 } 14817 14818 /** 14819 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14820 * scrollbars are painted only if they have been awakened first.</p> 14821 * 14822 * @param canvas the canvas on which to draw the scrollbars 14823 * 14824 * @see #awakenScrollBars(int) 14825 */ 14826 protected final void onDrawScrollBars(Canvas canvas) { 14827 // scrollbars are drawn only when the animation is running 14828 final ScrollabilityCache cache = mScrollCache; 14829 14830 if (cache != null) { 14831 14832 int state = cache.state; 14833 14834 if (state == ScrollabilityCache.OFF) { 14835 return; 14836 } 14837 14838 boolean invalidate = false; 14839 14840 if (state == ScrollabilityCache.FADING) { 14841 // We're fading -- get our fade interpolation 14842 if (cache.interpolatorValues == null) { 14843 cache.interpolatorValues = new float[1]; 14844 } 14845 14846 float[] values = cache.interpolatorValues; 14847 14848 // Stops the animation if we're done 14849 if (cache.scrollBarInterpolator.timeToValues(values) == 14850 Interpolator.Result.FREEZE_END) { 14851 cache.state = ScrollabilityCache.OFF; 14852 } else { 14853 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14854 } 14855 14856 // This will make the scroll bars inval themselves after 14857 // drawing. We only want this when we're fading so that 14858 // we prevent excessive redraws 14859 invalidate = true; 14860 } else { 14861 // We're just on -- but we may have been fading before so 14862 // reset alpha 14863 cache.scrollBar.mutate().setAlpha(255); 14864 } 14865 14866 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14867 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14868 && !isVerticalScrollBarHidden(); 14869 14870 // Fork out the scroll bar drawing for round wearable devices. 14871 if (mRoundScrollbarRenderer != null) { 14872 if (drawVerticalScrollBar) { 14873 final Rect bounds = cache.mScrollBarBounds; 14874 getVerticalScrollBarBounds(bounds); 14875 mRoundScrollbarRenderer.drawRoundScrollbars( 14876 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 14877 if (invalidate) { 14878 invalidate(); 14879 } 14880 } 14881 // Do not draw horizontal scroll bars for round wearable devices. 14882 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14883 final ScrollBarDrawable scrollBar = cache.scrollBar; 14884 14885 if (drawHorizontalScrollBar) { 14886 scrollBar.setParameters(computeHorizontalScrollRange(), 14887 computeHorizontalScrollOffset(), 14888 computeHorizontalScrollExtent(), false); 14889 final Rect bounds = cache.mScrollBarBounds; 14890 getHorizontalScrollBarBounds(bounds); 14891 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14892 bounds.right, bounds.bottom); 14893 if (invalidate) { 14894 invalidate(bounds); 14895 } 14896 } 14897 14898 if (drawVerticalScrollBar) { 14899 scrollBar.setParameters(computeVerticalScrollRange(), 14900 computeVerticalScrollOffset(), 14901 computeVerticalScrollExtent(), true); 14902 final Rect bounds = cache.mScrollBarBounds; 14903 getVerticalScrollBarBounds(bounds); 14904 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14905 bounds.right, bounds.bottom); 14906 if (invalidate) { 14907 invalidate(bounds); 14908 } 14909 } 14910 } 14911 } 14912 } 14913 14914 /** 14915 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14916 * FastScroller is visible. 14917 * @return whether to temporarily hide the vertical scrollbar 14918 * @hide 14919 */ 14920 protected boolean isVerticalScrollBarHidden() { 14921 return false; 14922 } 14923 14924 /** 14925 * <p>Draw the horizontal scrollbar if 14926 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14927 * 14928 * @param canvas the canvas on which to draw the scrollbar 14929 * @param scrollBar the scrollbar's drawable 14930 * 14931 * @see #isHorizontalScrollBarEnabled() 14932 * @see #computeHorizontalScrollRange() 14933 * @see #computeHorizontalScrollExtent() 14934 * @see #computeHorizontalScrollOffset() 14935 * @see android.widget.ScrollBarDrawable 14936 * @hide 14937 */ 14938 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14939 int l, int t, int r, int b) { 14940 scrollBar.setBounds(l, t, r, b); 14941 scrollBar.draw(canvas); 14942 } 14943 14944 /** 14945 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14946 * returns true.</p> 14947 * 14948 * @param canvas the canvas on which to draw the scrollbar 14949 * @param scrollBar the scrollbar's drawable 14950 * 14951 * @see #isVerticalScrollBarEnabled() 14952 * @see #computeVerticalScrollRange() 14953 * @see #computeVerticalScrollExtent() 14954 * @see #computeVerticalScrollOffset() 14955 * @see android.widget.ScrollBarDrawable 14956 * @hide 14957 */ 14958 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14959 int l, int t, int r, int b) { 14960 scrollBar.setBounds(l, t, r, b); 14961 scrollBar.draw(canvas); 14962 } 14963 14964 /** 14965 * Implement this to do your drawing. 14966 * 14967 * @param canvas the canvas on which the background will be drawn 14968 */ 14969 protected void onDraw(Canvas canvas) { 14970 } 14971 14972 /* 14973 * Caller is responsible for calling requestLayout if necessary. 14974 * (This allows addViewInLayout to not request a new layout.) 14975 */ 14976 void assignParent(ViewParent parent) { 14977 if (mParent == null) { 14978 mParent = parent; 14979 } else if (parent == null) { 14980 mParent = null; 14981 } else { 14982 throw new RuntimeException("view " + this + " being added, but" 14983 + " it already has a parent"); 14984 } 14985 } 14986 14987 /** 14988 * This is called when the view is attached to a window. At this point it 14989 * has a Surface and will start drawing. Note that this function is 14990 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14991 * however it may be called any time before the first onDraw -- including 14992 * before or after {@link #onMeasure(int, int)}. 14993 * 14994 * @see #onDetachedFromWindow() 14995 */ 14996 @CallSuper 14997 protected void onAttachedToWindow() { 14998 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14999 mParent.requestTransparentRegion(this); 15000 } 15001 15002 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15003 15004 jumpDrawablesToCurrentState(); 15005 15006 resetSubtreeAccessibilityStateChanged(); 15007 15008 // rebuild, since Outline not maintained while View is detached 15009 rebuildOutline(); 15010 15011 if (isFocused()) { 15012 InputMethodManager imm = InputMethodManager.peekInstance(); 15013 if (imm != null) { 15014 imm.focusIn(this); 15015 } 15016 } 15017 } 15018 15019 /** 15020 * Resolve all RTL related properties. 15021 * 15022 * @return true if resolution of RTL properties has been done 15023 * 15024 * @hide 15025 */ 15026 public boolean resolveRtlPropertiesIfNeeded() { 15027 if (!needRtlPropertiesResolution()) return false; 15028 15029 // Order is important here: LayoutDirection MUST be resolved first 15030 if (!isLayoutDirectionResolved()) { 15031 resolveLayoutDirection(); 15032 resolveLayoutParams(); 15033 } 15034 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 15035 if (!isTextDirectionResolved()) { 15036 resolveTextDirection(); 15037 } 15038 if (!isTextAlignmentResolved()) { 15039 resolveTextAlignment(); 15040 } 15041 // Should resolve Drawables before Padding because we need the layout direction of the 15042 // Drawable to correctly resolve Padding. 15043 if (!areDrawablesResolved()) { 15044 resolveDrawables(); 15045 } 15046 if (!isPaddingResolved()) { 15047 resolvePadding(); 15048 } 15049 onRtlPropertiesChanged(getLayoutDirection()); 15050 return true; 15051 } 15052 15053 /** 15054 * Reset resolution of all RTL related properties. 15055 * 15056 * @hide 15057 */ 15058 public void resetRtlProperties() { 15059 resetResolvedLayoutDirection(); 15060 resetResolvedTextDirection(); 15061 resetResolvedTextAlignment(); 15062 resetResolvedPadding(); 15063 resetResolvedDrawables(); 15064 } 15065 15066 /** 15067 * @see #onScreenStateChanged(int) 15068 */ 15069 void dispatchScreenStateChanged(int screenState) { 15070 onScreenStateChanged(screenState); 15071 } 15072 15073 /** 15074 * This method is called whenever the state of the screen this view is 15075 * attached to changes. A state change will usually occurs when the screen 15076 * turns on or off (whether it happens automatically or the user does it 15077 * manually.) 15078 * 15079 * @param screenState The new state of the screen. Can be either 15080 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 15081 */ 15082 public void onScreenStateChanged(int screenState) { 15083 } 15084 15085 /** 15086 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 15087 */ 15088 private boolean hasRtlSupport() { 15089 return mContext.getApplicationInfo().hasRtlSupport(); 15090 } 15091 15092 /** 15093 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 15094 * RTL not supported) 15095 */ 15096 private boolean isRtlCompatibilityMode() { 15097 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 15098 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 15099 } 15100 15101 /** 15102 * @return true if RTL properties need resolution. 15103 * 15104 */ 15105 private boolean needRtlPropertiesResolution() { 15106 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15107 } 15108 15109 /** 15110 * Called when any RTL property (layout direction or text direction or text alignment) has 15111 * been changed. 15112 * 15113 * Subclasses need to override this method to take care of cached information that depends on the 15114 * resolved layout direction, or to inform child views that inherit their layout direction. 15115 * 15116 * The default implementation does nothing. 15117 * 15118 * @param layoutDirection the direction of the layout 15119 * 15120 * @see #LAYOUT_DIRECTION_LTR 15121 * @see #LAYOUT_DIRECTION_RTL 15122 */ 15123 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15124 } 15125 15126 /** 15127 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15128 * that the parent directionality can and will be resolved before its children. 15129 * 15130 * @return true if resolution has been done, false otherwise. 15131 * 15132 * @hide 15133 */ 15134 public boolean resolveLayoutDirection() { 15135 // Clear any previous layout direction resolution 15136 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15137 15138 if (hasRtlSupport()) { 15139 // Set resolved depending on layout direction 15140 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15141 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15142 case LAYOUT_DIRECTION_INHERIT: 15143 // We cannot resolve yet. LTR is by default and let the resolution happen again 15144 // later to get the correct resolved value 15145 if (!canResolveLayoutDirection()) return false; 15146 15147 // Parent has not yet resolved, LTR is still the default 15148 try { 15149 if (!mParent.isLayoutDirectionResolved()) return false; 15150 15151 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15152 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15153 } 15154 } catch (AbstractMethodError e) { 15155 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15156 " does not fully implement ViewParent", e); 15157 } 15158 break; 15159 case LAYOUT_DIRECTION_RTL: 15160 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15161 break; 15162 case LAYOUT_DIRECTION_LOCALE: 15163 if((LAYOUT_DIRECTION_RTL == 15164 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15165 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15166 } 15167 break; 15168 default: 15169 // Nothing to do, LTR by default 15170 } 15171 } 15172 15173 // Set to resolved 15174 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15175 return true; 15176 } 15177 15178 /** 15179 * Check if layout direction resolution can be done. 15180 * 15181 * @return true if layout direction resolution can be done otherwise return false. 15182 */ 15183 public boolean canResolveLayoutDirection() { 15184 switch (getRawLayoutDirection()) { 15185 case LAYOUT_DIRECTION_INHERIT: 15186 if (mParent != null) { 15187 try { 15188 return mParent.canResolveLayoutDirection(); 15189 } catch (AbstractMethodError e) { 15190 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15191 " does not fully implement ViewParent", e); 15192 } 15193 } 15194 return false; 15195 15196 default: 15197 return true; 15198 } 15199 } 15200 15201 /** 15202 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15203 * {@link #onMeasure(int, int)}. 15204 * 15205 * @hide 15206 */ 15207 public void resetResolvedLayoutDirection() { 15208 // Reset the current resolved bits 15209 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15210 } 15211 15212 /** 15213 * @return true if the layout direction is inherited. 15214 * 15215 * @hide 15216 */ 15217 public boolean isLayoutDirectionInherited() { 15218 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15219 } 15220 15221 /** 15222 * @return true if layout direction has been resolved. 15223 */ 15224 public boolean isLayoutDirectionResolved() { 15225 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15226 } 15227 15228 /** 15229 * Return if padding has been resolved 15230 * 15231 * @hide 15232 */ 15233 boolean isPaddingResolved() { 15234 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15235 } 15236 15237 /** 15238 * Resolves padding depending on layout direction, if applicable, and 15239 * recomputes internal padding values to adjust for scroll bars. 15240 * 15241 * @hide 15242 */ 15243 public void resolvePadding() { 15244 final int resolvedLayoutDirection = getLayoutDirection(); 15245 15246 if (!isRtlCompatibilityMode()) { 15247 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15248 // If start / end padding are defined, they will be resolved (hence overriding) to 15249 // left / right or right / left depending on the resolved layout direction. 15250 // If start / end padding are not defined, use the left / right ones. 15251 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15252 Rect padding = sThreadLocal.get(); 15253 if (padding == null) { 15254 padding = new Rect(); 15255 sThreadLocal.set(padding); 15256 } 15257 mBackground.getPadding(padding); 15258 if (!mLeftPaddingDefined) { 15259 mUserPaddingLeftInitial = padding.left; 15260 } 15261 if (!mRightPaddingDefined) { 15262 mUserPaddingRightInitial = padding.right; 15263 } 15264 } 15265 switch (resolvedLayoutDirection) { 15266 case LAYOUT_DIRECTION_RTL: 15267 if (mUserPaddingStart != UNDEFINED_PADDING) { 15268 mUserPaddingRight = mUserPaddingStart; 15269 } else { 15270 mUserPaddingRight = mUserPaddingRightInitial; 15271 } 15272 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15273 mUserPaddingLeft = mUserPaddingEnd; 15274 } else { 15275 mUserPaddingLeft = mUserPaddingLeftInitial; 15276 } 15277 break; 15278 case LAYOUT_DIRECTION_LTR: 15279 default: 15280 if (mUserPaddingStart != UNDEFINED_PADDING) { 15281 mUserPaddingLeft = mUserPaddingStart; 15282 } else { 15283 mUserPaddingLeft = mUserPaddingLeftInitial; 15284 } 15285 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15286 mUserPaddingRight = mUserPaddingEnd; 15287 } else { 15288 mUserPaddingRight = mUserPaddingRightInitial; 15289 } 15290 } 15291 15292 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15293 } 15294 15295 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15296 onRtlPropertiesChanged(resolvedLayoutDirection); 15297 15298 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15299 } 15300 15301 /** 15302 * Reset the resolved layout direction. 15303 * 15304 * @hide 15305 */ 15306 public void resetResolvedPadding() { 15307 resetResolvedPaddingInternal(); 15308 } 15309 15310 /** 15311 * Used when we only want to reset *this* view's padding and not trigger overrides 15312 * in ViewGroup that reset children too. 15313 */ 15314 void resetResolvedPaddingInternal() { 15315 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15316 } 15317 15318 /** 15319 * This is called when the view is detached from a window. At this point it 15320 * no longer has a surface for drawing. 15321 * 15322 * @see #onAttachedToWindow() 15323 */ 15324 @CallSuper 15325 protected void onDetachedFromWindow() { 15326 } 15327 15328 /** 15329 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15330 * after onDetachedFromWindow(). 15331 * 15332 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15333 * The super method should be called at the end of the overridden method to ensure 15334 * subclasses are destroyed first 15335 * 15336 * @hide 15337 */ 15338 @CallSuper 15339 protected void onDetachedFromWindowInternal() { 15340 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15341 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15342 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15343 15344 removeUnsetPressCallback(); 15345 removeLongPressCallback(); 15346 removePerformClickCallback(); 15347 removeSendViewScrolledAccessibilityEventCallback(); 15348 stopNestedScroll(); 15349 15350 // Anything that started animating right before detach should already 15351 // be in its final state when re-attached. 15352 jumpDrawablesToCurrentState(); 15353 15354 destroyDrawingCache(); 15355 15356 cleanupDraw(); 15357 mCurrentAnimation = null; 15358 } 15359 15360 private void cleanupDraw() { 15361 resetDisplayList(); 15362 if (mAttachInfo != null) { 15363 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15364 } 15365 } 15366 15367 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15368 } 15369 15370 /** 15371 * @return The number of times this view has been attached to a window 15372 */ 15373 protected int getWindowAttachCount() { 15374 return mWindowAttachCount; 15375 } 15376 15377 /** 15378 * Retrieve a unique token identifying the window this view is attached to. 15379 * @return Return the window's token for use in 15380 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15381 */ 15382 public IBinder getWindowToken() { 15383 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15384 } 15385 15386 /** 15387 * Retrieve the {@link WindowId} for the window this view is 15388 * currently attached to. 15389 */ 15390 public WindowId getWindowId() { 15391 if (mAttachInfo == null) { 15392 return null; 15393 } 15394 if (mAttachInfo.mWindowId == null) { 15395 try { 15396 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15397 mAttachInfo.mWindowToken); 15398 mAttachInfo.mWindowId = new WindowId( 15399 mAttachInfo.mIWindowId); 15400 } catch (RemoteException e) { 15401 } 15402 } 15403 return mAttachInfo.mWindowId; 15404 } 15405 15406 /** 15407 * Retrieve a unique token identifying the top-level "real" window of 15408 * the window that this view is attached to. That is, this is like 15409 * {@link #getWindowToken}, except if the window this view in is a panel 15410 * window (attached to another containing window), then the token of 15411 * the containing window is returned instead. 15412 * 15413 * @return Returns the associated window token, either 15414 * {@link #getWindowToken()} or the containing window's token. 15415 */ 15416 public IBinder getApplicationWindowToken() { 15417 AttachInfo ai = mAttachInfo; 15418 if (ai != null) { 15419 IBinder appWindowToken = ai.mPanelParentWindowToken; 15420 if (appWindowToken == null) { 15421 appWindowToken = ai.mWindowToken; 15422 } 15423 return appWindowToken; 15424 } 15425 return null; 15426 } 15427 15428 /** 15429 * Gets the logical display to which the view's window has been attached. 15430 * 15431 * @return The logical display, or null if the view is not currently attached to a window. 15432 */ 15433 public Display getDisplay() { 15434 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15435 } 15436 15437 /** 15438 * Retrieve private session object this view hierarchy is using to 15439 * communicate with the window manager. 15440 * @return the session object to communicate with the window manager 15441 */ 15442 /*package*/ IWindowSession getWindowSession() { 15443 return mAttachInfo != null ? mAttachInfo.mSession : null; 15444 } 15445 15446 /** 15447 * Return the visibility value of the least visible component passed. 15448 */ 15449 int combineVisibility(int vis1, int vis2) { 15450 // This works because VISIBLE < INVISIBLE < GONE. 15451 return Math.max(vis1, vis2); 15452 } 15453 15454 /** 15455 * @param info the {@link android.view.View.AttachInfo} to associated with 15456 * this view 15457 */ 15458 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15459 mAttachInfo = info; 15460 if (mOverlay != null) { 15461 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15462 } 15463 mWindowAttachCount++; 15464 // We will need to evaluate the drawable state at least once. 15465 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15466 if (mFloatingTreeObserver != null) { 15467 info.mTreeObserver.merge(mFloatingTreeObserver); 15468 mFloatingTreeObserver = null; 15469 } 15470 15471 registerPendingFrameMetricsObservers(); 15472 15473 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15474 mAttachInfo.mScrollContainers.add(this); 15475 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15476 } 15477 // Transfer all pending runnables. 15478 if (mRunQueue != null) { 15479 mRunQueue.executeActions(info.mHandler); 15480 mRunQueue = null; 15481 } 15482 performCollectViewAttributes(mAttachInfo, visibility); 15483 onAttachedToWindow(); 15484 15485 ListenerInfo li = mListenerInfo; 15486 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15487 li != null ? li.mOnAttachStateChangeListeners : null; 15488 if (listeners != null && listeners.size() > 0) { 15489 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15490 // perform the dispatching. The iterator is a safe guard against listeners that 15491 // could mutate the list by calling the various add/remove methods. This prevents 15492 // the array from being modified while we iterate it. 15493 for (OnAttachStateChangeListener listener : listeners) { 15494 listener.onViewAttachedToWindow(this); 15495 } 15496 } 15497 15498 int vis = info.mWindowVisibility; 15499 if (vis != GONE) { 15500 onWindowVisibilityChanged(vis); 15501 if (isShown()) { 15502 // Calling onVisibilityAggregated directly here since the subtree will also 15503 // receive dispatchAttachedToWindow and this same call 15504 onVisibilityAggregated(vis == VISIBLE); 15505 } 15506 } 15507 15508 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15509 // As all views in the subtree will already receive dispatchAttachedToWindow 15510 // traversing the subtree again here is not desired. 15511 onVisibilityChanged(this, visibility); 15512 15513 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15514 // If nobody has evaluated the drawable state yet, then do it now. 15515 refreshDrawableState(); 15516 } 15517 needGlobalAttributesUpdate(false); 15518 } 15519 15520 void dispatchDetachedFromWindow() { 15521 AttachInfo info = mAttachInfo; 15522 if (info != null) { 15523 int vis = info.mWindowVisibility; 15524 if (vis != GONE) { 15525 onWindowVisibilityChanged(GONE); 15526 if (isShown()) { 15527 // Invoking onVisibilityAggregated directly here since the subtree 15528 // will also receive detached from window 15529 onVisibilityAggregated(false); 15530 } 15531 } 15532 } 15533 15534 onDetachedFromWindow(); 15535 onDetachedFromWindowInternal(); 15536 15537 InputMethodManager imm = InputMethodManager.peekInstance(); 15538 if (imm != null) { 15539 imm.onViewDetachedFromWindow(this); 15540 } 15541 15542 ListenerInfo li = mListenerInfo; 15543 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15544 li != null ? li.mOnAttachStateChangeListeners : null; 15545 if (listeners != null && listeners.size() > 0) { 15546 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15547 // perform the dispatching. The iterator is a safe guard against listeners that 15548 // could mutate the list by calling the various add/remove methods. This prevents 15549 // the array from being modified while we iterate it. 15550 for (OnAttachStateChangeListener listener : listeners) { 15551 listener.onViewDetachedFromWindow(this); 15552 } 15553 } 15554 15555 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15556 mAttachInfo.mScrollContainers.remove(this); 15557 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15558 } 15559 15560 mAttachInfo = null; 15561 if (mOverlay != null) { 15562 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15563 } 15564 } 15565 15566 /** 15567 * Cancel any deferred high-level input events that were previously posted to the event queue. 15568 * 15569 * <p>Many views post high-level events such as click handlers to the event queue 15570 * to run deferred in order to preserve a desired user experience - clearing visible 15571 * pressed states before executing, etc. This method will abort any events of this nature 15572 * that are currently in flight.</p> 15573 * 15574 * <p>Custom views that generate their own high-level deferred input events should override 15575 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15576 * 15577 * <p>This will also cancel pending input events for any child views.</p> 15578 * 15579 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15580 * This will not impact newer events posted after this call that may occur as a result of 15581 * lower-level input events still waiting in the queue. If you are trying to prevent 15582 * double-submitted events for the duration of some sort of asynchronous transaction 15583 * you should also take other steps to protect against unexpected double inputs e.g. calling 15584 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15585 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15586 */ 15587 public final void cancelPendingInputEvents() { 15588 dispatchCancelPendingInputEvents(); 15589 } 15590 15591 /** 15592 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15593 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15594 */ 15595 void dispatchCancelPendingInputEvents() { 15596 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15597 onCancelPendingInputEvents(); 15598 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15599 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15600 " did not call through to super.onCancelPendingInputEvents()"); 15601 } 15602 } 15603 15604 /** 15605 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15606 * a parent view. 15607 * 15608 * <p>This method is responsible for removing any pending high-level input events that were 15609 * posted to the event queue to run later. Custom view classes that post their own deferred 15610 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15611 * {@link android.os.Handler} should override this method, call 15612 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15613 * </p> 15614 */ 15615 public void onCancelPendingInputEvents() { 15616 removePerformClickCallback(); 15617 cancelLongPress(); 15618 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15619 } 15620 15621 /** 15622 * Store this view hierarchy's frozen state into the given container. 15623 * 15624 * @param container The SparseArray in which to save the view's state. 15625 * 15626 * @see #restoreHierarchyState(android.util.SparseArray) 15627 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15628 * @see #onSaveInstanceState() 15629 */ 15630 public void saveHierarchyState(SparseArray<Parcelable> container) { 15631 dispatchSaveInstanceState(container); 15632 } 15633 15634 /** 15635 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15636 * this view and its children. May be overridden to modify how freezing happens to a 15637 * view's children; for example, some views may want to not store state for their children. 15638 * 15639 * @param container The SparseArray in which to save the view's state. 15640 * 15641 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15642 * @see #saveHierarchyState(android.util.SparseArray) 15643 * @see #onSaveInstanceState() 15644 */ 15645 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15646 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15647 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15648 Parcelable state = onSaveInstanceState(); 15649 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15650 throw new IllegalStateException( 15651 "Derived class did not call super.onSaveInstanceState()"); 15652 } 15653 if (state != null) { 15654 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15655 // + ": " + state); 15656 container.put(mID, state); 15657 } 15658 } 15659 } 15660 15661 /** 15662 * Hook allowing a view to generate a representation of its internal state 15663 * that can later be used to create a new instance with that same state. 15664 * This state should only contain information that is not persistent or can 15665 * not be reconstructed later. For example, you will never store your 15666 * current position on screen because that will be computed again when a 15667 * new instance of the view is placed in its view hierarchy. 15668 * <p> 15669 * Some examples of things you may store here: the current cursor position 15670 * in a text view (but usually not the text itself since that is stored in a 15671 * content provider or other persistent storage), the currently selected 15672 * item in a list view. 15673 * 15674 * @return Returns a Parcelable object containing the view's current dynamic 15675 * state, or null if there is nothing interesting to save. The 15676 * default implementation returns null. 15677 * @see #onRestoreInstanceState(android.os.Parcelable) 15678 * @see #saveHierarchyState(android.util.SparseArray) 15679 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15680 * @see #setSaveEnabled(boolean) 15681 */ 15682 @CallSuper 15683 protected Parcelable onSaveInstanceState() { 15684 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15685 if (mStartActivityRequestWho != null) { 15686 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15687 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15688 return state; 15689 } 15690 return BaseSavedState.EMPTY_STATE; 15691 } 15692 15693 /** 15694 * Restore this view hierarchy's frozen state from the given container. 15695 * 15696 * @param container The SparseArray which holds previously frozen states. 15697 * 15698 * @see #saveHierarchyState(android.util.SparseArray) 15699 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15700 * @see #onRestoreInstanceState(android.os.Parcelable) 15701 */ 15702 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15703 dispatchRestoreInstanceState(container); 15704 } 15705 15706 /** 15707 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15708 * state for this view and its children. May be overridden to modify how restoring 15709 * happens to a view's children; for example, some views may want to not store state 15710 * for their children. 15711 * 15712 * @param container The SparseArray which holds previously saved state. 15713 * 15714 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15715 * @see #restoreHierarchyState(android.util.SparseArray) 15716 * @see #onRestoreInstanceState(android.os.Parcelable) 15717 */ 15718 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15719 if (mID != NO_ID) { 15720 Parcelable state = container.get(mID); 15721 if (state != null) { 15722 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15723 // + ": " + state); 15724 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15725 onRestoreInstanceState(state); 15726 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15727 throw new IllegalStateException( 15728 "Derived class did not call super.onRestoreInstanceState()"); 15729 } 15730 } 15731 } 15732 } 15733 15734 /** 15735 * Hook allowing a view to re-apply a representation of its internal state that had previously 15736 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15737 * null state. 15738 * 15739 * @param state The frozen state that had previously been returned by 15740 * {@link #onSaveInstanceState}. 15741 * 15742 * @see #onSaveInstanceState() 15743 * @see #restoreHierarchyState(android.util.SparseArray) 15744 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15745 */ 15746 @CallSuper 15747 protected void onRestoreInstanceState(Parcelable state) { 15748 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15749 if (state != null && !(state instanceof AbsSavedState)) { 15750 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15751 + "received " + state.getClass().toString() + " instead. This usually happens " 15752 + "when two views of different type have the same id in the same hierarchy. " 15753 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15754 + "other views do not use the same id."); 15755 } 15756 if (state != null && state instanceof BaseSavedState) { 15757 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15758 } 15759 } 15760 15761 /** 15762 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15763 * 15764 * @return the drawing start time in milliseconds 15765 */ 15766 public long getDrawingTime() { 15767 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15768 } 15769 15770 /** 15771 * <p>Enables or disables the duplication of the parent's state into this view. When 15772 * duplication is enabled, this view gets its drawable state from its parent rather 15773 * than from its own internal properties.</p> 15774 * 15775 * <p>Note: in the current implementation, setting this property to true after the 15776 * view was added to a ViewGroup might have no effect at all. This property should 15777 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15778 * 15779 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15780 * property is enabled, an exception will be thrown.</p> 15781 * 15782 * <p>Note: if the child view uses and updates additional states which are unknown to the 15783 * parent, these states should not be affected by this method.</p> 15784 * 15785 * @param enabled True to enable duplication of the parent's drawable state, false 15786 * to disable it. 15787 * 15788 * @see #getDrawableState() 15789 * @see #isDuplicateParentStateEnabled() 15790 */ 15791 public void setDuplicateParentStateEnabled(boolean enabled) { 15792 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15793 } 15794 15795 /** 15796 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15797 * 15798 * @return True if this view's drawable state is duplicated from the parent, 15799 * false otherwise 15800 * 15801 * @see #getDrawableState() 15802 * @see #setDuplicateParentStateEnabled(boolean) 15803 */ 15804 public boolean isDuplicateParentStateEnabled() { 15805 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15806 } 15807 15808 /** 15809 * <p>Specifies the type of layer backing this view. The layer can be 15810 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15811 * {@link #LAYER_TYPE_HARDWARE}.</p> 15812 * 15813 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15814 * instance that controls how the layer is composed on screen. The following 15815 * properties of the paint are taken into account when composing the layer:</p> 15816 * <ul> 15817 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15818 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15819 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15820 * </ul> 15821 * 15822 * <p>If this view has an alpha value set to < 1.0 by calling 15823 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15824 * by this view's alpha value.</p> 15825 * 15826 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15827 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15828 * for more information on when and how to use layers.</p> 15829 * 15830 * @param layerType The type of layer to use with this view, must be one of 15831 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15832 * {@link #LAYER_TYPE_HARDWARE} 15833 * @param paint The paint used to compose the layer. This argument is optional 15834 * and can be null. It is ignored when the layer type is 15835 * {@link #LAYER_TYPE_NONE} 15836 * 15837 * @see #getLayerType() 15838 * @see #LAYER_TYPE_NONE 15839 * @see #LAYER_TYPE_SOFTWARE 15840 * @see #LAYER_TYPE_HARDWARE 15841 * @see #setAlpha(float) 15842 * 15843 * @attr ref android.R.styleable#View_layerType 15844 */ 15845 public void setLayerType(int layerType, @Nullable Paint paint) { 15846 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15847 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15848 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15849 } 15850 15851 boolean typeChanged = mRenderNode.setLayerType(layerType); 15852 15853 if (!typeChanged) { 15854 setLayerPaint(paint); 15855 return; 15856 } 15857 15858 if (layerType != LAYER_TYPE_SOFTWARE) { 15859 // Destroy any previous software drawing cache if present 15860 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 15861 // drawing cache created in View#draw when drawing to a SW canvas. 15862 destroyDrawingCache(); 15863 } 15864 15865 mLayerType = layerType; 15866 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15867 mRenderNode.setLayerPaint(mLayerPaint); 15868 15869 // draw() behaves differently if we are on a layer, so we need to 15870 // invalidate() here 15871 invalidateParentCaches(); 15872 invalidate(true); 15873 } 15874 15875 /** 15876 * Updates the {@link Paint} object used with the current layer (used only if the current 15877 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15878 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15879 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15880 * ensure that the view gets redrawn immediately. 15881 * 15882 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15883 * instance that controls how the layer is composed on screen. The following 15884 * properties of the paint are taken into account when composing the layer:</p> 15885 * <ul> 15886 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15887 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15888 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15889 * </ul> 15890 * 15891 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15892 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15893 * 15894 * @param paint The paint used to compose the layer. This argument is optional 15895 * and can be null. It is ignored when the layer type is 15896 * {@link #LAYER_TYPE_NONE} 15897 * 15898 * @see #setLayerType(int, android.graphics.Paint) 15899 */ 15900 public void setLayerPaint(@Nullable Paint paint) { 15901 int layerType = getLayerType(); 15902 if (layerType != LAYER_TYPE_NONE) { 15903 mLayerPaint = paint; 15904 if (layerType == LAYER_TYPE_HARDWARE) { 15905 if (mRenderNode.setLayerPaint(paint)) { 15906 invalidateViewProperty(false, false); 15907 } 15908 } else { 15909 invalidate(); 15910 } 15911 } 15912 } 15913 15914 /** 15915 * Indicates what type of layer is currently associated with this view. By default 15916 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15917 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15918 * for more information on the different types of layers. 15919 * 15920 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15921 * {@link #LAYER_TYPE_HARDWARE} 15922 * 15923 * @see #setLayerType(int, android.graphics.Paint) 15924 * @see #buildLayer() 15925 * @see #LAYER_TYPE_NONE 15926 * @see #LAYER_TYPE_SOFTWARE 15927 * @see #LAYER_TYPE_HARDWARE 15928 */ 15929 public int getLayerType() { 15930 return mLayerType; 15931 } 15932 15933 /** 15934 * Forces this view's layer to be created and this view to be rendered 15935 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15936 * invoking this method will have no effect. 15937 * 15938 * This method can for instance be used to render a view into its layer before 15939 * starting an animation. If this view is complex, rendering into the layer 15940 * before starting the animation will avoid skipping frames. 15941 * 15942 * @throws IllegalStateException If this view is not attached to a window 15943 * 15944 * @see #setLayerType(int, android.graphics.Paint) 15945 */ 15946 public void buildLayer() { 15947 if (mLayerType == LAYER_TYPE_NONE) return; 15948 15949 final AttachInfo attachInfo = mAttachInfo; 15950 if (attachInfo == null) { 15951 throw new IllegalStateException("This view must be attached to a window first"); 15952 } 15953 15954 if (getWidth() == 0 || getHeight() == 0) { 15955 return; 15956 } 15957 15958 switch (mLayerType) { 15959 case LAYER_TYPE_HARDWARE: 15960 updateDisplayListIfDirty(); 15961 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 15962 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 15963 } 15964 break; 15965 case LAYER_TYPE_SOFTWARE: 15966 buildDrawingCache(true); 15967 break; 15968 } 15969 } 15970 15971 /** 15972 * Destroys all hardware rendering resources. This method is invoked 15973 * when the system needs to reclaim resources. Upon execution of this 15974 * method, you should free any OpenGL resources created by the view. 15975 * 15976 * Note: you <strong>must</strong> call 15977 * <code>super.destroyHardwareResources()</code> when overriding 15978 * this method. 15979 * 15980 * @hide 15981 */ 15982 @CallSuper 15983 protected void destroyHardwareResources() { 15984 // Although the Layer will be destroyed by RenderNode, we want to release 15985 // the staging display list, which is also a signal to RenderNode that it's 15986 // safe to free its copy of the display list as it knows that we will 15987 // push an updated DisplayList if we try to draw again 15988 resetDisplayList(); 15989 } 15990 15991 /** 15992 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15993 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15994 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15995 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15996 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15997 * null.</p> 15998 * 15999 * <p>Enabling the drawing cache is similar to 16000 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 16001 * acceleration is turned off. When hardware acceleration is turned on, enabling the 16002 * drawing cache has no effect on rendering because the system uses a different mechanism 16003 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 16004 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 16005 * for information on how to enable software and hardware layers.</p> 16006 * 16007 * <p>This API can be used to manually generate 16008 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 16009 * {@link #getDrawingCache()}.</p> 16010 * 16011 * @param enabled true to enable the drawing cache, false otherwise 16012 * 16013 * @see #isDrawingCacheEnabled() 16014 * @see #getDrawingCache() 16015 * @see #buildDrawingCache() 16016 * @see #setLayerType(int, android.graphics.Paint) 16017 */ 16018 public void setDrawingCacheEnabled(boolean enabled) { 16019 mCachingFailed = false; 16020 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 16021 } 16022 16023 /** 16024 * <p>Indicates whether the drawing cache is enabled for this view.</p> 16025 * 16026 * @return true if the drawing cache is enabled 16027 * 16028 * @see #setDrawingCacheEnabled(boolean) 16029 * @see #getDrawingCache() 16030 */ 16031 @ViewDebug.ExportedProperty(category = "drawing") 16032 public boolean isDrawingCacheEnabled() { 16033 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 16034 } 16035 16036 /** 16037 * Debugging utility which recursively outputs the dirty state of a view and its 16038 * descendants. 16039 * 16040 * @hide 16041 */ 16042 @SuppressWarnings({"UnusedDeclaration"}) 16043 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 16044 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 16045 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 16046 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 16047 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 16048 if (clear) { 16049 mPrivateFlags &= clearMask; 16050 } 16051 if (this instanceof ViewGroup) { 16052 ViewGroup parent = (ViewGroup) this; 16053 final int count = parent.getChildCount(); 16054 for (int i = 0; i < count; i++) { 16055 final View child = parent.getChildAt(i); 16056 child.outputDirtyFlags(indent + " ", clear, clearMask); 16057 } 16058 } 16059 } 16060 16061 /** 16062 * This method is used by ViewGroup to cause its children to restore or recreate their 16063 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 16064 * to recreate its own display list, which would happen if it went through the normal 16065 * draw/dispatchDraw mechanisms. 16066 * 16067 * @hide 16068 */ 16069 protected void dispatchGetDisplayList() {} 16070 16071 /** 16072 * A view that is not attached or hardware accelerated cannot create a display list. 16073 * This method checks these conditions and returns the appropriate result. 16074 * 16075 * @return true if view has the ability to create a display list, false otherwise. 16076 * 16077 * @hide 16078 */ 16079 public boolean canHaveDisplayList() { 16080 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 16081 } 16082 16083 /** 16084 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 16085 * @hide 16086 */ 16087 @NonNull 16088 public RenderNode updateDisplayListIfDirty() { 16089 final RenderNode renderNode = mRenderNode; 16090 if (!canHaveDisplayList()) { 16091 // can't populate RenderNode, don't try 16092 return renderNode; 16093 } 16094 16095 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 16096 || !renderNode.isValid() 16097 || (mRecreateDisplayList)) { 16098 // Don't need to recreate the display list, just need to tell our 16099 // children to restore/recreate theirs 16100 if (renderNode.isValid() 16101 && !mRecreateDisplayList) { 16102 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16103 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16104 dispatchGetDisplayList(); 16105 16106 return renderNode; // no work needed 16107 } 16108 16109 // If we got here, we're recreating it. Mark it as such to ensure that 16110 // we copy in child display lists into ours in drawChild() 16111 mRecreateDisplayList = true; 16112 16113 int width = mRight - mLeft; 16114 int height = mBottom - mTop; 16115 int layerType = getLayerType(); 16116 16117 final DisplayListCanvas canvas = renderNode.start(width, height); 16118 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16119 16120 try { 16121 if (layerType == LAYER_TYPE_SOFTWARE) { 16122 buildDrawingCache(true); 16123 Bitmap cache = getDrawingCache(true); 16124 if (cache != null) { 16125 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16126 } 16127 } else { 16128 computeScroll(); 16129 16130 canvas.translate(-mScrollX, -mScrollY); 16131 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16132 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16133 16134 // Fast path for layouts with no backgrounds 16135 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16136 dispatchDraw(canvas); 16137 if (mOverlay != null && !mOverlay.isEmpty()) { 16138 mOverlay.getOverlayView().draw(canvas); 16139 } 16140 } else { 16141 draw(canvas); 16142 } 16143 } 16144 } finally { 16145 renderNode.end(canvas); 16146 setDisplayListProperties(renderNode); 16147 } 16148 } else { 16149 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16150 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16151 } 16152 return renderNode; 16153 } 16154 16155 private void resetDisplayList() { 16156 if (mRenderNode.isValid()) { 16157 mRenderNode.discardDisplayList(); 16158 } 16159 16160 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16161 mBackgroundRenderNode.discardDisplayList(); 16162 } 16163 } 16164 16165 /** 16166 * Called when the passed RenderNode is removed from the draw tree 16167 * @hide 16168 */ 16169 public void onRenderNodeDetached(RenderNode renderNode) { 16170 } 16171 16172 /** 16173 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16174 * 16175 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16176 * 16177 * @see #getDrawingCache(boolean) 16178 */ 16179 public Bitmap getDrawingCache() { 16180 return getDrawingCache(false); 16181 } 16182 16183 /** 16184 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16185 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16186 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16187 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16188 * request the drawing cache by calling this method and draw it on screen if the 16189 * returned bitmap is not null.</p> 16190 * 16191 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16192 * this method will create a bitmap of the same size as this view. Because this bitmap 16193 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16194 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16195 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16196 * size than the view. This implies that your application must be able to handle this 16197 * size.</p> 16198 * 16199 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16200 * the current density of the screen when the application is in compatibility 16201 * mode. 16202 * 16203 * @return A bitmap representing this view or null if cache is disabled. 16204 * 16205 * @see #setDrawingCacheEnabled(boolean) 16206 * @see #isDrawingCacheEnabled() 16207 * @see #buildDrawingCache(boolean) 16208 * @see #destroyDrawingCache() 16209 */ 16210 public Bitmap getDrawingCache(boolean autoScale) { 16211 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16212 return null; 16213 } 16214 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16215 buildDrawingCache(autoScale); 16216 } 16217 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16218 } 16219 16220 /** 16221 * <p>Frees the resources used by the drawing cache. If you call 16222 * {@link #buildDrawingCache()} manually without calling 16223 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16224 * should cleanup the cache with this method afterwards.</p> 16225 * 16226 * @see #setDrawingCacheEnabled(boolean) 16227 * @see #buildDrawingCache() 16228 * @see #getDrawingCache() 16229 */ 16230 public void destroyDrawingCache() { 16231 if (mDrawingCache != null) { 16232 mDrawingCache.recycle(); 16233 mDrawingCache = null; 16234 } 16235 if (mUnscaledDrawingCache != null) { 16236 mUnscaledDrawingCache.recycle(); 16237 mUnscaledDrawingCache = null; 16238 } 16239 } 16240 16241 /** 16242 * Setting a solid background color for the drawing cache's bitmaps will improve 16243 * performance and memory usage. Note, though that this should only be used if this 16244 * view will always be drawn on top of a solid color. 16245 * 16246 * @param color The background color to use for the drawing cache's bitmap 16247 * 16248 * @see #setDrawingCacheEnabled(boolean) 16249 * @see #buildDrawingCache() 16250 * @see #getDrawingCache() 16251 */ 16252 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16253 if (color != mDrawingCacheBackgroundColor) { 16254 mDrawingCacheBackgroundColor = color; 16255 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16256 } 16257 } 16258 16259 /** 16260 * @see #setDrawingCacheBackgroundColor(int) 16261 * 16262 * @return The background color to used for the drawing cache's bitmap 16263 */ 16264 @ColorInt 16265 public int getDrawingCacheBackgroundColor() { 16266 return mDrawingCacheBackgroundColor; 16267 } 16268 16269 /** 16270 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16271 * 16272 * @see #buildDrawingCache(boolean) 16273 */ 16274 public void buildDrawingCache() { 16275 buildDrawingCache(false); 16276 } 16277 16278 /** 16279 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16280 * 16281 * <p>If you call {@link #buildDrawingCache()} manually without calling 16282 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16283 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16284 * 16285 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16286 * this method will create a bitmap of the same size as this view. Because this bitmap 16287 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16288 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16289 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16290 * size than the view. This implies that your application must be able to handle this 16291 * size.</p> 16292 * 16293 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16294 * you do not need the drawing cache bitmap, calling this method will increase memory 16295 * usage and cause the view to be rendered in software once, thus negatively impacting 16296 * performance.</p> 16297 * 16298 * @see #getDrawingCache() 16299 * @see #destroyDrawingCache() 16300 */ 16301 public void buildDrawingCache(boolean autoScale) { 16302 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16303 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16304 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16305 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16306 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16307 } 16308 try { 16309 buildDrawingCacheImpl(autoScale); 16310 } finally { 16311 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16312 } 16313 } 16314 } 16315 16316 /** 16317 * private, internal implementation of buildDrawingCache, used to enable tracing 16318 */ 16319 private void buildDrawingCacheImpl(boolean autoScale) { 16320 mCachingFailed = false; 16321 16322 int width = mRight - mLeft; 16323 int height = mBottom - mTop; 16324 16325 final AttachInfo attachInfo = mAttachInfo; 16326 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16327 16328 if (autoScale && scalingRequired) { 16329 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16330 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16331 } 16332 16333 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16334 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16335 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16336 16337 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16338 final long drawingCacheSize = 16339 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16340 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16341 if (width > 0 && height > 0) { 16342 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16343 + " too large to fit into a software layer (or drawing cache), needs " 16344 + projectedBitmapSize + " bytes, only " 16345 + drawingCacheSize + " available"); 16346 } 16347 destroyDrawingCache(); 16348 mCachingFailed = true; 16349 return; 16350 } 16351 16352 boolean clear = true; 16353 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16354 16355 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16356 Bitmap.Config quality; 16357 if (!opaque) { 16358 // Never pick ARGB_4444 because it looks awful 16359 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16360 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16361 case DRAWING_CACHE_QUALITY_AUTO: 16362 case DRAWING_CACHE_QUALITY_LOW: 16363 case DRAWING_CACHE_QUALITY_HIGH: 16364 default: 16365 quality = Bitmap.Config.ARGB_8888; 16366 break; 16367 } 16368 } else { 16369 // Optimization for translucent windows 16370 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16371 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16372 } 16373 16374 // Try to cleanup memory 16375 if (bitmap != null) bitmap.recycle(); 16376 16377 try { 16378 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16379 width, height, quality); 16380 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16381 if (autoScale) { 16382 mDrawingCache = bitmap; 16383 } else { 16384 mUnscaledDrawingCache = bitmap; 16385 } 16386 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16387 } catch (OutOfMemoryError e) { 16388 // If there is not enough memory to create the bitmap cache, just 16389 // ignore the issue as bitmap caches are not required to draw the 16390 // view hierarchy 16391 if (autoScale) { 16392 mDrawingCache = null; 16393 } else { 16394 mUnscaledDrawingCache = null; 16395 } 16396 mCachingFailed = true; 16397 return; 16398 } 16399 16400 clear = drawingCacheBackgroundColor != 0; 16401 } 16402 16403 Canvas canvas; 16404 if (attachInfo != null) { 16405 canvas = attachInfo.mCanvas; 16406 if (canvas == null) { 16407 canvas = new Canvas(); 16408 } 16409 canvas.setBitmap(bitmap); 16410 // Temporarily clobber the cached Canvas in case one of our children 16411 // is also using a drawing cache. Without this, the children would 16412 // steal the canvas by attaching their own bitmap to it and bad, bad 16413 // thing would happen (invisible views, corrupted drawings, etc.) 16414 attachInfo.mCanvas = null; 16415 } else { 16416 // This case should hopefully never or seldom happen 16417 canvas = new Canvas(bitmap); 16418 } 16419 16420 if (clear) { 16421 bitmap.eraseColor(drawingCacheBackgroundColor); 16422 } 16423 16424 computeScroll(); 16425 final int restoreCount = canvas.save(); 16426 16427 if (autoScale && scalingRequired) { 16428 final float scale = attachInfo.mApplicationScale; 16429 canvas.scale(scale, scale); 16430 } 16431 16432 canvas.translate(-mScrollX, -mScrollY); 16433 16434 mPrivateFlags |= PFLAG_DRAWN; 16435 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16436 mLayerType != LAYER_TYPE_NONE) { 16437 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16438 } 16439 16440 // Fast path for layouts with no backgrounds 16441 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16442 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16443 dispatchDraw(canvas); 16444 if (mOverlay != null && !mOverlay.isEmpty()) { 16445 mOverlay.getOverlayView().draw(canvas); 16446 } 16447 } else { 16448 draw(canvas); 16449 } 16450 16451 canvas.restoreToCount(restoreCount); 16452 canvas.setBitmap(null); 16453 16454 if (attachInfo != null) { 16455 // Restore the cached Canvas for our siblings 16456 attachInfo.mCanvas = canvas; 16457 } 16458 } 16459 16460 /** 16461 * Create a snapshot of the view into a bitmap. We should probably make 16462 * some form of this public, but should think about the API. 16463 * 16464 * @hide 16465 */ 16466 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16467 int width = mRight - mLeft; 16468 int height = mBottom - mTop; 16469 16470 final AttachInfo attachInfo = mAttachInfo; 16471 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16472 width = (int) ((width * scale) + 0.5f); 16473 height = (int) ((height * scale) + 0.5f); 16474 16475 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16476 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16477 if (bitmap == null) { 16478 throw new OutOfMemoryError(); 16479 } 16480 16481 Resources resources = getResources(); 16482 if (resources != null) { 16483 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16484 } 16485 16486 Canvas canvas; 16487 if (attachInfo != null) { 16488 canvas = attachInfo.mCanvas; 16489 if (canvas == null) { 16490 canvas = new Canvas(); 16491 } 16492 canvas.setBitmap(bitmap); 16493 // Temporarily clobber the cached Canvas in case one of our children 16494 // is also using a drawing cache. Without this, the children would 16495 // steal the canvas by attaching their own bitmap to it and bad, bad 16496 // things would happen (invisible views, corrupted drawings, etc.) 16497 attachInfo.mCanvas = null; 16498 } else { 16499 // This case should hopefully never or seldom happen 16500 canvas = new Canvas(bitmap); 16501 } 16502 16503 if ((backgroundColor & 0xff000000) != 0) { 16504 bitmap.eraseColor(backgroundColor); 16505 } 16506 16507 computeScroll(); 16508 final int restoreCount = canvas.save(); 16509 canvas.scale(scale, scale); 16510 canvas.translate(-mScrollX, -mScrollY); 16511 16512 // Temporarily remove the dirty mask 16513 int flags = mPrivateFlags; 16514 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16515 16516 // Fast path for layouts with no backgrounds 16517 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16518 dispatchDraw(canvas); 16519 if (mOverlay != null && !mOverlay.isEmpty()) { 16520 mOverlay.getOverlayView().draw(canvas); 16521 } 16522 } else { 16523 draw(canvas); 16524 } 16525 16526 mPrivateFlags = flags; 16527 16528 canvas.restoreToCount(restoreCount); 16529 canvas.setBitmap(null); 16530 16531 if (attachInfo != null) { 16532 // Restore the cached Canvas for our siblings 16533 attachInfo.mCanvas = canvas; 16534 } 16535 16536 return bitmap; 16537 } 16538 16539 /** 16540 * Indicates whether this View is currently in edit mode. A View is usually 16541 * in edit mode when displayed within a developer tool. For instance, if 16542 * this View is being drawn by a visual user interface builder, this method 16543 * should return true. 16544 * 16545 * Subclasses should check the return value of this method to provide 16546 * different behaviors if their normal behavior might interfere with the 16547 * host environment. For instance: the class spawns a thread in its 16548 * constructor, the drawing code relies on device-specific features, etc. 16549 * 16550 * This method is usually checked in the drawing code of custom widgets. 16551 * 16552 * @return True if this View is in edit mode, false otherwise. 16553 */ 16554 public boolean isInEditMode() { 16555 return false; 16556 } 16557 16558 /** 16559 * If the View draws content inside its padding and enables fading edges, 16560 * it needs to support padding offsets. Padding offsets are added to the 16561 * fading edges to extend the length of the fade so that it covers pixels 16562 * drawn inside the padding. 16563 * 16564 * Subclasses of this class should override this method if they need 16565 * to draw content inside the padding. 16566 * 16567 * @return True if padding offset must be applied, false otherwise. 16568 * 16569 * @see #getLeftPaddingOffset() 16570 * @see #getRightPaddingOffset() 16571 * @see #getTopPaddingOffset() 16572 * @see #getBottomPaddingOffset() 16573 * 16574 * @since CURRENT 16575 */ 16576 protected boolean isPaddingOffsetRequired() { 16577 return false; 16578 } 16579 16580 /** 16581 * Amount by which to extend the left fading region. Called only when 16582 * {@link #isPaddingOffsetRequired()} returns true. 16583 * 16584 * @return The left padding offset in pixels. 16585 * 16586 * @see #isPaddingOffsetRequired() 16587 * 16588 * @since CURRENT 16589 */ 16590 protected int getLeftPaddingOffset() { 16591 return 0; 16592 } 16593 16594 /** 16595 * Amount by which to extend the right fading region. Called only when 16596 * {@link #isPaddingOffsetRequired()} returns true. 16597 * 16598 * @return The right padding offset in pixels. 16599 * 16600 * @see #isPaddingOffsetRequired() 16601 * 16602 * @since CURRENT 16603 */ 16604 protected int getRightPaddingOffset() { 16605 return 0; 16606 } 16607 16608 /** 16609 * Amount by which to extend the top fading region. Called only when 16610 * {@link #isPaddingOffsetRequired()} returns true. 16611 * 16612 * @return The top padding offset in pixels. 16613 * 16614 * @see #isPaddingOffsetRequired() 16615 * 16616 * @since CURRENT 16617 */ 16618 protected int getTopPaddingOffset() { 16619 return 0; 16620 } 16621 16622 /** 16623 * Amount by which to extend the bottom fading region. Called only when 16624 * {@link #isPaddingOffsetRequired()} returns true. 16625 * 16626 * @return The bottom padding offset in pixels. 16627 * 16628 * @see #isPaddingOffsetRequired() 16629 * 16630 * @since CURRENT 16631 */ 16632 protected int getBottomPaddingOffset() { 16633 return 0; 16634 } 16635 16636 /** 16637 * @hide 16638 * @param offsetRequired 16639 */ 16640 protected int getFadeTop(boolean offsetRequired) { 16641 int top = mPaddingTop; 16642 if (offsetRequired) top += getTopPaddingOffset(); 16643 return top; 16644 } 16645 16646 /** 16647 * @hide 16648 * @param offsetRequired 16649 */ 16650 protected int getFadeHeight(boolean offsetRequired) { 16651 int padding = mPaddingTop; 16652 if (offsetRequired) padding += getTopPaddingOffset(); 16653 return mBottom - mTop - mPaddingBottom - padding; 16654 } 16655 16656 /** 16657 * <p>Indicates whether this view is attached to a hardware accelerated 16658 * window or not.</p> 16659 * 16660 * <p>Even if this method returns true, it does not mean that every call 16661 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16662 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16663 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16664 * window is hardware accelerated, 16665 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16666 * return false, and this method will return true.</p> 16667 * 16668 * @return True if the view is attached to a window and the window is 16669 * hardware accelerated; false in any other case. 16670 */ 16671 @ViewDebug.ExportedProperty(category = "drawing") 16672 public boolean isHardwareAccelerated() { 16673 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16674 } 16675 16676 /** 16677 * Sets a rectangular area on this view to which the view will be clipped 16678 * when it is drawn. Setting the value to null will remove the clip bounds 16679 * and the view will draw normally, using its full bounds. 16680 * 16681 * @param clipBounds The rectangular area, in the local coordinates of 16682 * this view, to which future drawing operations will be clipped. 16683 */ 16684 public void setClipBounds(Rect clipBounds) { 16685 if (clipBounds == mClipBounds 16686 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16687 return; 16688 } 16689 if (clipBounds != null) { 16690 if (mClipBounds == null) { 16691 mClipBounds = new Rect(clipBounds); 16692 } else { 16693 mClipBounds.set(clipBounds); 16694 } 16695 } else { 16696 mClipBounds = null; 16697 } 16698 mRenderNode.setClipBounds(mClipBounds); 16699 invalidateViewProperty(false, false); 16700 } 16701 16702 /** 16703 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16704 * 16705 * @return A copy of the current clip bounds if clip bounds are set, 16706 * otherwise null. 16707 */ 16708 public Rect getClipBounds() { 16709 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16710 } 16711 16712 16713 /** 16714 * Populates an output rectangle with the clip bounds of the view, 16715 * returning {@code true} if successful or {@code false} if the view's 16716 * clip bounds are {@code null}. 16717 * 16718 * @param outRect rectangle in which to place the clip bounds of the view 16719 * @return {@code true} if successful or {@code false} if the view's 16720 * clip bounds are {@code null} 16721 */ 16722 public boolean getClipBounds(Rect outRect) { 16723 if (mClipBounds != null) { 16724 outRect.set(mClipBounds); 16725 return true; 16726 } 16727 return false; 16728 } 16729 16730 /** 16731 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16732 * case of an active Animation being run on the view. 16733 */ 16734 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16735 Animation a, boolean scalingRequired) { 16736 Transformation invalidationTransform; 16737 final int flags = parent.mGroupFlags; 16738 final boolean initialized = a.isInitialized(); 16739 if (!initialized) { 16740 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16741 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16742 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16743 onAnimationStart(); 16744 } 16745 16746 final Transformation t = parent.getChildTransformation(); 16747 boolean more = a.getTransformation(drawingTime, t, 1f); 16748 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16749 if (parent.mInvalidationTransformation == null) { 16750 parent.mInvalidationTransformation = new Transformation(); 16751 } 16752 invalidationTransform = parent.mInvalidationTransformation; 16753 a.getTransformation(drawingTime, invalidationTransform, 1f); 16754 } else { 16755 invalidationTransform = t; 16756 } 16757 16758 if (more) { 16759 if (!a.willChangeBounds()) { 16760 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16761 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16762 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16763 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16764 // The child need to draw an animation, potentially offscreen, so 16765 // make sure we do not cancel invalidate requests 16766 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16767 parent.invalidate(mLeft, mTop, mRight, mBottom); 16768 } 16769 } else { 16770 if (parent.mInvalidateRegion == null) { 16771 parent.mInvalidateRegion = new RectF(); 16772 } 16773 final RectF region = parent.mInvalidateRegion; 16774 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16775 invalidationTransform); 16776 16777 // The child need to draw an animation, potentially offscreen, so 16778 // make sure we do not cancel invalidate requests 16779 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16780 16781 final int left = mLeft + (int) region.left; 16782 final int top = mTop + (int) region.top; 16783 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16784 top + (int) (region.height() + .5f)); 16785 } 16786 } 16787 return more; 16788 } 16789 16790 /** 16791 * This method is called by getDisplayList() when a display list is recorded for a View. 16792 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16793 */ 16794 void setDisplayListProperties(RenderNode renderNode) { 16795 if (renderNode != null) { 16796 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16797 renderNode.setClipToBounds(mParent instanceof ViewGroup 16798 && ((ViewGroup) mParent).getClipChildren()); 16799 16800 float alpha = 1; 16801 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16802 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16803 ViewGroup parentVG = (ViewGroup) mParent; 16804 final Transformation t = parentVG.getChildTransformation(); 16805 if (parentVG.getChildStaticTransformation(this, t)) { 16806 final int transformType = t.getTransformationType(); 16807 if (transformType != Transformation.TYPE_IDENTITY) { 16808 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16809 alpha = t.getAlpha(); 16810 } 16811 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16812 renderNode.setStaticMatrix(t.getMatrix()); 16813 } 16814 } 16815 } 16816 } 16817 if (mTransformationInfo != null) { 16818 alpha *= getFinalAlpha(); 16819 if (alpha < 1) { 16820 final int multipliedAlpha = (int) (255 * alpha); 16821 if (onSetAlpha(multipliedAlpha)) { 16822 alpha = 1; 16823 } 16824 } 16825 renderNode.setAlpha(alpha); 16826 } else if (alpha < 1) { 16827 renderNode.setAlpha(alpha); 16828 } 16829 } 16830 } 16831 16832 /** 16833 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16834 * 16835 * This is where the View specializes rendering behavior based on layer type, 16836 * and hardware acceleration. 16837 */ 16838 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16839 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16840 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16841 * 16842 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16843 * HW accelerated, it can't handle drawing RenderNodes. 16844 */ 16845 boolean drawingWithRenderNode = mAttachInfo != null 16846 && mAttachInfo.mHardwareAccelerated 16847 && hardwareAcceleratedCanvas; 16848 16849 boolean more = false; 16850 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16851 final int parentFlags = parent.mGroupFlags; 16852 16853 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16854 parent.getChildTransformation().clear(); 16855 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16856 } 16857 16858 Transformation transformToApply = null; 16859 boolean concatMatrix = false; 16860 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16861 final Animation a = getAnimation(); 16862 if (a != null) { 16863 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16864 concatMatrix = a.willChangeTransformationMatrix(); 16865 if (concatMatrix) { 16866 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16867 } 16868 transformToApply = parent.getChildTransformation(); 16869 } else { 16870 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16871 // No longer animating: clear out old animation matrix 16872 mRenderNode.setAnimationMatrix(null); 16873 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16874 } 16875 if (!drawingWithRenderNode 16876 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16877 final Transformation t = parent.getChildTransformation(); 16878 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16879 if (hasTransform) { 16880 final int transformType = t.getTransformationType(); 16881 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16882 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16883 } 16884 } 16885 } 16886 16887 concatMatrix |= !childHasIdentityMatrix; 16888 16889 // Sets the flag as early as possible to allow draw() implementations 16890 // to call invalidate() successfully when doing animations 16891 mPrivateFlags |= PFLAG_DRAWN; 16892 16893 if (!concatMatrix && 16894 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16895 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16896 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16897 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16898 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16899 return more; 16900 } 16901 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16902 16903 if (hardwareAcceleratedCanvas) { 16904 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16905 // retain the flag's value temporarily in the mRecreateDisplayList flag 16906 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16907 mPrivateFlags &= ~PFLAG_INVALIDATED; 16908 } 16909 16910 RenderNode renderNode = null; 16911 Bitmap cache = null; 16912 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16913 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16914 if (layerType != LAYER_TYPE_NONE) { 16915 // If not drawing with RenderNode, treat HW layers as SW 16916 layerType = LAYER_TYPE_SOFTWARE; 16917 buildDrawingCache(true); 16918 } 16919 cache = getDrawingCache(true); 16920 } 16921 16922 if (drawingWithRenderNode) { 16923 // Delay getting the display list until animation-driven alpha values are 16924 // set up and possibly passed on to the view 16925 renderNode = updateDisplayListIfDirty(); 16926 if (!renderNode.isValid()) { 16927 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16928 // to getDisplayList(), the display list will be marked invalid and we should not 16929 // try to use it again. 16930 renderNode = null; 16931 drawingWithRenderNode = false; 16932 } 16933 } 16934 16935 int sx = 0; 16936 int sy = 0; 16937 if (!drawingWithRenderNode) { 16938 computeScroll(); 16939 sx = mScrollX; 16940 sy = mScrollY; 16941 } 16942 16943 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16944 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16945 16946 int restoreTo = -1; 16947 if (!drawingWithRenderNode || transformToApply != null) { 16948 restoreTo = canvas.save(); 16949 } 16950 if (offsetForScroll) { 16951 canvas.translate(mLeft - sx, mTop - sy); 16952 } else { 16953 if (!drawingWithRenderNode) { 16954 canvas.translate(mLeft, mTop); 16955 } 16956 if (scalingRequired) { 16957 if (drawingWithRenderNode) { 16958 // TODO: Might not need this if we put everything inside the DL 16959 restoreTo = canvas.save(); 16960 } 16961 // mAttachInfo cannot be null, otherwise scalingRequired == false 16962 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16963 canvas.scale(scale, scale); 16964 } 16965 } 16966 16967 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16968 if (transformToApply != null 16969 || alpha < 1 16970 || !hasIdentityMatrix() 16971 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16972 if (transformToApply != null || !childHasIdentityMatrix) { 16973 int transX = 0; 16974 int transY = 0; 16975 16976 if (offsetForScroll) { 16977 transX = -sx; 16978 transY = -sy; 16979 } 16980 16981 if (transformToApply != null) { 16982 if (concatMatrix) { 16983 if (drawingWithRenderNode) { 16984 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16985 } else { 16986 // Undo the scroll translation, apply the transformation matrix, 16987 // then redo the scroll translate to get the correct result. 16988 canvas.translate(-transX, -transY); 16989 canvas.concat(transformToApply.getMatrix()); 16990 canvas.translate(transX, transY); 16991 } 16992 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16993 } 16994 16995 float transformAlpha = transformToApply.getAlpha(); 16996 if (transformAlpha < 1) { 16997 alpha *= transformAlpha; 16998 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16999 } 17000 } 17001 17002 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 17003 canvas.translate(-transX, -transY); 17004 canvas.concat(getMatrix()); 17005 canvas.translate(transX, transY); 17006 } 17007 } 17008 17009 // Deal with alpha if it is or used to be <1 17010 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 17011 if (alpha < 1) { 17012 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17013 } else { 17014 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17015 } 17016 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17017 if (!drawingWithDrawingCache) { 17018 final int multipliedAlpha = (int) (255 * alpha); 17019 if (!onSetAlpha(multipliedAlpha)) { 17020 if (drawingWithRenderNode) { 17021 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 17022 } else if (layerType == LAYER_TYPE_NONE) { 17023 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 17024 multipliedAlpha); 17025 } 17026 } else { 17027 // Alpha is handled by the child directly, clobber the layer's alpha 17028 mPrivateFlags |= PFLAG_ALPHA_SET; 17029 } 17030 } 17031 } 17032 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17033 onSetAlpha(255); 17034 mPrivateFlags &= ~PFLAG_ALPHA_SET; 17035 } 17036 17037 if (!drawingWithRenderNode) { 17038 // apply clips directly, since RenderNode won't do it for this draw 17039 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 17040 if (offsetForScroll) { 17041 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 17042 } else { 17043 if (!scalingRequired || cache == null) { 17044 canvas.clipRect(0, 0, getWidth(), getHeight()); 17045 } else { 17046 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 17047 } 17048 } 17049 } 17050 17051 if (mClipBounds != null) { 17052 // clip bounds ignore scroll 17053 canvas.clipRect(mClipBounds); 17054 } 17055 } 17056 17057 if (!drawingWithDrawingCache) { 17058 if (drawingWithRenderNode) { 17059 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17060 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17061 } else { 17062 // Fast path for layouts with no backgrounds 17063 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17064 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17065 dispatchDraw(canvas); 17066 } else { 17067 draw(canvas); 17068 } 17069 } 17070 } else if (cache != null) { 17071 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17072 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 17073 // no layer paint, use temporary paint to draw bitmap 17074 Paint cachePaint = parent.mCachePaint; 17075 if (cachePaint == null) { 17076 cachePaint = new Paint(); 17077 cachePaint.setDither(false); 17078 parent.mCachePaint = cachePaint; 17079 } 17080 cachePaint.setAlpha((int) (alpha * 255)); 17081 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 17082 } else { 17083 // use layer paint to draw the bitmap, merging the two alphas, but also restore 17084 int layerPaintAlpha = mLayerPaint.getAlpha(); 17085 if (alpha < 1) { 17086 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 17087 } 17088 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17089 if (alpha < 1) { 17090 mLayerPaint.setAlpha(layerPaintAlpha); 17091 } 17092 } 17093 } 17094 17095 if (restoreTo >= 0) { 17096 canvas.restoreToCount(restoreTo); 17097 } 17098 17099 if (a != null && !more) { 17100 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17101 onSetAlpha(255); 17102 } 17103 parent.finishAnimatingView(this, a); 17104 } 17105 17106 if (more && hardwareAcceleratedCanvas) { 17107 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17108 // alpha animations should cause the child to recreate its display list 17109 invalidate(true); 17110 } 17111 } 17112 17113 mRecreateDisplayList = false; 17114 17115 return more; 17116 } 17117 17118 /** 17119 * Manually render this view (and all of its children) to the given Canvas. 17120 * The view must have already done a full layout before this function is 17121 * called. When implementing a view, implement 17122 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17123 * If you do need to override this method, call the superclass version. 17124 * 17125 * @param canvas The Canvas to which the View is rendered. 17126 */ 17127 @CallSuper 17128 public void draw(Canvas canvas) { 17129 final int privateFlags = mPrivateFlags; 17130 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17131 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17132 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17133 17134 /* 17135 * Draw traversal performs several drawing steps which must be executed 17136 * in the appropriate order: 17137 * 17138 * 1. Draw the background 17139 * 2. If necessary, save the canvas' layers to prepare for fading 17140 * 3. Draw view's content 17141 * 4. Draw children 17142 * 5. If necessary, draw the fading edges and restore layers 17143 * 6. Draw decorations (scrollbars for instance) 17144 */ 17145 17146 // Step 1, draw the background, if needed 17147 int saveCount; 17148 17149 if (!dirtyOpaque) { 17150 drawBackground(canvas); 17151 } 17152 17153 // skip step 2 & 5 if possible (common case) 17154 final int viewFlags = mViewFlags; 17155 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17156 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17157 if (!verticalEdges && !horizontalEdges) { 17158 // Step 3, draw the content 17159 if (!dirtyOpaque) onDraw(canvas); 17160 17161 // Step 4, draw the children 17162 dispatchDraw(canvas); 17163 17164 // Overlay is part of the content and draws beneath Foreground 17165 if (mOverlay != null && !mOverlay.isEmpty()) { 17166 mOverlay.getOverlayView().dispatchDraw(canvas); 17167 } 17168 17169 // Step 6, draw decorations (foreground, scrollbars) 17170 onDrawForeground(canvas); 17171 17172 // we're done... 17173 return; 17174 } 17175 17176 /* 17177 * Here we do the full fledged routine... 17178 * (this is an uncommon case where speed matters less, 17179 * this is why we repeat some of the tests that have been 17180 * done above) 17181 */ 17182 17183 boolean drawTop = false; 17184 boolean drawBottom = false; 17185 boolean drawLeft = false; 17186 boolean drawRight = false; 17187 17188 float topFadeStrength = 0.0f; 17189 float bottomFadeStrength = 0.0f; 17190 float leftFadeStrength = 0.0f; 17191 float rightFadeStrength = 0.0f; 17192 17193 // Step 2, save the canvas' layers 17194 int paddingLeft = mPaddingLeft; 17195 17196 final boolean offsetRequired = isPaddingOffsetRequired(); 17197 if (offsetRequired) { 17198 paddingLeft += getLeftPaddingOffset(); 17199 } 17200 17201 int left = mScrollX + paddingLeft; 17202 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17203 int top = mScrollY + getFadeTop(offsetRequired); 17204 int bottom = top + getFadeHeight(offsetRequired); 17205 17206 if (offsetRequired) { 17207 right += getRightPaddingOffset(); 17208 bottom += getBottomPaddingOffset(); 17209 } 17210 17211 final ScrollabilityCache scrollabilityCache = mScrollCache; 17212 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17213 int length = (int) fadeHeight; 17214 17215 // clip the fade length if top and bottom fades overlap 17216 // overlapping fades produce odd-looking artifacts 17217 if (verticalEdges && (top + length > bottom - length)) { 17218 length = (bottom - top) / 2; 17219 } 17220 17221 // also clip horizontal fades if necessary 17222 if (horizontalEdges && (left + length > right - length)) { 17223 length = (right - left) / 2; 17224 } 17225 17226 if (verticalEdges) { 17227 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17228 drawTop = topFadeStrength * fadeHeight > 1.0f; 17229 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17230 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17231 } 17232 17233 if (horizontalEdges) { 17234 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17235 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17236 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17237 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17238 } 17239 17240 saveCount = canvas.getSaveCount(); 17241 17242 int solidColor = getSolidColor(); 17243 if (solidColor == 0) { 17244 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17245 17246 if (drawTop) { 17247 canvas.saveLayer(left, top, right, top + length, null, flags); 17248 } 17249 17250 if (drawBottom) { 17251 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17252 } 17253 17254 if (drawLeft) { 17255 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17256 } 17257 17258 if (drawRight) { 17259 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17260 } 17261 } else { 17262 scrollabilityCache.setFadeColor(solidColor); 17263 } 17264 17265 // Step 3, draw the content 17266 if (!dirtyOpaque) onDraw(canvas); 17267 17268 // Step 4, draw the children 17269 dispatchDraw(canvas); 17270 17271 // Step 5, draw the fade effect and restore layers 17272 final Paint p = scrollabilityCache.paint; 17273 final Matrix matrix = scrollabilityCache.matrix; 17274 final Shader fade = scrollabilityCache.shader; 17275 17276 if (drawTop) { 17277 matrix.setScale(1, fadeHeight * topFadeStrength); 17278 matrix.postTranslate(left, top); 17279 fade.setLocalMatrix(matrix); 17280 p.setShader(fade); 17281 canvas.drawRect(left, top, right, top + length, p); 17282 } 17283 17284 if (drawBottom) { 17285 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17286 matrix.postRotate(180); 17287 matrix.postTranslate(left, bottom); 17288 fade.setLocalMatrix(matrix); 17289 p.setShader(fade); 17290 canvas.drawRect(left, bottom - length, right, bottom, p); 17291 } 17292 17293 if (drawLeft) { 17294 matrix.setScale(1, fadeHeight * leftFadeStrength); 17295 matrix.postRotate(-90); 17296 matrix.postTranslate(left, top); 17297 fade.setLocalMatrix(matrix); 17298 p.setShader(fade); 17299 canvas.drawRect(left, top, left + length, bottom, p); 17300 } 17301 17302 if (drawRight) { 17303 matrix.setScale(1, fadeHeight * rightFadeStrength); 17304 matrix.postRotate(90); 17305 matrix.postTranslate(right, top); 17306 fade.setLocalMatrix(matrix); 17307 p.setShader(fade); 17308 canvas.drawRect(right - length, top, right, bottom, p); 17309 } 17310 17311 canvas.restoreToCount(saveCount); 17312 17313 // Overlay is part of the content and draws beneath Foreground 17314 if (mOverlay != null && !mOverlay.isEmpty()) { 17315 mOverlay.getOverlayView().dispatchDraw(canvas); 17316 } 17317 17318 // Step 6, draw decorations (foreground, scrollbars) 17319 onDrawForeground(canvas); 17320 } 17321 17322 /** 17323 * Draws the background onto the specified canvas. 17324 * 17325 * @param canvas Canvas on which to draw the background 17326 */ 17327 private void drawBackground(Canvas canvas) { 17328 final Drawable background = mBackground; 17329 if (background == null) { 17330 return; 17331 } 17332 17333 setBackgroundBounds(); 17334 17335 // Attempt to use a display list if requested. 17336 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17337 && mAttachInfo.mThreadedRenderer != null) { 17338 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17339 17340 final RenderNode renderNode = mBackgroundRenderNode; 17341 if (renderNode != null && renderNode.isValid()) { 17342 setBackgroundRenderNodeProperties(renderNode); 17343 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17344 return; 17345 } 17346 } 17347 17348 final int scrollX = mScrollX; 17349 final int scrollY = mScrollY; 17350 if ((scrollX | scrollY) == 0) { 17351 background.draw(canvas); 17352 } else { 17353 canvas.translate(scrollX, scrollY); 17354 background.draw(canvas); 17355 canvas.translate(-scrollX, -scrollY); 17356 } 17357 } 17358 17359 /** 17360 * Sets the correct background bounds and rebuilds the outline, if needed. 17361 * <p/> 17362 * This is called by LayoutLib. 17363 */ 17364 void setBackgroundBounds() { 17365 if (mBackgroundSizeChanged && mBackground != null) { 17366 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17367 mBackgroundSizeChanged = false; 17368 rebuildOutline(); 17369 } 17370 } 17371 17372 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17373 renderNode.setTranslationX(mScrollX); 17374 renderNode.setTranslationY(mScrollY); 17375 } 17376 17377 /** 17378 * Creates a new display list or updates the existing display list for the 17379 * specified Drawable. 17380 * 17381 * @param drawable Drawable for which to create a display list 17382 * @param renderNode Existing RenderNode, or {@code null} 17383 * @return A valid display list for the specified drawable 17384 */ 17385 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17386 if (renderNode == null) { 17387 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17388 } 17389 17390 final Rect bounds = drawable.getBounds(); 17391 final int width = bounds.width(); 17392 final int height = bounds.height(); 17393 final DisplayListCanvas canvas = renderNode.start(width, height); 17394 17395 // Reverse left/top translation done by drawable canvas, which will 17396 // instead be applied by rendernode's LTRB bounds below. This way, the 17397 // drawable's bounds match with its rendernode bounds and its content 17398 // will lie within those bounds in the rendernode tree. 17399 canvas.translate(-bounds.left, -bounds.top); 17400 17401 try { 17402 drawable.draw(canvas); 17403 } finally { 17404 renderNode.end(canvas); 17405 } 17406 17407 // Set up drawable properties that are view-independent. 17408 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17409 renderNode.setProjectBackwards(drawable.isProjected()); 17410 renderNode.setProjectionReceiver(true); 17411 renderNode.setClipToBounds(false); 17412 return renderNode; 17413 } 17414 17415 /** 17416 * Returns the overlay for this view, creating it if it does not yet exist. 17417 * Adding drawables to the overlay will cause them to be displayed whenever 17418 * the view itself is redrawn. Objects in the overlay should be actively 17419 * managed: remove them when they should not be displayed anymore. The 17420 * overlay will always have the same size as its host view. 17421 * 17422 * <p>Note: Overlays do not currently work correctly with {@link 17423 * SurfaceView} or {@link TextureView}; contents in overlays for these 17424 * types of views may not display correctly.</p> 17425 * 17426 * @return The ViewOverlay object for this view. 17427 * @see ViewOverlay 17428 */ 17429 public ViewOverlay getOverlay() { 17430 if (mOverlay == null) { 17431 mOverlay = new ViewOverlay(mContext, this); 17432 } 17433 return mOverlay; 17434 } 17435 17436 /** 17437 * Override this if your view is known to always be drawn on top of a solid color background, 17438 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17439 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17440 * should be set to 0xFF. 17441 * 17442 * @see #setVerticalFadingEdgeEnabled(boolean) 17443 * @see #setHorizontalFadingEdgeEnabled(boolean) 17444 * 17445 * @return The known solid color background for this view, or 0 if the color may vary 17446 */ 17447 @ViewDebug.ExportedProperty(category = "drawing") 17448 @ColorInt 17449 public int getSolidColor() { 17450 return 0; 17451 } 17452 17453 /** 17454 * Build a human readable string representation of the specified view flags. 17455 * 17456 * @param flags the view flags to convert to a string 17457 * @return a String representing the supplied flags 17458 */ 17459 private static String printFlags(int flags) { 17460 String output = ""; 17461 int numFlags = 0; 17462 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17463 output += "TAKES_FOCUS"; 17464 numFlags++; 17465 } 17466 17467 switch (flags & VISIBILITY_MASK) { 17468 case INVISIBLE: 17469 if (numFlags > 0) { 17470 output += " "; 17471 } 17472 output += "INVISIBLE"; 17473 // USELESS HERE numFlags++; 17474 break; 17475 case GONE: 17476 if (numFlags > 0) { 17477 output += " "; 17478 } 17479 output += "GONE"; 17480 // USELESS HERE numFlags++; 17481 break; 17482 default: 17483 break; 17484 } 17485 return output; 17486 } 17487 17488 /** 17489 * Build a human readable string representation of the specified private 17490 * view flags. 17491 * 17492 * @param privateFlags the private view flags to convert to a string 17493 * @return a String representing the supplied flags 17494 */ 17495 private static String printPrivateFlags(int privateFlags) { 17496 String output = ""; 17497 int numFlags = 0; 17498 17499 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17500 output += "WANTS_FOCUS"; 17501 numFlags++; 17502 } 17503 17504 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17505 if (numFlags > 0) { 17506 output += " "; 17507 } 17508 output += "FOCUSED"; 17509 numFlags++; 17510 } 17511 17512 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17513 if (numFlags > 0) { 17514 output += " "; 17515 } 17516 output += "SELECTED"; 17517 numFlags++; 17518 } 17519 17520 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17521 if (numFlags > 0) { 17522 output += " "; 17523 } 17524 output += "IS_ROOT_NAMESPACE"; 17525 numFlags++; 17526 } 17527 17528 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17529 if (numFlags > 0) { 17530 output += " "; 17531 } 17532 output += "HAS_BOUNDS"; 17533 numFlags++; 17534 } 17535 17536 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17537 if (numFlags > 0) { 17538 output += " "; 17539 } 17540 output += "DRAWN"; 17541 // USELESS HERE numFlags++; 17542 } 17543 return output; 17544 } 17545 17546 /** 17547 * <p>Indicates whether or not this view's layout will be requested during 17548 * the next hierarchy layout pass.</p> 17549 * 17550 * @return true if the layout will be forced during next layout pass 17551 */ 17552 public boolean isLayoutRequested() { 17553 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17554 } 17555 17556 /** 17557 * Return true if o is a ViewGroup that is laying out using optical bounds. 17558 * @hide 17559 */ 17560 public static boolean isLayoutModeOptical(Object o) { 17561 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17562 } 17563 17564 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17565 Insets parentInsets = mParent instanceof View ? 17566 ((View) mParent).getOpticalInsets() : Insets.NONE; 17567 Insets childInsets = getOpticalInsets(); 17568 return setFrame( 17569 left + parentInsets.left - childInsets.left, 17570 top + parentInsets.top - childInsets.top, 17571 right + parentInsets.left + childInsets.right, 17572 bottom + parentInsets.top + childInsets.bottom); 17573 } 17574 17575 /** 17576 * Assign a size and position to a view and all of its 17577 * descendants 17578 * 17579 * <p>This is the second phase of the layout mechanism. 17580 * (The first is measuring). In this phase, each parent calls 17581 * layout on all of its children to position them. 17582 * This is typically done using the child measurements 17583 * that were stored in the measure pass().</p> 17584 * 17585 * <p>Derived classes should not override this method. 17586 * Derived classes with children should override 17587 * onLayout. In that method, they should 17588 * call layout on each of their children.</p> 17589 * 17590 * @param l Left position, relative to parent 17591 * @param t Top position, relative to parent 17592 * @param r Right position, relative to parent 17593 * @param b Bottom position, relative to parent 17594 */ 17595 @SuppressWarnings({"unchecked"}) 17596 public void layout(int l, int t, int r, int b) { 17597 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17598 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17599 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17600 } 17601 17602 int oldL = mLeft; 17603 int oldT = mTop; 17604 int oldB = mBottom; 17605 int oldR = mRight; 17606 17607 boolean changed = isLayoutModeOptical(mParent) ? 17608 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17609 17610 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17611 onLayout(changed, l, t, r, b); 17612 17613 if (shouldDrawRoundScrollbar()) { 17614 if(mRoundScrollbarRenderer == null) { 17615 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 17616 } 17617 } else { 17618 mRoundScrollbarRenderer = null; 17619 } 17620 17621 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17622 17623 ListenerInfo li = mListenerInfo; 17624 if (li != null && li.mOnLayoutChangeListeners != null) { 17625 ArrayList<OnLayoutChangeListener> listenersCopy = 17626 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17627 int numListeners = listenersCopy.size(); 17628 for (int i = 0; i < numListeners; ++i) { 17629 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17630 } 17631 } 17632 } 17633 17634 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17635 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17636 } 17637 17638 /** 17639 * Called from layout when this view should 17640 * assign a size and position to each of its children. 17641 * 17642 * Derived classes with children should override 17643 * this method and call layout on each of 17644 * their children. 17645 * @param changed This is a new size or position for this view 17646 * @param left Left position, relative to parent 17647 * @param top Top position, relative to parent 17648 * @param right Right position, relative to parent 17649 * @param bottom Bottom position, relative to parent 17650 */ 17651 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17652 } 17653 17654 /** 17655 * Assign a size and position to this view. 17656 * 17657 * This is called from layout. 17658 * 17659 * @param left Left position, relative to parent 17660 * @param top Top position, relative to parent 17661 * @param right Right position, relative to parent 17662 * @param bottom Bottom position, relative to parent 17663 * @return true if the new size and position are different than the 17664 * previous ones 17665 * {@hide} 17666 */ 17667 protected boolean setFrame(int left, int top, int right, int bottom) { 17668 boolean changed = false; 17669 17670 if (DBG) { 17671 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17672 + right + "," + bottom + ")"); 17673 } 17674 17675 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17676 changed = true; 17677 17678 // Remember our drawn bit 17679 int drawn = mPrivateFlags & PFLAG_DRAWN; 17680 17681 int oldWidth = mRight - mLeft; 17682 int oldHeight = mBottom - mTop; 17683 int newWidth = right - left; 17684 int newHeight = bottom - top; 17685 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17686 17687 // Invalidate our old position 17688 invalidate(sizeChanged); 17689 17690 mLeft = left; 17691 mTop = top; 17692 mRight = right; 17693 mBottom = bottom; 17694 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17695 17696 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17697 17698 17699 if (sizeChanged) { 17700 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17701 } 17702 17703 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17704 // If we are visible, force the DRAWN bit to on so that 17705 // this invalidate will go through (at least to our parent). 17706 // This is because someone may have invalidated this view 17707 // before this call to setFrame came in, thereby clearing 17708 // the DRAWN bit. 17709 mPrivateFlags |= PFLAG_DRAWN; 17710 invalidate(sizeChanged); 17711 // parent display list may need to be recreated based on a change in the bounds 17712 // of any child 17713 invalidateParentCaches(); 17714 } 17715 17716 // Reset drawn bit to original value (invalidate turns it off) 17717 mPrivateFlags |= drawn; 17718 17719 mBackgroundSizeChanged = true; 17720 if (mForegroundInfo != null) { 17721 mForegroundInfo.mBoundsChanged = true; 17722 } 17723 17724 notifySubtreeAccessibilityStateChangedIfNeeded(); 17725 } 17726 return changed; 17727 } 17728 17729 /** 17730 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17731 * @hide 17732 */ 17733 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17734 setFrame(left, top, right, bottom); 17735 } 17736 17737 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17738 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17739 if (mOverlay != null) { 17740 mOverlay.getOverlayView().setRight(newWidth); 17741 mOverlay.getOverlayView().setBottom(newHeight); 17742 } 17743 rebuildOutline(); 17744 } 17745 17746 /** 17747 * Finalize inflating a view from XML. This is called as the last phase 17748 * of inflation, after all child views have been added. 17749 * 17750 * <p>Even if the subclass overrides onFinishInflate, they should always be 17751 * sure to call the super method, so that we get called. 17752 */ 17753 @CallSuper 17754 protected void onFinishInflate() { 17755 } 17756 17757 /** 17758 * Returns the resources associated with this view. 17759 * 17760 * @return Resources object. 17761 */ 17762 public Resources getResources() { 17763 return mResources; 17764 } 17765 17766 /** 17767 * Invalidates the specified Drawable. 17768 * 17769 * @param drawable the drawable to invalidate 17770 */ 17771 @Override 17772 public void invalidateDrawable(@NonNull Drawable drawable) { 17773 if (verifyDrawable(drawable)) { 17774 final Rect dirty = drawable.getDirtyBounds(); 17775 final int scrollX = mScrollX; 17776 final int scrollY = mScrollY; 17777 17778 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17779 dirty.right + scrollX, dirty.bottom + scrollY); 17780 rebuildOutline(); 17781 } 17782 } 17783 17784 /** 17785 * Schedules an action on a drawable to occur at a specified time. 17786 * 17787 * @param who the recipient of the action 17788 * @param what the action to run on the drawable 17789 * @param when the time at which the action must occur. Uses the 17790 * {@link SystemClock#uptimeMillis} timebase. 17791 */ 17792 @Override 17793 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17794 if (verifyDrawable(who) && what != null) { 17795 final long delay = when - SystemClock.uptimeMillis(); 17796 if (mAttachInfo != null) { 17797 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17798 Choreographer.CALLBACK_ANIMATION, what, who, 17799 Choreographer.subtractFrameDelay(delay)); 17800 } else { 17801 // Postpone the runnable until we know 17802 // on which thread it needs to run. 17803 getRunQueue().postDelayed(what, delay); 17804 } 17805 } 17806 } 17807 17808 /** 17809 * Cancels a scheduled action on a drawable. 17810 * 17811 * @param who the recipient of the action 17812 * @param what the action to cancel 17813 */ 17814 @Override 17815 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17816 if (verifyDrawable(who) && what != null) { 17817 if (mAttachInfo != null) { 17818 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17819 Choreographer.CALLBACK_ANIMATION, what, who); 17820 } 17821 getRunQueue().removeCallbacks(what); 17822 } 17823 } 17824 17825 /** 17826 * Unschedule any events associated with the given Drawable. This can be 17827 * used when selecting a new Drawable into a view, so that the previous 17828 * one is completely unscheduled. 17829 * 17830 * @param who The Drawable to unschedule. 17831 * 17832 * @see #drawableStateChanged 17833 */ 17834 public void unscheduleDrawable(Drawable who) { 17835 if (mAttachInfo != null && who != null) { 17836 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17837 Choreographer.CALLBACK_ANIMATION, null, who); 17838 } 17839 } 17840 17841 /** 17842 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17843 * that the View directionality can and will be resolved before its Drawables. 17844 * 17845 * Will call {@link View#onResolveDrawables} when resolution is done. 17846 * 17847 * @hide 17848 */ 17849 protected void resolveDrawables() { 17850 // Drawables resolution may need to happen before resolving the layout direction (which is 17851 // done only during the measure() call). 17852 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17853 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17854 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17855 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17856 // direction to be resolved as its resolved value will be the same as its raw value. 17857 if (!isLayoutDirectionResolved() && 17858 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17859 return; 17860 } 17861 17862 final int layoutDirection = isLayoutDirectionResolved() ? 17863 getLayoutDirection() : getRawLayoutDirection(); 17864 17865 if (mBackground != null) { 17866 mBackground.setLayoutDirection(layoutDirection); 17867 } 17868 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17869 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17870 } 17871 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17872 onResolveDrawables(layoutDirection); 17873 } 17874 17875 boolean areDrawablesResolved() { 17876 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17877 } 17878 17879 /** 17880 * Called when layout direction has been resolved. 17881 * 17882 * The default implementation does nothing. 17883 * 17884 * @param layoutDirection The resolved layout direction. 17885 * 17886 * @see #LAYOUT_DIRECTION_LTR 17887 * @see #LAYOUT_DIRECTION_RTL 17888 * 17889 * @hide 17890 */ 17891 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17892 } 17893 17894 /** 17895 * @hide 17896 */ 17897 protected void resetResolvedDrawables() { 17898 resetResolvedDrawablesInternal(); 17899 } 17900 17901 void resetResolvedDrawablesInternal() { 17902 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17903 } 17904 17905 /** 17906 * If your view subclass is displaying its own Drawable objects, it should 17907 * override this function and return true for any Drawable it is 17908 * displaying. This allows animations for those drawables to be 17909 * scheduled. 17910 * 17911 * <p>Be sure to call through to the super class when overriding this 17912 * function. 17913 * 17914 * @param who The Drawable to verify. Return true if it is one you are 17915 * displaying, else return the result of calling through to the 17916 * super class. 17917 * 17918 * @return boolean If true than the Drawable is being displayed in the 17919 * view; else false and it is not allowed to animate. 17920 * 17921 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17922 * @see #drawableStateChanged() 17923 */ 17924 @CallSuper 17925 protected boolean verifyDrawable(@NonNull Drawable who) { 17926 // Avoid verifying the scroll bar drawable so that we don't end up in 17927 // an invalidation loop. This effectively prevents the scroll bar 17928 // drawable from triggering invalidations and scheduling runnables. 17929 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17930 } 17931 17932 /** 17933 * This function is called whenever the state of the view changes in such 17934 * a way that it impacts the state of drawables being shown. 17935 * <p> 17936 * If the View has a StateListAnimator, it will also be called to run necessary state 17937 * change animations. 17938 * <p> 17939 * Be sure to call through to the superclass when overriding this function. 17940 * 17941 * @see Drawable#setState(int[]) 17942 */ 17943 @CallSuper 17944 protected void drawableStateChanged() { 17945 final int[] state = getDrawableState(); 17946 boolean changed = false; 17947 17948 final Drawable bg = mBackground; 17949 if (bg != null && bg.isStateful()) { 17950 changed |= bg.setState(state); 17951 } 17952 17953 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17954 if (fg != null && fg.isStateful()) { 17955 changed |= fg.setState(state); 17956 } 17957 17958 if (mScrollCache != null) { 17959 final Drawable scrollBar = mScrollCache.scrollBar; 17960 if (scrollBar != null && scrollBar.isStateful()) { 17961 changed |= scrollBar.setState(state) 17962 && mScrollCache.state != ScrollabilityCache.OFF; 17963 } 17964 } 17965 17966 if (mStateListAnimator != null) { 17967 mStateListAnimator.setState(state); 17968 } 17969 17970 if (changed) { 17971 invalidate(); 17972 } 17973 } 17974 17975 /** 17976 * This function is called whenever the view hotspot changes and needs to 17977 * be propagated to drawables or child views managed by the view. 17978 * <p> 17979 * Dispatching to child views is handled by 17980 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17981 * <p> 17982 * Be sure to call through to the superclass when overriding this function. 17983 * 17984 * @param x hotspot x coordinate 17985 * @param y hotspot y coordinate 17986 */ 17987 @CallSuper 17988 public void drawableHotspotChanged(float x, float y) { 17989 if (mBackground != null) { 17990 mBackground.setHotspot(x, y); 17991 } 17992 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17993 mForegroundInfo.mDrawable.setHotspot(x, y); 17994 } 17995 17996 dispatchDrawableHotspotChanged(x, y); 17997 } 17998 17999 /** 18000 * Dispatches drawableHotspotChanged to all of this View's children. 18001 * 18002 * @param x hotspot x coordinate 18003 * @param y hotspot y coordinate 18004 * @see #drawableHotspotChanged(float, float) 18005 */ 18006 public void dispatchDrawableHotspotChanged(float x, float y) { 18007 } 18008 18009 /** 18010 * Call this to force a view to update its drawable state. This will cause 18011 * drawableStateChanged to be called on this view. Views that are interested 18012 * in the new state should call getDrawableState. 18013 * 18014 * @see #drawableStateChanged 18015 * @see #getDrawableState 18016 */ 18017 public void refreshDrawableState() { 18018 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 18019 drawableStateChanged(); 18020 18021 ViewParent parent = mParent; 18022 if (parent != null) { 18023 parent.childDrawableStateChanged(this); 18024 } 18025 } 18026 18027 /** 18028 * Return an array of resource IDs of the drawable states representing the 18029 * current state of the view. 18030 * 18031 * @return The current drawable state 18032 * 18033 * @see Drawable#setState(int[]) 18034 * @see #drawableStateChanged() 18035 * @see #onCreateDrawableState(int) 18036 */ 18037 public final int[] getDrawableState() { 18038 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 18039 return mDrawableState; 18040 } else { 18041 mDrawableState = onCreateDrawableState(0); 18042 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 18043 return mDrawableState; 18044 } 18045 } 18046 18047 /** 18048 * Generate the new {@link android.graphics.drawable.Drawable} state for 18049 * this view. This is called by the view 18050 * system when the cached Drawable state is determined to be invalid. To 18051 * retrieve the current state, you should use {@link #getDrawableState}. 18052 * 18053 * @param extraSpace if non-zero, this is the number of extra entries you 18054 * would like in the returned array in which you can place your own 18055 * states. 18056 * 18057 * @return Returns an array holding the current {@link Drawable} state of 18058 * the view. 18059 * 18060 * @see #mergeDrawableStates(int[], int[]) 18061 */ 18062 protected int[] onCreateDrawableState(int extraSpace) { 18063 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 18064 mParent instanceof View) { 18065 return ((View) mParent).onCreateDrawableState(extraSpace); 18066 } 18067 18068 int[] drawableState; 18069 18070 int privateFlags = mPrivateFlags; 18071 18072 int viewStateIndex = 0; 18073 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 18074 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 18075 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 18076 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 18077 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 18078 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 18079 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 18080 ThreadedRenderer.isAvailable()) { 18081 // This is set if HW acceleration is requested, even if the current 18082 // process doesn't allow it. This is just to allow app preview 18083 // windows to better match their app. 18084 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 18085 } 18086 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 18087 18088 final int privateFlags2 = mPrivateFlags2; 18089 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 18090 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 18091 } 18092 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 18093 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 18094 } 18095 18096 drawableState = StateSet.get(viewStateIndex); 18097 18098 //noinspection ConstantIfStatement 18099 if (false) { 18100 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18101 Log.i("View", toString() 18102 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18103 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18104 + " fo=" + hasFocus() 18105 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18106 + " wf=" + hasWindowFocus() 18107 + ": " + Arrays.toString(drawableState)); 18108 } 18109 18110 if (extraSpace == 0) { 18111 return drawableState; 18112 } 18113 18114 final int[] fullState; 18115 if (drawableState != null) { 18116 fullState = new int[drawableState.length + extraSpace]; 18117 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18118 } else { 18119 fullState = new int[extraSpace]; 18120 } 18121 18122 return fullState; 18123 } 18124 18125 /** 18126 * Merge your own state values in <var>additionalState</var> into the base 18127 * state values <var>baseState</var> that were returned by 18128 * {@link #onCreateDrawableState(int)}. 18129 * 18130 * @param baseState The base state values returned by 18131 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18132 * own additional state values. 18133 * 18134 * @param additionalState The additional state values you would like 18135 * added to <var>baseState</var>; this array is not modified. 18136 * 18137 * @return As a convenience, the <var>baseState</var> array you originally 18138 * passed into the function is returned. 18139 * 18140 * @see #onCreateDrawableState(int) 18141 */ 18142 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18143 final int N = baseState.length; 18144 int i = N - 1; 18145 while (i >= 0 && baseState[i] == 0) { 18146 i--; 18147 } 18148 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18149 return baseState; 18150 } 18151 18152 /** 18153 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18154 * on all Drawable objects associated with this view. 18155 * <p> 18156 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18157 * attached to this view. 18158 */ 18159 @CallSuper 18160 public void jumpDrawablesToCurrentState() { 18161 if (mBackground != null) { 18162 mBackground.jumpToCurrentState(); 18163 } 18164 if (mStateListAnimator != null) { 18165 mStateListAnimator.jumpToCurrentState(); 18166 } 18167 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18168 mForegroundInfo.mDrawable.jumpToCurrentState(); 18169 } 18170 } 18171 18172 /** 18173 * Sets the background color for this view. 18174 * @param color the color of the background 18175 */ 18176 @RemotableViewMethod 18177 public void setBackgroundColor(@ColorInt int color) { 18178 if (mBackground instanceof ColorDrawable) { 18179 ((ColorDrawable) mBackground.mutate()).setColor(color); 18180 computeOpaqueFlags(); 18181 mBackgroundResource = 0; 18182 } else { 18183 setBackground(new ColorDrawable(color)); 18184 } 18185 } 18186 18187 /** 18188 * Set the background to a given resource. The resource should refer to 18189 * a Drawable object or 0 to remove the background. 18190 * @param resid The identifier of the resource. 18191 * 18192 * @attr ref android.R.styleable#View_background 18193 */ 18194 @RemotableViewMethod 18195 public void setBackgroundResource(@DrawableRes int resid) { 18196 if (resid != 0 && resid == mBackgroundResource) { 18197 return; 18198 } 18199 18200 Drawable d = null; 18201 if (resid != 0) { 18202 d = mContext.getDrawable(resid); 18203 } 18204 setBackground(d); 18205 18206 mBackgroundResource = resid; 18207 } 18208 18209 /** 18210 * Set the background to a given Drawable, or remove the background. If the 18211 * background has padding, this View's padding is set to the background's 18212 * padding. However, when a background is removed, this View's padding isn't 18213 * touched. If setting the padding is desired, please use 18214 * {@link #setPadding(int, int, int, int)}. 18215 * 18216 * @param background The Drawable to use as the background, or null to remove the 18217 * background 18218 */ 18219 public void setBackground(Drawable background) { 18220 //noinspection deprecation 18221 setBackgroundDrawable(background); 18222 } 18223 18224 /** 18225 * @deprecated use {@link #setBackground(Drawable)} instead 18226 */ 18227 @Deprecated 18228 public void setBackgroundDrawable(Drawable background) { 18229 computeOpaqueFlags(); 18230 18231 if (background == mBackground) { 18232 return; 18233 } 18234 18235 boolean requestLayout = false; 18236 18237 mBackgroundResource = 0; 18238 18239 /* 18240 * Regardless of whether we're setting a new background or not, we want 18241 * to clear the previous drawable. setVisible first while we still have the callback set. 18242 */ 18243 if (mBackground != null) { 18244 if (isAttachedToWindow()) { 18245 mBackground.setVisible(false, false); 18246 } 18247 mBackground.setCallback(null); 18248 unscheduleDrawable(mBackground); 18249 } 18250 18251 if (background != null) { 18252 Rect padding = sThreadLocal.get(); 18253 if (padding == null) { 18254 padding = new Rect(); 18255 sThreadLocal.set(padding); 18256 } 18257 resetResolvedDrawablesInternal(); 18258 background.setLayoutDirection(getLayoutDirection()); 18259 if (background.getPadding(padding)) { 18260 resetResolvedPaddingInternal(); 18261 switch (background.getLayoutDirection()) { 18262 case LAYOUT_DIRECTION_RTL: 18263 mUserPaddingLeftInitial = padding.right; 18264 mUserPaddingRightInitial = padding.left; 18265 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18266 break; 18267 case LAYOUT_DIRECTION_LTR: 18268 default: 18269 mUserPaddingLeftInitial = padding.left; 18270 mUserPaddingRightInitial = padding.right; 18271 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18272 } 18273 mLeftPaddingDefined = false; 18274 mRightPaddingDefined = false; 18275 } 18276 18277 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18278 // if it has a different minimum size, we should layout again 18279 if (mBackground == null 18280 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18281 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18282 requestLayout = true; 18283 } 18284 18285 // Set mBackground before we set this as the callback and start making other 18286 // background drawable state change calls. In particular, the setVisible call below 18287 // can result in drawables attempting to start animations or otherwise invalidate, 18288 // which requires the view set as the callback (us) to recognize the drawable as 18289 // belonging to it as per verifyDrawable. 18290 mBackground = background; 18291 if (background.isStateful()) { 18292 background.setState(getDrawableState()); 18293 } 18294 if (isAttachedToWindow()) { 18295 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18296 } 18297 18298 applyBackgroundTint(); 18299 18300 // Set callback last, since the view may still be initializing. 18301 background.setCallback(this); 18302 18303 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18304 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18305 requestLayout = true; 18306 } 18307 } else { 18308 /* Remove the background */ 18309 mBackground = null; 18310 if ((mViewFlags & WILL_NOT_DRAW) != 0 18311 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18312 mPrivateFlags |= PFLAG_SKIP_DRAW; 18313 } 18314 18315 /* 18316 * When the background is set, we try to apply its padding to this 18317 * View. When the background is removed, we don't touch this View's 18318 * padding. This is noted in the Javadocs. Hence, we don't need to 18319 * requestLayout(), the invalidate() below is sufficient. 18320 */ 18321 18322 // The old background's minimum size could have affected this 18323 // View's layout, so let's requestLayout 18324 requestLayout = true; 18325 } 18326 18327 computeOpaqueFlags(); 18328 18329 if (requestLayout) { 18330 requestLayout(); 18331 } 18332 18333 mBackgroundSizeChanged = true; 18334 invalidate(true); 18335 invalidateOutline(); 18336 } 18337 18338 /** 18339 * Gets the background drawable 18340 * 18341 * @return The drawable used as the background for this view, if any. 18342 * 18343 * @see #setBackground(Drawable) 18344 * 18345 * @attr ref android.R.styleable#View_background 18346 */ 18347 public Drawable getBackground() { 18348 return mBackground; 18349 } 18350 18351 /** 18352 * Applies a tint to the background drawable. Does not modify the current tint 18353 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18354 * <p> 18355 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18356 * mutate the drawable and apply the specified tint and tint mode using 18357 * {@link Drawable#setTintList(ColorStateList)}. 18358 * 18359 * @param tint the tint to apply, may be {@code null} to clear tint 18360 * 18361 * @attr ref android.R.styleable#View_backgroundTint 18362 * @see #getBackgroundTintList() 18363 * @see Drawable#setTintList(ColorStateList) 18364 */ 18365 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18366 if (mBackgroundTint == null) { 18367 mBackgroundTint = new TintInfo(); 18368 } 18369 mBackgroundTint.mTintList = tint; 18370 mBackgroundTint.mHasTintList = true; 18371 18372 applyBackgroundTint(); 18373 } 18374 18375 /** 18376 * Return the tint applied to the background drawable, if specified. 18377 * 18378 * @return the tint applied to the background drawable 18379 * @attr ref android.R.styleable#View_backgroundTint 18380 * @see #setBackgroundTintList(ColorStateList) 18381 */ 18382 @Nullable 18383 public ColorStateList getBackgroundTintList() { 18384 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18385 } 18386 18387 /** 18388 * Specifies the blending mode used to apply the tint specified by 18389 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18390 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18391 * 18392 * @param tintMode the blending mode used to apply the tint, may be 18393 * {@code null} to clear tint 18394 * @attr ref android.R.styleable#View_backgroundTintMode 18395 * @see #getBackgroundTintMode() 18396 * @see Drawable#setTintMode(PorterDuff.Mode) 18397 */ 18398 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18399 if (mBackgroundTint == null) { 18400 mBackgroundTint = new TintInfo(); 18401 } 18402 mBackgroundTint.mTintMode = tintMode; 18403 mBackgroundTint.mHasTintMode = true; 18404 18405 applyBackgroundTint(); 18406 } 18407 18408 /** 18409 * Return the blending mode used to apply the tint to the background 18410 * drawable, if specified. 18411 * 18412 * @return the blending mode used to apply the tint to the background 18413 * drawable 18414 * @attr ref android.R.styleable#View_backgroundTintMode 18415 * @see #setBackgroundTintMode(PorterDuff.Mode) 18416 */ 18417 @Nullable 18418 public PorterDuff.Mode getBackgroundTintMode() { 18419 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18420 } 18421 18422 private void applyBackgroundTint() { 18423 if (mBackground != null && mBackgroundTint != null) { 18424 final TintInfo tintInfo = mBackgroundTint; 18425 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18426 mBackground = mBackground.mutate(); 18427 18428 if (tintInfo.mHasTintList) { 18429 mBackground.setTintList(tintInfo.mTintList); 18430 } 18431 18432 if (tintInfo.mHasTintMode) { 18433 mBackground.setTintMode(tintInfo.mTintMode); 18434 } 18435 18436 // The drawable (or one of its children) may not have been 18437 // stateful before applying the tint, so let's try again. 18438 if (mBackground.isStateful()) { 18439 mBackground.setState(getDrawableState()); 18440 } 18441 } 18442 } 18443 } 18444 18445 /** 18446 * Returns the drawable used as the foreground of this View. The 18447 * foreground drawable, if non-null, is always drawn on top of the view's content. 18448 * 18449 * @return a Drawable or null if no foreground was set 18450 * 18451 * @see #onDrawForeground(Canvas) 18452 */ 18453 public Drawable getForeground() { 18454 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18455 } 18456 18457 /** 18458 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18459 * 18460 * @param foreground the Drawable to be drawn on top of the children 18461 * 18462 * @attr ref android.R.styleable#View_foreground 18463 */ 18464 public void setForeground(Drawable foreground) { 18465 if (mForegroundInfo == null) { 18466 if (foreground == null) { 18467 // Nothing to do. 18468 return; 18469 } 18470 mForegroundInfo = new ForegroundInfo(); 18471 } 18472 18473 if (foreground == mForegroundInfo.mDrawable) { 18474 // Nothing to do 18475 return; 18476 } 18477 18478 if (mForegroundInfo.mDrawable != null) { 18479 if (isAttachedToWindow()) { 18480 mForegroundInfo.mDrawable.setVisible(false, false); 18481 } 18482 mForegroundInfo.mDrawable.setCallback(null); 18483 unscheduleDrawable(mForegroundInfo.mDrawable); 18484 } 18485 18486 mForegroundInfo.mDrawable = foreground; 18487 mForegroundInfo.mBoundsChanged = true; 18488 if (foreground != null) { 18489 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18490 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18491 } 18492 foreground.setLayoutDirection(getLayoutDirection()); 18493 if (foreground.isStateful()) { 18494 foreground.setState(getDrawableState()); 18495 } 18496 applyForegroundTint(); 18497 if (isAttachedToWindow()) { 18498 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18499 } 18500 // Set callback last, since the view may still be initializing. 18501 foreground.setCallback(this); 18502 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18503 mPrivateFlags |= PFLAG_SKIP_DRAW; 18504 } 18505 requestLayout(); 18506 invalidate(); 18507 } 18508 18509 /** 18510 * Magic bit used to support features of framework-internal window decor implementation details. 18511 * This used to live exclusively in FrameLayout. 18512 * 18513 * @return true if the foreground should draw inside the padding region or false 18514 * if it should draw inset by the view's padding 18515 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18516 */ 18517 public boolean isForegroundInsidePadding() { 18518 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18519 } 18520 18521 /** 18522 * Describes how the foreground is positioned. 18523 * 18524 * @return foreground gravity. 18525 * 18526 * @see #setForegroundGravity(int) 18527 * 18528 * @attr ref android.R.styleable#View_foregroundGravity 18529 */ 18530 public int getForegroundGravity() { 18531 return mForegroundInfo != null ? mForegroundInfo.mGravity 18532 : Gravity.START | Gravity.TOP; 18533 } 18534 18535 /** 18536 * Describes how the foreground is positioned. Defaults to START and TOP. 18537 * 18538 * @param gravity see {@link android.view.Gravity} 18539 * 18540 * @see #getForegroundGravity() 18541 * 18542 * @attr ref android.R.styleable#View_foregroundGravity 18543 */ 18544 public void setForegroundGravity(int gravity) { 18545 if (mForegroundInfo == null) { 18546 mForegroundInfo = new ForegroundInfo(); 18547 } 18548 18549 if (mForegroundInfo.mGravity != gravity) { 18550 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18551 gravity |= Gravity.START; 18552 } 18553 18554 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18555 gravity |= Gravity.TOP; 18556 } 18557 18558 mForegroundInfo.mGravity = gravity; 18559 requestLayout(); 18560 } 18561 } 18562 18563 /** 18564 * Applies a tint to the foreground drawable. Does not modify the current tint 18565 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18566 * <p> 18567 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18568 * mutate the drawable and apply the specified tint and tint mode using 18569 * {@link Drawable#setTintList(ColorStateList)}. 18570 * 18571 * @param tint the tint to apply, may be {@code null} to clear tint 18572 * 18573 * @attr ref android.R.styleable#View_foregroundTint 18574 * @see #getForegroundTintList() 18575 * @see Drawable#setTintList(ColorStateList) 18576 */ 18577 public void setForegroundTintList(@Nullable ColorStateList tint) { 18578 if (mForegroundInfo == null) { 18579 mForegroundInfo = new ForegroundInfo(); 18580 } 18581 if (mForegroundInfo.mTintInfo == null) { 18582 mForegroundInfo.mTintInfo = new TintInfo(); 18583 } 18584 mForegroundInfo.mTintInfo.mTintList = tint; 18585 mForegroundInfo.mTintInfo.mHasTintList = true; 18586 18587 applyForegroundTint(); 18588 } 18589 18590 /** 18591 * Return the tint applied to the foreground drawable, if specified. 18592 * 18593 * @return the tint applied to the foreground drawable 18594 * @attr ref android.R.styleable#View_foregroundTint 18595 * @see #setForegroundTintList(ColorStateList) 18596 */ 18597 @Nullable 18598 public ColorStateList getForegroundTintList() { 18599 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18600 ? mForegroundInfo.mTintInfo.mTintList : null; 18601 } 18602 18603 /** 18604 * Specifies the blending mode used to apply the tint specified by 18605 * {@link #setForegroundTintList(ColorStateList)}} to the background 18606 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18607 * 18608 * @param tintMode the blending mode used to apply the tint, may be 18609 * {@code null} to clear tint 18610 * @attr ref android.R.styleable#View_foregroundTintMode 18611 * @see #getForegroundTintMode() 18612 * @see Drawable#setTintMode(PorterDuff.Mode) 18613 */ 18614 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18615 if (mForegroundInfo == null) { 18616 mForegroundInfo = new ForegroundInfo(); 18617 } 18618 if (mForegroundInfo.mTintInfo == null) { 18619 mForegroundInfo.mTintInfo = new TintInfo(); 18620 } 18621 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18622 mForegroundInfo.mTintInfo.mHasTintMode = true; 18623 18624 applyForegroundTint(); 18625 } 18626 18627 /** 18628 * Return the blending mode used to apply the tint to the foreground 18629 * drawable, if specified. 18630 * 18631 * @return the blending mode used to apply the tint to the foreground 18632 * drawable 18633 * @attr ref android.R.styleable#View_foregroundTintMode 18634 * @see #setForegroundTintMode(PorterDuff.Mode) 18635 */ 18636 @Nullable 18637 public PorterDuff.Mode getForegroundTintMode() { 18638 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18639 ? mForegroundInfo.mTintInfo.mTintMode : null; 18640 } 18641 18642 private void applyForegroundTint() { 18643 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18644 && mForegroundInfo.mTintInfo != null) { 18645 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18646 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18647 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18648 18649 if (tintInfo.mHasTintList) { 18650 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18651 } 18652 18653 if (tintInfo.mHasTintMode) { 18654 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18655 } 18656 18657 // The drawable (or one of its children) may not have been 18658 // stateful before applying the tint, so let's try again. 18659 if (mForegroundInfo.mDrawable.isStateful()) { 18660 mForegroundInfo.mDrawable.setState(getDrawableState()); 18661 } 18662 } 18663 } 18664 } 18665 18666 /** 18667 * Draw any foreground content for this view. 18668 * 18669 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18670 * drawable or other view-specific decorations. The foreground is drawn on top of the 18671 * primary view content.</p> 18672 * 18673 * @param canvas canvas to draw into 18674 */ 18675 public void onDrawForeground(Canvas canvas) { 18676 onDrawScrollIndicators(canvas); 18677 onDrawScrollBars(canvas); 18678 18679 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18680 if (foreground != null) { 18681 if (mForegroundInfo.mBoundsChanged) { 18682 mForegroundInfo.mBoundsChanged = false; 18683 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18684 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18685 18686 if (mForegroundInfo.mInsidePadding) { 18687 selfBounds.set(0, 0, getWidth(), getHeight()); 18688 } else { 18689 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18690 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18691 } 18692 18693 final int ld = getLayoutDirection(); 18694 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18695 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18696 foreground.setBounds(overlayBounds); 18697 } 18698 18699 foreground.draw(canvas); 18700 } 18701 } 18702 18703 /** 18704 * Sets the padding. The view may add on the space required to display 18705 * the scrollbars, depending on the style and visibility of the scrollbars. 18706 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18707 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18708 * from the values set in this call. 18709 * 18710 * @attr ref android.R.styleable#View_padding 18711 * @attr ref android.R.styleable#View_paddingBottom 18712 * @attr ref android.R.styleable#View_paddingLeft 18713 * @attr ref android.R.styleable#View_paddingRight 18714 * @attr ref android.R.styleable#View_paddingTop 18715 * @param left the left padding in pixels 18716 * @param top the top padding in pixels 18717 * @param right the right padding in pixels 18718 * @param bottom the bottom padding in pixels 18719 */ 18720 public void setPadding(int left, int top, int right, int bottom) { 18721 resetResolvedPaddingInternal(); 18722 18723 mUserPaddingStart = UNDEFINED_PADDING; 18724 mUserPaddingEnd = UNDEFINED_PADDING; 18725 18726 mUserPaddingLeftInitial = left; 18727 mUserPaddingRightInitial = right; 18728 18729 mLeftPaddingDefined = true; 18730 mRightPaddingDefined = true; 18731 18732 internalSetPadding(left, top, right, bottom); 18733 } 18734 18735 /** 18736 * @hide 18737 */ 18738 protected void internalSetPadding(int left, int top, int right, int bottom) { 18739 mUserPaddingLeft = left; 18740 mUserPaddingRight = right; 18741 mUserPaddingBottom = bottom; 18742 18743 final int viewFlags = mViewFlags; 18744 boolean changed = false; 18745 18746 // Common case is there are no scroll bars. 18747 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18748 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18749 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18750 ? 0 : getVerticalScrollbarWidth(); 18751 switch (mVerticalScrollbarPosition) { 18752 case SCROLLBAR_POSITION_DEFAULT: 18753 if (isLayoutRtl()) { 18754 left += offset; 18755 } else { 18756 right += offset; 18757 } 18758 break; 18759 case SCROLLBAR_POSITION_RIGHT: 18760 right += offset; 18761 break; 18762 case SCROLLBAR_POSITION_LEFT: 18763 left += offset; 18764 break; 18765 } 18766 } 18767 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18768 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18769 ? 0 : getHorizontalScrollbarHeight(); 18770 } 18771 } 18772 18773 if (mPaddingLeft != left) { 18774 changed = true; 18775 mPaddingLeft = left; 18776 } 18777 if (mPaddingTop != top) { 18778 changed = true; 18779 mPaddingTop = top; 18780 } 18781 if (mPaddingRight != right) { 18782 changed = true; 18783 mPaddingRight = right; 18784 } 18785 if (mPaddingBottom != bottom) { 18786 changed = true; 18787 mPaddingBottom = bottom; 18788 } 18789 18790 if (changed) { 18791 requestLayout(); 18792 invalidateOutline(); 18793 } 18794 } 18795 18796 /** 18797 * Sets the relative padding. The view may add on the space required to display 18798 * the scrollbars, depending on the style and visibility of the scrollbars. 18799 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18800 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18801 * from the values set in this call. 18802 * 18803 * @attr ref android.R.styleable#View_padding 18804 * @attr ref android.R.styleable#View_paddingBottom 18805 * @attr ref android.R.styleable#View_paddingStart 18806 * @attr ref android.R.styleable#View_paddingEnd 18807 * @attr ref android.R.styleable#View_paddingTop 18808 * @param start the start padding in pixels 18809 * @param top the top padding in pixels 18810 * @param end the end padding in pixels 18811 * @param bottom the bottom padding in pixels 18812 */ 18813 public void setPaddingRelative(int start, int top, int end, int bottom) { 18814 resetResolvedPaddingInternal(); 18815 18816 mUserPaddingStart = start; 18817 mUserPaddingEnd = end; 18818 mLeftPaddingDefined = true; 18819 mRightPaddingDefined = true; 18820 18821 switch(getLayoutDirection()) { 18822 case LAYOUT_DIRECTION_RTL: 18823 mUserPaddingLeftInitial = end; 18824 mUserPaddingRightInitial = start; 18825 internalSetPadding(end, top, start, bottom); 18826 break; 18827 case LAYOUT_DIRECTION_LTR: 18828 default: 18829 mUserPaddingLeftInitial = start; 18830 mUserPaddingRightInitial = end; 18831 internalSetPadding(start, top, end, bottom); 18832 } 18833 } 18834 18835 /** 18836 * Returns the top padding of this view. 18837 * 18838 * @return the top padding in pixels 18839 */ 18840 public int getPaddingTop() { 18841 return mPaddingTop; 18842 } 18843 18844 /** 18845 * Returns the bottom padding of this view. If there are inset and enabled 18846 * scrollbars, this value may include the space required to display the 18847 * scrollbars as well. 18848 * 18849 * @return the bottom padding in pixels 18850 */ 18851 public int getPaddingBottom() { 18852 return mPaddingBottom; 18853 } 18854 18855 /** 18856 * Returns the left padding of this view. If there are inset and enabled 18857 * scrollbars, this value may include the space required to display the 18858 * scrollbars as well. 18859 * 18860 * @return the left padding in pixels 18861 */ 18862 public int getPaddingLeft() { 18863 if (!isPaddingResolved()) { 18864 resolvePadding(); 18865 } 18866 return mPaddingLeft; 18867 } 18868 18869 /** 18870 * Returns the start padding of this view depending on its resolved layout direction. 18871 * If there are inset and enabled scrollbars, this value may include the space 18872 * required to display the scrollbars as well. 18873 * 18874 * @return the start padding in pixels 18875 */ 18876 public int getPaddingStart() { 18877 if (!isPaddingResolved()) { 18878 resolvePadding(); 18879 } 18880 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18881 mPaddingRight : mPaddingLeft; 18882 } 18883 18884 /** 18885 * Returns the right padding of this view. If there are inset and enabled 18886 * scrollbars, this value may include the space required to display the 18887 * scrollbars as well. 18888 * 18889 * @return the right padding in pixels 18890 */ 18891 public int getPaddingRight() { 18892 if (!isPaddingResolved()) { 18893 resolvePadding(); 18894 } 18895 return mPaddingRight; 18896 } 18897 18898 /** 18899 * Returns the end padding of this view depending on its resolved layout direction. 18900 * If there are inset and enabled scrollbars, this value may include the space 18901 * required to display the scrollbars as well. 18902 * 18903 * @return the end padding in pixels 18904 */ 18905 public int getPaddingEnd() { 18906 if (!isPaddingResolved()) { 18907 resolvePadding(); 18908 } 18909 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18910 mPaddingLeft : mPaddingRight; 18911 } 18912 18913 /** 18914 * Return if the padding has been set through relative values 18915 * {@link #setPaddingRelative(int, int, int, int)} or through 18916 * @attr ref android.R.styleable#View_paddingStart or 18917 * @attr ref android.R.styleable#View_paddingEnd 18918 * 18919 * @return true if the padding is relative or false if it is not. 18920 */ 18921 public boolean isPaddingRelative() { 18922 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18923 } 18924 18925 Insets computeOpticalInsets() { 18926 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18927 } 18928 18929 /** 18930 * @hide 18931 */ 18932 public void resetPaddingToInitialValues() { 18933 if (isRtlCompatibilityMode()) { 18934 mPaddingLeft = mUserPaddingLeftInitial; 18935 mPaddingRight = mUserPaddingRightInitial; 18936 return; 18937 } 18938 if (isLayoutRtl()) { 18939 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18940 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18941 } else { 18942 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18943 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18944 } 18945 } 18946 18947 /** 18948 * @hide 18949 */ 18950 public Insets getOpticalInsets() { 18951 if (mLayoutInsets == null) { 18952 mLayoutInsets = computeOpticalInsets(); 18953 } 18954 return mLayoutInsets; 18955 } 18956 18957 /** 18958 * Set this view's optical insets. 18959 * 18960 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18961 * property. Views that compute their own optical insets should call it as part of measurement. 18962 * This method does not request layout. If you are setting optical insets outside of 18963 * measure/layout itself you will want to call requestLayout() yourself. 18964 * </p> 18965 * @hide 18966 */ 18967 public void setOpticalInsets(Insets insets) { 18968 mLayoutInsets = insets; 18969 } 18970 18971 /** 18972 * Changes the selection state of this view. A view can be selected or not. 18973 * Note that selection is not the same as focus. Views are typically 18974 * selected in the context of an AdapterView like ListView or GridView; 18975 * the selected view is the view that is highlighted. 18976 * 18977 * @param selected true if the view must be selected, false otherwise 18978 */ 18979 public void setSelected(boolean selected) { 18980 //noinspection DoubleNegation 18981 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18982 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18983 if (!selected) resetPressedState(); 18984 invalidate(true); 18985 refreshDrawableState(); 18986 dispatchSetSelected(selected); 18987 if (selected) { 18988 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18989 } else { 18990 notifyViewAccessibilityStateChangedIfNeeded( 18991 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18992 } 18993 } 18994 } 18995 18996 /** 18997 * Dispatch setSelected to all of this View's children. 18998 * 18999 * @see #setSelected(boolean) 19000 * 19001 * @param selected The new selected state 19002 */ 19003 protected void dispatchSetSelected(boolean selected) { 19004 } 19005 19006 /** 19007 * Indicates the selection state of this view. 19008 * 19009 * @return true if the view is selected, false otherwise 19010 */ 19011 @ViewDebug.ExportedProperty 19012 public boolean isSelected() { 19013 return (mPrivateFlags & PFLAG_SELECTED) != 0; 19014 } 19015 19016 /** 19017 * Changes the activated state of this view. A view can be activated or not. 19018 * Note that activation is not the same as selection. Selection is 19019 * a transient property, representing the view (hierarchy) the user is 19020 * currently interacting with. Activation is a longer-term state that the 19021 * user can move views in and out of. For example, in a list view with 19022 * single or multiple selection enabled, the views in the current selection 19023 * set are activated. (Um, yeah, we are deeply sorry about the terminology 19024 * here.) The activated state is propagated down to children of the view it 19025 * is set on. 19026 * 19027 * @param activated true if the view must be activated, false otherwise 19028 */ 19029 public void setActivated(boolean activated) { 19030 //noinspection DoubleNegation 19031 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 19032 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 19033 invalidate(true); 19034 refreshDrawableState(); 19035 dispatchSetActivated(activated); 19036 } 19037 } 19038 19039 /** 19040 * Dispatch setActivated to all of this View's children. 19041 * 19042 * @see #setActivated(boolean) 19043 * 19044 * @param activated The new activated state 19045 */ 19046 protected void dispatchSetActivated(boolean activated) { 19047 } 19048 19049 /** 19050 * Indicates the activation state of this view. 19051 * 19052 * @return true if the view is activated, false otherwise 19053 */ 19054 @ViewDebug.ExportedProperty 19055 public boolean isActivated() { 19056 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 19057 } 19058 19059 /** 19060 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 19061 * observer can be used to get notifications when global events, like 19062 * layout, happen. 19063 * 19064 * The returned ViewTreeObserver observer is not guaranteed to remain 19065 * valid for the lifetime of this View. If the caller of this method keeps 19066 * a long-lived reference to ViewTreeObserver, it should always check for 19067 * the return value of {@link ViewTreeObserver#isAlive()}. 19068 * 19069 * @return The ViewTreeObserver for this view's hierarchy. 19070 */ 19071 public ViewTreeObserver getViewTreeObserver() { 19072 if (mAttachInfo != null) { 19073 return mAttachInfo.mTreeObserver; 19074 } 19075 if (mFloatingTreeObserver == null) { 19076 mFloatingTreeObserver = new ViewTreeObserver(mContext); 19077 } 19078 return mFloatingTreeObserver; 19079 } 19080 19081 /** 19082 * <p>Finds the topmost view in the current view hierarchy.</p> 19083 * 19084 * @return the topmost view containing this view 19085 */ 19086 public View getRootView() { 19087 if (mAttachInfo != null) { 19088 final View v = mAttachInfo.mRootView; 19089 if (v != null) { 19090 return v; 19091 } 19092 } 19093 19094 View parent = this; 19095 19096 while (parent.mParent != null && parent.mParent instanceof View) { 19097 parent = (View) parent.mParent; 19098 } 19099 19100 return parent; 19101 } 19102 19103 /** 19104 * Transforms a motion event from view-local coordinates to on-screen 19105 * coordinates. 19106 * 19107 * @param ev the view-local motion event 19108 * @return false if the transformation could not be applied 19109 * @hide 19110 */ 19111 public boolean toGlobalMotionEvent(MotionEvent ev) { 19112 final AttachInfo info = mAttachInfo; 19113 if (info == null) { 19114 return false; 19115 } 19116 19117 final Matrix m = info.mTmpMatrix; 19118 m.set(Matrix.IDENTITY_MATRIX); 19119 transformMatrixToGlobal(m); 19120 ev.transform(m); 19121 return true; 19122 } 19123 19124 /** 19125 * Transforms a motion event from on-screen coordinates to view-local 19126 * coordinates. 19127 * 19128 * @param ev the on-screen motion event 19129 * @return false if the transformation could not be applied 19130 * @hide 19131 */ 19132 public boolean toLocalMotionEvent(MotionEvent ev) { 19133 final AttachInfo info = mAttachInfo; 19134 if (info == null) { 19135 return false; 19136 } 19137 19138 final Matrix m = info.mTmpMatrix; 19139 m.set(Matrix.IDENTITY_MATRIX); 19140 transformMatrixToLocal(m); 19141 ev.transform(m); 19142 return true; 19143 } 19144 19145 /** 19146 * Modifies the input matrix such that it maps view-local coordinates to 19147 * on-screen coordinates. 19148 * 19149 * @param m input matrix to modify 19150 * @hide 19151 */ 19152 public void transformMatrixToGlobal(Matrix m) { 19153 final ViewParent parent = mParent; 19154 if (parent instanceof View) { 19155 final View vp = (View) parent; 19156 vp.transformMatrixToGlobal(m); 19157 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19158 } else if (parent instanceof ViewRootImpl) { 19159 final ViewRootImpl vr = (ViewRootImpl) parent; 19160 vr.transformMatrixToGlobal(m); 19161 m.preTranslate(0, -vr.mCurScrollY); 19162 } 19163 19164 m.preTranslate(mLeft, mTop); 19165 19166 if (!hasIdentityMatrix()) { 19167 m.preConcat(getMatrix()); 19168 } 19169 } 19170 19171 /** 19172 * Modifies the input matrix such that it maps on-screen coordinates to 19173 * view-local coordinates. 19174 * 19175 * @param m input matrix to modify 19176 * @hide 19177 */ 19178 public void transformMatrixToLocal(Matrix m) { 19179 final ViewParent parent = mParent; 19180 if (parent instanceof View) { 19181 final View vp = (View) parent; 19182 vp.transformMatrixToLocal(m); 19183 m.postTranslate(vp.mScrollX, vp.mScrollY); 19184 } else if (parent instanceof ViewRootImpl) { 19185 final ViewRootImpl vr = (ViewRootImpl) parent; 19186 vr.transformMatrixToLocal(m); 19187 m.postTranslate(0, vr.mCurScrollY); 19188 } 19189 19190 m.postTranslate(-mLeft, -mTop); 19191 19192 if (!hasIdentityMatrix()) { 19193 m.postConcat(getInverseMatrix()); 19194 } 19195 } 19196 19197 /** 19198 * @hide 19199 */ 19200 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19201 @ViewDebug.IntToString(from = 0, to = "x"), 19202 @ViewDebug.IntToString(from = 1, to = "y") 19203 }) 19204 public int[] getLocationOnScreen() { 19205 int[] location = new int[2]; 19206 getLocationOnScreen(location); 19207 return location; 19208 } 19209 19210 /** 19211 * <p>Computes the coordinates of this view on the screen. The argument 19212 * must be an array of two integers. After the method returns, the array 19213 * contains the x and y location in that order.</p> 19214 * 19215 * @param outLocation an array of two integers in which to hold the coordinates 19216 */ 19217 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19218 getLocationInWindow(outLocation); 19219 19220 final AttachInfo info = mAttachInfo; 19221 if (info != null) { 19222 outLocation[0] += info.mWindowLeft; 19223 outLocation[1] += info.mWindowTop; 19224 } 19225 } 19226 19227 /** 19228 * <p>Computes the coordinates of this view in its window. The argument 19229 * must be an array of two integers. After the method returns, the array 19230 * contains the x and y location in that order.</p> 19231 * 19232 * @param outLocation an array of two integers in which to hold the coordinates 19233 */ 19234 public void getLocationInWindow(@Size(2) int[] outLocation) { 19235 if (outLocation == null || outLocation.length < 2) { 19236 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19237 } 19238 19239 outLocation[0] = 0; 19240 outLocation[1] = 0; 19241 19242 transformFromViewToWindowSpace(outLocation); 19243 } 19244 19245 /** @hide */ 19246 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19247 if (inOutLocation == null || inOutLocation.length < 2) { 19248 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19249 } 19250 19251 if (mAttachInfo == null) { 19252 // When the view is not attached to a window, this method does not make sense 19253 inOutLocation[0] = inOutLocation[1] = 0; 19254 return; 19255 } 19256 19257 float position[] = mAttachInfo.mTmpTransformLocation; 19258 position[0] = inOutLocation[0]; 19259 position[1] = inOutLocation[1]; 19260 19261 if (!hasIdentityMatrix()) { 19262 getMatrix().mapPoints(position); 19263 } 19264 19265 position[0] += mLeft; 19266 position[1] += mTop; 19267 19268 ViewParent viewParent = mParent; 19269 while (viewParent instanceof View) { 19270 final View view = (View) viewParent; 19271 19272 position[0] -= view.mScrollX; 19273 position[1] -= view.mScrollY; 19274 19275 if (!view.hasIdentityMatrix()) { 19276 view.getMatrix().mapPoints(position); 19277 } 19278 19279 position[0] += view.mLeft; 19280 position[1] += view.mTop; 19281 19282 viewParent = view.mParent; 19283 } 19284 19285 if (viewParent instanceof ViewRootImpl) { 19286 // *cough* 19287 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19288 position[1] -= vr.mCurScrollY; 19289 } 19290 19291 inOutLocation[0] = Math.round(position[0]); 19292 inOutLocation[1] = Math.round(position[1]); 19293 } 19294 19295 /** 19296 * {@hide} 19297 * @param id the id of the view to be found 19298 * @return the view of the specified id, null if cannot be found 19299 */ 19300 protected View findViewTraversal(@IdRes int id) { 19301 if (id == mID) { 19302 return this; 19303 } 19304 return null; 19305 } 19306 19307 /** 19308 * {@hide} 19309 * @param tag the tag of the view to be found 19310 * @return the view of specified tag, null if cannot be found 19311 */ 19312 protected View findViewWithTagTraversal(Object tag) { 19313 if (tag != null && tag.equals(mTag)) { 19314 return this; 19315 } 19316 return null; 19317 } 19318 19319 /** 19320 * {@hide} 19321 * @param predicate The predicate to evaluate. 19322 * @param childToSkip If not null, ignores this child during the recursive traversal. 19323 * @return The first view that matches the predicate or null. 19324 */ 19325 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19326 if (predicate.apply(this)) { 19327 return this; 19328 } 19329 return null; 19330 } 19331 19332 /** 19333 * Look for a child view with the given id. If this view has the given 19334 * id, return this view. 19335 * 19336 * @param id The id to search for. 19337 * @return The view that has the given id in the hierarchy or null 19338 */ 19339 @Nullable 19340 public final View findViewById(@IdRes int id) { 19341 if (id < 0) { 19342 return null; 19343 } 19344 return findViewTraversal(id); 19345 } 19346 19347 /** 19348 * Finds a view by its unuque and stable accessibility id. 19349 * 19350 * @param accessibilityId The searched accessibility id. 19351 * @return The found view. 19352 */ 19353 final View findViewByAccessibilityId(int accessibilityId) { 19354 if (accessibilityId < 0) { 19355 return null; 19356 } 19357 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19358 if (view != null) { 19359 return view.includeForAccessibility() ? view : null; 19360 } 19361 return null; 19362 } 19363 19364 /** 19365 * Performs the traversal to find a view by its unuque and stable accessibility id. 19366 * 19367 * <strong>Note:</strong>This method does not stop at the root namespace 19368 * boundary since the user can touch the screen at an arbitrary location 19369 * potentially crossing the root namespace bounday which will send an 19370 * accessibility event to accessibility services and they should be able 19371 * to obtain the event source. Also accessibility ids are guaranteed to be 19372 * unique in the window. 19373 * 19374 * @param accessibilityId The accessibility id. 19375 * @return The found view. 19376 * 19377 * @hide 19378 */ 19379 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19380 if (getAccessibilityViewId() == accessibilityId) { 19381 return this; 19382 } 19383 return null; 19384 } 19385 19386 /** 19387 * Look for a child view with the given tag. If this view has the given 19388 * tag, return this view. 19389 * 19390 * @param tag The tag to search for, using "tag.equals(getTag())". 19391 * @return The View that has the given tag in the hierarchy or null 19392 */ 19393 public final View findViewWithTag(Object tag) { 19394 if (tag == null) { 19395 return null; 19396 } 19397 return findViewWithTagTraversal(tag); 19398 } 19399 19400 /** 19401 * {@hide} 19402 * Look for a child view that matches the specified predicate. 19403 * If this view matches the predicate, return this view. 19404 * 19405 * @param predicate The predicate to evaluate. 19406 * @return The first view that matches the predicate or null. 19407 */ 19408 public final View findViewByPredicate(Predicate<View> predicate) { 19409 return findViewByPredicateTraversal(predicate, null); 19410 } 19411 19412 /** 19413 * {@hide} 19414 * Look for a child view that matches the specified predicate, 19415 * starting with the specified view and its descendents and then 19416 * recusively searching the ancestors and siblings of that view 19417 * until this view is reached. 19418 * 19419 * This method is useful in cases where the predicate does not match 19420 * a single unique view (perhaps multiple views use the same id) 19421 * and we are trying to find the view that is "closest" in scope to the 19422 * starting view. 19423 * 19424 * @param start The view to start from. 19425 * @param predicate The predicate to evaluate. 19426 * @return The first view that matches the predicate or null. 19427 */ 19428 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19429 View childToSkip = null; 19430 for (;;) { 19431 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19432 if (view != null || start == this) { 19433 return view; 19434 } 19435 19436 ViewParent parent = start.getParent(); 19437 if (parent == null || !(parent instanceof View)) { 19438 return null; 19439 } 19440 19441 childToSkip = start; 19442 start = (View) parent; 19443 } 19444 } 19445 19446 /** 19447 * Sets the identifier for this view. The identifier does not have to be 19448 * unique in this view's hierarchy. The identifier should be a positive 19449 * number. 19450 * 19451 * @see #NO_ID 19452 * @see #getId() 19453 * @see #findViewById(int) 19454 * 19455 * @param id a number used to identify the view 19456 * 19457 * @attr ref android.R.styleable#View_id 19458 */ 19459 public void setId(@IdRes int id) { 19460 mID = id; 19461 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19462 mID = generateViewId(); 19463 } 19464 } 19465 19466 /** 19467 * {@hide} 19468 * 19469 * @param isRoot true if the view belongs to the root namespace, false 19470 * otherwise 19471 */ 19472 public void setIsRootNamespace(boolean isRoot) { 19473 if (isRoot) { 19474 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19475 } else { 19476 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19477 } 19478 } 19479 19480 /** 19481 * {@hide} 19482 * 19483 * @return true if the view belongs to the root namespace, false otherwise 19484 */ 19485 public boolean isRootNamespace() { 19486 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19487 } 19488 19489 /** 19490 * Returns this view's identifier. 19491 * 19492 * @return a positive integer used to identify the view or {@link #NO_ID} 19493 * if the view has no ID 19494 * 19495 * @see #setId(int) 19496 * @see #findViewById(int) 19497 * @attr ref android.R.styleable#View_id 19498 */ 19499 @IdRes 19500 @ViewDebug.CapturedViewProperty 19501 public int getId() { 19502 return mID; 19503 } 19504 19505 /** 19506 * Returns this view's tag. 19507 * 19508 * @return the Object stored in this view as a tag, or {@code null} if not 19509 * set 19510 * 19511 * @see #setTag(Object) 19512 * @see #getTag(int) 19513 */ 19514 @ViewDebug.ExportedProperty 19515 public Object getTag() { 19516 return mTag; 19517 } 19518 19519 /** 19520 * Sets the tag associated with this view. A tag can be used to mark 19521 * a view in its hierarchy and does not have to be unique within the 19522 * hierarchy. Tags can also be used to store data within a view without 19523 * resorting to another data structure. 19524 * 19525 * @param tag an Object to tag the view with 19526 * 19527 * @see #getTag() 19528 * @see #setTag(int, Object) 19529 */ 19530 public void setTag(final Object tag) { 19531 mTag = tag; 19532 } 19533 19534 /** 19535 * Returns the tag associated with this view and the specified key. 19536 * 19537 * @param key The key identifying the tag 19538 * 19539 * @return the Object stored in this view as a tag, or {@code null} if not 19540 * set 19541 * 19542 * @see #setTag(int, Object) 19543 * @see #getTag() 19544 */ 19545 public Object getTag(int key) { 19546 if (mKeyedTags != null) return mKeyedTags.get(key); 19547 return null; 19548 } 19549 19550 /** 19551 * Sets a tag associated with this view and a key. A tag can be used 19552 * to mark a view in its hierarchy and does not have to be unique within 19553 * the hierarchy. Tags can also be used to store data within a view 19554 * without resorting to another data structure. 19555 * 19556 * The specified key should be an id declared in the resources of the 19557 * application to ensure it is unique (see the <a 19558 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19559 * Keys identified as belonging to 19560 * the Android framework or not associated with any package will cause 19561 * an {@link IllegalArgumentException} to be thrown. 19562 * 19563 * @param key The key identifying the tag 19564 * @param tag An Object to tag the view with 19565 * 19566 * @throws IllegalArgumentException If they specified key is not valid 19567 * 19568 * @see #setTag(Object) 19569 * @see #getTag(int) 19570 */ 19571 public void setTag(int key, final Object tag) { 19572 // If the package id is 0x00 or 0x01, it's either an undefined package 19573 // or a framework id 19574 if ((key >>> 24) < 2) { 19575 throw new IllegalArgumentException("The key must be an application-specific " 19576 + "resource id."); 19577 } 19578 19579 setKeyedTag(key, tag); 19580 } 19581 19582 /** 19583 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19584 * framework id. 19585 * 19586 * @hide 19587 */ 19588 public void setTagInternal(int key, Object tag) { 19589 if ((key >>> 24) != 0x1) { 19590 throw new IllegalArgumentException("The key must be a framework-specific " 19591 + "resource id."); 19592 } 19593 19594 setKeyedTag(key, tag); 19595 } 19596 19597 private void setKeyedTag(int key, Object tag) { 19598 if (mKeyedTags == null) { 19599 mKeyedTags = new SparseArray<Object>(2); 19600 } 19601 19602 mKeyedTags.put(key, tag); 19603 } 19604 19605 /** 19606 * Prints information about this view in the log output, with the tag 19607 * {@link #VIEW_LOG_TAG}. 19608 * 19609 * @hide 19610 */ 19611 public void debug() { 19612 debug(0); 19613 } 19614 19615 /** 19616 * Prints information about this view in the log output, with the tag 19617 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19618 * indentation defined by the <code>depth</code>. 19619 * 19620 * @param depth the indentation level 19621 * 19622 * @hide 19623 */ 19624 protected void debug(int depth) { 19625 String output = debugIndent(depth - 1); 19626 19627 output += "+ " + this; 19628 int id = getId(); 19629 if (id != -1) { 19630 output += " (id=" + id + ")"; 19631 } 19632 Object tag = getTag(); 19633 if (tag != null) { 19634 output += " (tag=" + tag + ")"; 19635 } 19636 Log.d(VIEW_LOG_TAG, output); 19637 19638 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19639 output = debugIndent(depth) + " FOCUSED"; 19640 Log.d(VIEW_LOG_TAG, output); 19641 } 19642 19643 output = debugIndent(depth); 19644 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19645 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19646 + "} "; 19647 Log.d(VIEW_LOG_TAG, output); 19648 19649 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19650 || mPaddingBottom != 0) { 19651 output = debugIndent(depth); 19652 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19653 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19654 Log.d(VIEW_LOG_TAG, output); 19655 } 19656 19657 output = debugIndent(depth); 19658 output += "mMeasureWidth=" + mMeasuredWidth + 19659 " mMeasureHeight=" + mMeasuredHeight; 19660 Log.d(VIEW_LOG_TAG, output); 19661 19662 output = debugIndent(depth); 19663 if (mLayoutParams == null) { 19664 output += "BAD! no layout params"; 19665 } else { 19666 output = mLayoutParams.debug(output); 19667 } 19668 Log.d(VIEW_LOG_TAG, output); 19669 19670 output = debugIndent(depth); 19671 output += "flags={"; 19672 output += View.printFlags(mViewFlags); 19673 output += "}"; 19674 Log.d(VIEW_LOG_TAG, output); 19675 19676 output = debugIndent(depth); 19677 output += "privateFlags={"; 19678 output += View.printPrivateFlags(mPrivateFlags); 19679 output += "}"; 19680 Log.d(VIEW_LOG_TAG, output); 19681 } 19682 19683 /** 19684 * Creates a string of whitespaces used for indentation. 19685 * 19686 * @param depth the indentation level 19687 * @return a String containing (depth * 2 + 3) * 2 white spaces 19688 * 19689 * @hide 19690 */ 19691 protected static String debugIndent(int depth) { 19692 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19693 for (int i = 0; i < (depth * 2) + 3; i++) { 19694 spaces.append(' ').append(' '); 19695 } 19696 return spaces.toString(); 19697 } 19698 19699 /** 19700 * <p>Return the offset of the widget's text baseline from the widget's top 19701 * boundary. If this widget does not support baseline alignment, this 19702 * method returns -1. </p> 19703 * 19704 * @return the offset of the baseline within the widget's bounds or -1 19705 * if baseline alignment is not supported 19706 */ 19707 @ViewDebug.ExportedProperty(category = "layout") 19708 public int getBaseline() { 19709 return -1; 19710 } 19711 19712 /** 19713 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19714 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19715 * a layout pass. 19716 * 19717 * @return whether the view hierarchy is currently undergoing a layout pass 19718 */ 19719 public boolean isInLayout() { 19720 ViewRootImpl viewRoot = getViewRootImpl(); 19721 return (viewRoot != null && viewRoot.isInLayout()); 19722 } 19723 19724 /** 19725 * Call this when something has changed which has invalidated the 19726 * layout of this view. This will schedule a layout pass of the view 19727 * tree. This should not be called while the view hierarchy is currently in a layout 19728 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19729 * end of the current layout pass (and then layout will run again) or after the current 19730 * frame is drawn and the next layout occurs. 19731 * 19732 * <p>Subclasses which override this method should call the superclass method to 19733 * handle possible request-during-layout errors correctly.</p> 19734 */ 19735 @CallSuper 19736 public void requestLayout() { 19737 if (mMeasureCache != null) mMeasureCache.clear(); 19738 19739 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19740 // Only trigger request-during-layout logic if this is the view requesting it, 19741 // not the views in its parent hierarchy 19742 ViewRootImpl viewRoot = getViewRootImpl(); 19743 if (viewRoot != null && viewRoot.isInLayout()) { 19744 if (!viewRoot.requestLayoutDuringLayout(this)) { 19745 return; 19746 } 19747 } 19748 mAttachInfo.mViewRequestingLayout = this; 19749 } 19750 19751 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19752 mPrivateFlags |= PFLAG_INVALIDATED; 19753 19754 if (mParent != null && !mParent.isLayoutRequested()) { 19755 mParent.requestLayout(); 19756 } 19757 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19758 mAttachInfo.mViewRequestingLayout = null; 19759 } 19760 } 19761 19762 /** 19763 * Forces this view to be laid out during the next layout pass. 19764 * This method does not call requestLayout() or forceLayout() 19765 * on the parent. 19766 */ 19767 public void forceLayout() { 19768 if (mMeasureCache != null) mMeasureCache.clear(); 19769 19770 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19771 mPrivateFlags |= PFLAG_INVALIDATED; 19772 } 19773 19774 /** 19775 * <p> 19776 * This is called to find out how big a view should be. The parent 19777 * supplies constraint information in the width and height parameters. 19778 * </p> 19779 * 19780 * <p> 19781 * The actual measurement work of a view is performed in 19782 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19783 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19784 * </p> 19785 * 19786 * 19787 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19788 * parent 19789 * @param heightMeasureSpec Vertical space requirements as imposed by the 19790 * parent 19791 * 19792 * @see #onMeasure(int, int) 19793 */ 19794 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19795 boolean optical = isLayoutModeOptical(this); 19796 if (optical != isLayoutModeOptical(mParent)) { 19797 Insets insets = getOpticalInsets(); 19798 int oWidth = insets.left + insets.right; 19799 int oHeight = insets.top + insets.bottom; 19800 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19801 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19802 } 19803 19804 // Suppress sign extension for the low bytes 19805 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19806 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19807 19808 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19809 19810 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19811 // already measured as the correct size. In API 23 and below, this 19812 // extra pass is required to make LinearLayout re-distribute weight. 19813 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19814 || heightMeasureSpec != mOldHeightMeasureSpec; 19815 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19816 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19817 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19818 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19819 final boolean needsLayout = specChanged 19820 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19821 19822 if (forceLayout || needsLayout) { 19823 // first clears the measured dimension flag 19824 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19825 19826 resolveRtlPropertiesIfNeeded(); 19827 19828 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19829 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19830 // measure ourselves, this should set the measured dimension flag back 19831 onMeasure(widthMeasureSpec, heightMeasureSpec); 19832 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19833 } else { 19834 long value = mMeasureCache.valueAt(cacheIndex); 19835 // Casting a long to int drops the high 32 bits, no mask needed 19836 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19837 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19838 } 19839 19840 // flag not set, setMeasuredDimension() was not invoked, we raise 19841 // an exception to warn the developer 19842 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19843 throw new IllegalStateException("View with id " + getId() + ": " 19844 + getClass().getName() + "#onMeasure() did not set the" 19845 + " measured dimension by calling" 19846 + " setMeasuredDimension()"); 19847 } 19848 19849 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19850 } 19851 19852 mOldWidthMeasureSpec = widthMeasureSpec; 19853 mOldHeightMeasureSpec = heightMeasureSpec; 19854 19855 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19856 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19857 } 19858 19859 /** 19860 * <p> 19861 * Measure the view and its content to determine the measured width and the 19862 * measured height. This method is invoked by {@link #measure(int, int)} and 19863 * should be overridden by subclasses to provide accurate and efficient 19864 * measurement of their contents. 19865 * </p> 19866 * 19867 * <p> 19868 * <strong>CONTRACT:</strong> When overriding this method, you 19869 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19870 * measured width and height of this view. Failure to do so will trigger an 19871 * <code>IllegalStateException</code>, thrown by 19872 * {@link #measure(int, int)}. Calling the superclass' 19873 * {@link #onMeasure(int, int)} is a valid use. 19874 * </p> 19875 * 19876 * <p> 19877 * The base class implementation of measure defaults to the background size, 19878 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19879 * override {@link #onMeasure(int, int)} to provide better measurements of 19880 * their content. 19881 * </p> 19882 * 19883 * <p> 19884 * If this method is overridden, it is the subclass's responsibility to make 19885 * sure the measured height and width are at least the view's minimum height 19886 * and width ({@link #getSuggestedMinimumHeight()} and 19887 * {@link #getSuggestedMinimumWidth()}). 19888 * </p> 19889 * 19890 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19891 * The requirements are encoded with 19892 * {@link android.view.View.MeasureSpec}. 19893 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19894 * The requirements are encoded with 19895 * {@link android.view.View.MeasureSpec}. 19896 * 19897 * @see #getMeasuredWidth() 19898 * @see #getMeasuredHeight() 19899 * @see #setMeasuredDimension(int, int) 19900 * @see #getSuggestedMinimumHeight() 19901 * @see #getSuggestedMinimumWidth() 19902 * @see android.view.View.MeasureSpec#getMode(int) 19903 * @see android.view.View.MeasureSpec#getSize(int) 19904 */ 19905 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19906 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19907 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19908 } 19909 19910 /** 19911 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19912 * measured width and measured height. Failing to do so will trigger an 19913 * exception at measurement time.</p> 19914 * 19915 * @param measuredWidth The measured width of this view. May be a complex 19916 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19917 * {@link #MEASURED_STATE_TOO_SMALL}. 19918 * @param measuredHeight The measured height of this view. May be a complex 19919 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19920 * {@link #MEASURED_STATE_TOO_SMALL}. 19921 */ 19922 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19923 boolean optical = isLayoutModeOptical(this); 19924 if (optical != isLayoutModeOptical(mParent)) { 19925 Insets insets = getOpticalInsets(); 19926 int opticalWidth = insets.left + insets.right; 19927 int opticalHeight = insets.top + insets.bottom; 19928 19929 measuredWidth += optical ? opticalWidth : -opticalWidth; 19930 measuredHeight += optical ? opticalHeight : -opticalHeight; 19931 } 19932 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19933 } 19934 19935 /** 19936 * Sets the measured dimension without extra processing for things like optical bounds. 19937 * Useful for reapplying consistent values that have already been cooked with adjustments 19938 * for optical bounds, etc. such as those from the measurement cache. 19939 * 19940 * @param measuredWidth The measured width of this view. May be a complex 19941 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19942 * {@link #MEASURED_STATE_TOO_SMALL}. 19943 * @param measuredHeight The measured height of this view. May be a complex 19944 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19945 * {@link #MEASURED_STATE_TOO_SMALL}. 19946 */ 19947 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19948 mMeasuredWidth = measuredWidth; 19949 mMeasuredHeight = measuredHeight; 19950 19951 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19952 } 19953 19954 /** 19955 * Merge two states as returned by {@link #getMeasuredState()}. 19956 * @param curState The current state as returned from a view or the result 19957 * of combining multiple views. 19958 * @param newState The new view state to combine. 19959 * @return Returns a new integer reflecting the combination of the two 19960 * states. 19961 */ 19962 public static int combineMeasuredStates(int curState, int newState) { 19963 return curState | newState; 19964 } 19965 19966 /** 19967 * Version of {@link #resolveSizeAndState(int, int, int)} 19968 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19969 */ 19970 public static int resolveSize(int size, int measureSpec) { 19971 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19972 } 19973 19974 /** 19975 * Utility to reconcile a desired size and state, with constraints imposed 19976 * by a MeasureSpec. Will take the desired size, unless a different size 19977 * is imposed by the constraints. The returned value is a compound integer, 19978 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19979 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19980 * resulting size is smaller than the size the view wants to be. 19981 * 19982 * @param size How big the view wants to be. 19983 * @param measureSpec Constraints imposed by the parent. 19984 * @param childMeasuredState Size information bit mask for the view's 19985 * children. 19986 * @return Size information bit mask as defined by 19987 * {@link #MEASURED_SIZE_MASK} and 19988 * {@link #MEASURED_STATE_TOO_SMALL}. 19989 */ 19990 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19991 final int specMode = MeasureSpec.getMode(measureSpec); 19992 final int specSize = MeasureSpec.getSize(measureSpec); 19993 final int result; 19994 switch (specMode) { 19995 case MeasureSpec.AT_MOST: 19996 if (specSize < size) { 19997 result = specSize | MEASURED_STATE_TOO_SMALL; 19998 } else { 19999 result = size; 20000 } 20001 break; 20002 case MeasureSpec.EXACTLY: 20003 result = specSize; 20004 break; 20005 case MeasureSpec.UNSPECIFIED: 20006 default: 20007 result = size; 20008 } 20009 return result | (childMeasuredState & MEASURED_STATE_MASK); 20010 } 20011 20012 /** 20013 * Utility to return a default size. Uses the supplied size if the 20014 * MeasureSpec imposed no constraints. Will get larger if allowed 20015 * by the MeasureSpec. 20016 * 20017 * @param size Default size for this view 20018 * @param measureSpec Constraints imposed by the parent 20019 * @return The size this view should be. 20020 */ 20021 public static int getDefaultSize(int size, int measureSpec) { 20022 int result = size; 20023 int specMode = MeasureSpec.getMode(measureSpec); 20024 int specSize = MeasureSpec.getSize(measureSpec); 20025 20026 switch (specMode) { 20027 case MeasureSpec.UNSPECIFIED: 20028 result = size; 20029 break; 20030 case MeasureSpec.AT_MOST: 20031 case MeasureSpec.EXACTLY: 20032 result = specSize; 20033 break; 20034 } 20035 return result; 20036 } 20037 20038 /** 20039 * Returns the suggested minimum height that the view should use. This 20040 * returns the maximum of the view's minimum height 20041 * and the background's minimum height 20042 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 20043 * <p> 20044 * When being used in {@link #onMeasure(int, int)}, the caller should still 20045 * ensure the returned height is within the requirements of the parent. 20046 * 20047 * @return The suggested minimum height of the view. 20048 */ 20049 protected int getSuggestedMinimumHeight() { 20050 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 20051 20052 } 20053 20054 /** 20055 * Returns the suggested minimum width that the view should use. This 20056 * returns the maximum of the view's minimum width 20057 * and the background's minimum width 20058 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 20059 * <p> 20060 * When being used in {@link #onMeasure(int, int)}, the caller should still 20061 * ensure the returned width is within the requirements of the parent. 20062 * 20063 * @return The suggested minimum width of the view. 20064 */ 20065 protected int getSuggestedMinimumWidth() { 20066 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 20067 } 20068 20069 /** 20070 * Returns the minimum height of the view. 20071 * 20072 * @return the minimum height the view will try to be, in pixels 20073 * 20074 * @see #setMinimumHeight(int) 20075 * 20076 * @attr ref android.R.styleable#View_minHeight 20077 */ 20078 public int getMinimumHeight() { 20079 return mMinHeight; 20080 } 20081 20082 /** 20083 * Sets the minimum height of the view. It is not guaranteed the view will 20084 * be able to achieve this minimum height (for example, if its parent layout 20085 * constrains it with less available height). 20086 * 20087 * @param minHeight The minimum height the view will try to be, in pixels 20088 * 20089 * @see #getMinimumHeight() 20090 * 20091 * @attr ref android.R.styleable#View_minHeight 20092 */ 20093 @RemotableViewMethod 20094 public void setMinimumHeight(int minHeight) { 20095 mMinHeight = minHeight; 20096 requestLayout(); 20097 } 20098 20099 /** 20100 * Returns the minimum width of the view. 20101 * 20102 * @return the minimum width the view will try to be, in pixels 20103 * 20104 * @see #setMinimumWidth(int) 20105 * 20106 * @attr ref android.R.styleable#View_minWidth 20107 */ 20108 public int getMinimumWidth() { 20109 return mMinWidth; 20110 } 20111 20112 /** 20113 * Sets the minimum width of the view. It is not guaranteed the view will 20114 * be able to achieve this minimum width (for example, if its parent layout 20115 * constrains it with less available width). 20116 * 20117 * @param minWidth The minimum width the view will try to be, in pixels 20118 * 20119 * @see #getMinimumWidth() 20120 * 20121 * @attr ref android.R.styleable#View_minWidth 20122 */ 20123 public void setMinimumWidth(int minWidth) { 20124 mMinWidth = minWidth; 20125 requestLayout(); 20126 20127 } 20128 20129 /** 20130 * Get the animation currently associated with this view. 20131 * 20132 * @return The animation that is currently playing or 20133 * scheduled to play for this view. 20134 */ 20135 public Animation getAnimation() { 20136 return mCurrentAnimation; 20137 } 20138 20139 /** 20140 * Start the specified animation now. 20141 * 20142 * @param animation the animation to start now 20143 */ 20144 public void startAnimation(Animation animation) { 20145 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20146 setAnimation(animation); 20147 invalidateParentCaches(); 20148 invalidate(true); 20149 } 20150 20151 /** 20152 * Cancels any animations for this view. 20153 */ 20154 public void clearAnimation() { 20155 if (mCurrentAnimation != null) { 20156 mCurrentAnimation.detach(); 20157 } 20158 mCurrentAnimation = null; 20159 invalidateParentIfNeeded(); 20160 } 20161 20162 /** 20163 * Sets the next animation to play for this view. 20164 * If you want the animation to play immediately, use 20165 * {@link #startAnimation(android.view.animation.Animation)} instead. 20166 * This method provides allows fine-grained 20167 * control over the start time and invalidation, but you 20168 * must make sure that 1) the animation has a start time set, and 20169 * 2) the view's parent (which controls animations on its children) 20170 * will be invalidated when the animation is supposed to 20171 * start. 20172 * 20173 * @param animation The next animation, or null. 20174 */ 20175 public void setAnimation(Animation animation) { 20176 mCurrentAnimation = animation; 20177 20178 if (animation != null) { 20179 // If the screen is off assume the animation start time is now instead of 20180 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20181 // would cause the animation to start when the screen turns back on 20182 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20183 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20184 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20185 } 20186 animation.reset(); 20187 } 20188 } 20189 20190 /** 20191 * Invoked by a parent ViewGroup to notify the start of the animation 20192 * currently associated with this view. If you override this method, 20193 * always call super.onAnimationStart(); 20194 * 20195 * @see #setAnimation(android.view.animation.Animation) 20196 * @see #getAnimation() 20197 */ 20198 @CallSuper 20199 protected void onAnimationStart() { 20200 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20201 } 20202 20203 /** 20204 * Invoked by a parent ViewGroup to notify the end of the animation 20205 * currently associated with this view. If you override this method, 20206 * always call super.onAnimationEnd(); 20207 * 20208 * @see #setAnimation(android.view.animation.Animation) 20209 * @see #getAnimation() 20210 */ 20211 @CallSuper 20212 protected void onAnimationEnd() { 20213 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20214 } 20215 20216 /** 20217 * Invoked if there is a Transform that involves alpha. Subclass that can 20218 * draw themselves with the specified alpha should return true, and then 20219 * respect that alpha when their onDraw() is called. If this returns false 20220 * then the view may be redirected to draw into an offscreen buffer to 20221 * fulfill the request, which will look fine, but may be slower than if the 20222 * subclass handles it internally. The default implementation returns false. 20223 * 20224 * @param alpha The alpha (0..255) to apply to the view's drawing 20225 * @return true if the view can draw with the specified alpha. 20226 */ 20227 protected boolean onSetAlpha(int alpha) { 20228 return false; 20229 } 20230 20231 /** 20232 * This is used by the RootView to perform an optimization when 20233 * the view hierarchy contains one or several SurfaceView. 20234 * SurfaceView is always considered transparent, but its children are not, 20235 * therefore all View objects remove themselves from the global transparent 20236 * region (passed as a parameter to this function). 20237 * 20238 * @param region The transparent region for this ViewAncestor (window). 20239 * 20240 * @return Returns true if the effective visibility of the view at this 20241 * point is opaque, regardless of the transparent region; returns false 20242 * if it is possible for underlying windows to be seen behind the view. 20243 * 20244 * {@hide} 20245 */ 20246 public boolean gatherTransparentRegion(Region region) { 20247 final AttachInfo attachInfo = mAttachInfo; 20248 if (region != null && attachInfo != null) { 20249 final int pflags = mPrivateFlags; 20250 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20251 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20252 // remove it from the transparent region. 20253 final int[] location = attachInfo.mTransparentLocation; 20254 getLocationInWindow(location); 20255 // When a view has Z value, then it will be better to leave some area below the view 20256 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 20257 // the bottom part needs more offset than the left, top and right parts due to the 20258 // spot light effects. 20259 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 20260 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 20261 location[0] + mRight - mLeft + shadowOffset, 20262 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 20263 } else { 20264 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20265 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20266 // the background drawable's non-transparent parts from this transparent region. 20267 applyDrawableToTransparentRegion(mBackground, region); 20268 } 20269 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20270 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20271 // Similarly, we remove the foreground drawable's non-transparent parts. 20272 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20273 } 20274 } 20275 } 20276 return true; 20277 } 20278 20279 /** 20280 * Play a sound effect for this view. 20281 * 20282 * <p>The framework will play sound effects for some built in actions, such as 20283 * clicking, but you may wish to play these effects in your widget, 20284 * for instance, for internal navigation. 20285 * 20286 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20287 * {@link #isSoundEffectsEnabled()} is true. 20288 * 20289 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20290 */ 20291 public void playSoundEffect(int soundConstant) { 20292 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20293 return; 20294 } 20295 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20296 } 20297 20298 /** 20299 * BZZZTT!!1! 20300 * 20301 * <p>Provide haptic feedback to the user for this view. 20302 * 20303 * <p>The framework will provide haptic feedback for some built in actions, 20304 * such as long presses, but you may wish to provide feedback for your 20305 * own widget. 20306 * 20307 * <p>The feedback will only be performed if 20308 * {@link #isHapticFeedbackEnabled()} is true. 20309 * 20310 * @param feedbackConstant One of the constants defined in 20311 * {@link HapticFeedbackConstants} 20312 */ 20313 public boolean performHapticFeedback(int feedbackConstant) { 20314 return performHapticFeedback(feedbackConstant, 0); 20315 } 20316 20317 /** 20318 * BZZZTT!!1! 20319 * 20320 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20321 * 20322 * @param feedbackConstant One of the constants defined in 20323 * {@link HapticFeedbackConstants} 20324 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20325 */ 20326 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20327 if (mAttachInfo == null) { 20328 return false; 20329 } 20330 //noinspection SimplifiableIfStatement 20331 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20332 && !isHapticFeedbackEnabled()) { 20333 return false; 20334 } 20335 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20336 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20337 } 20338 20339 /** 20340 * Request that the visibility of the status bar or other screen/window 20341 * decorations be changed. 20342 * 20343 * <p>This method is used to put the over device UI into temporary modes 20344 * where the user's attention is focused more on the application content, 20345 * by dimming or hiding surrounding system affordances. This is typically 20346 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20347 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20348 * to be placed behind the action bar (and with these flags other system 20349 * affordances) so that smooth transitions between hiding and showing them 20350 * can be done. 20351 * 20352 * <p>Two representative examples of the use of system UI visibility is 20353 * implementing a content browsing application (like a magazine reader) 20354 * and a video playing application. 20355 * 20356 * <p>The first code shows a typical implementation of a View in a content 20357 * browsing application. In this implementation, the application goes 20358 * into a content-oriented mode by hiding the status bar and action bar, 20359 * and putting the navigation elements into lights out mode. The user can 20360 * then interact with content while in this mode. Such an application should 20361 * provide an easy way for the user to toggle out of the mode (such as to 20362 * check information in the status bar or access notifications). In the 20363 * implementation here, this is done simply by tapping on the content. 20364 * 20365 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20366 * content} 20367 * 20368 * <p>This second code sample shows a typical implementation of a View 20369 * in a video playing application. In this situation, while the video is 20370 * playing the application would like to go into a complete full-screen mode, 20371 * to use as much of the display as possible for the video. When in this state 20372 * the user can not interact with the application; the system intercepts 20373 * touching on the screen to pop the UI out of full screen mode. See 20374 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20375 * 20376 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20377 * content} 20378 * 20379 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20380 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20381 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20382 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20383 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20384 */ 20385 public void setSystemUiVisibility(int visibility) { 20386 if (visibility != mSystemUiVisibility) { 20387 mSystemUiVisibility = visibility; 20388 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20389 mParent.recomputeViewAttributes(this); 20390 } 20391 } 20392 } 20393 20394 /** 20395 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20396 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20397 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20398 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20399 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20400 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20401 */ 20402 public int getSystemUiVisibility() { 20403 return mSystemUiVisibility; 20404 } 20405 20406 /** 20407 * Returns the current system UI visibility that is currently set for 20408 * the entire window. This is the combination of the 20409 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20410 * views in the window. 20411 */ 20412 public int getWindowSystemUiVisibility() { 20413 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20414 } 20415 20416 /** 20417 * Override to find out when the window's requested system UI visibility 20418 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20419 * This is different from the callbacks received through 20420 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20421 * in that this is only telling you about the local request of the window, 20422 * not the actual values applied by the system. 20423 */ 20424 public void onWindowSystemUiVisibilityChanged(int visible) { 20425 } 20426 20427 /** 20428 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20429 * the view hierarchy. 20430 */ 20431 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20432 onWindowSystemUiVisibilityChanged(visible); 20433 } 20434 20435 /** 20436 * Set a listener to receive callbacks when the visibility of the system bar changes. 20437 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20438 */ 20439 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20440 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20441 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20442 mParent.recomputeViewAttributes(this); 20443 } 20444 } 20445 20446 /** 20447 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20448 * the view hierarchy. 20449 */ 20450 public void dispatchSystemUiVisibilityChanged(int visibility) { 20451 ListenerInfo li = mListenerInfo; 20452 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20453 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20454 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20455 } 20456 } 20457 20458 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20459 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20460 if (val != mSystemUiVisibility) { 20461 setSystemUiVisibility(val); 20462 return true; 20463 } 20464 return false; 20465 } 20466 20467 /** @hide */ 20468 public void setDisabledSystemUiVisibility(int flags) { 20469 if (mAttachInfo != null) { 20470 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20471 mAttachInfo.mDisabledSystemUiVisibility = flags; 20472 if (mParent != null) { 20473 mParent.recomputeViewAttributes(this); 20474 } 20475 } 20476 } 20477 } 20478 20479 /** 20480 * Creates an image that the system displays during the drag and drop 20481 * operation. This is called a "drag shadow". The default implementation 20482 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20483 * appearance as the given View. The default also positions the center of the drag shadow 20484 * directly under the touch point. If no View is provided (the constructor with no parameters 20485 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20486 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20487 * default is an invisible drag shadow. 20488 * <p> 20489 * You are not required to use the View you provide to the constructor as the basis of the 20490 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20491 * anything you want as the drag shadow. 20492 * </p> 20493 * <p> 20494 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20495 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20496 * size and position of the drag shadow. It uses this data to construct a 20497 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20498 * so that your application can draw the shadow image in the Canvas. 20499 * </p> 20500 * 20501 * <div class="special reference"> 20502 * <h3>Developer Guides</h3> 20503 * <p>For a guide to implementing drag and drop features, read the 20504 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20505 * </div> 20506 */ 20507 public static class DragShadowBuilder { 20508 private final WeakReference<View> mView; 20509 20510 /** 20511 * Constructs a shadow image builder based on a View. By default, the resulting drag 20512 * shadow will have the same appearance and dimensions as the View, with the touch point 20513 * over the center of the View. 20514 * @param view A View. Any View in scope can be used. 20515 */ 20516 public DragShadowBuilder(View view) { 20517 mView = new WeakReference<View>(view); 20518 } 20519 20520 /** 20521 * Construct a shadow builder object with no associated View. This 20522 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20523 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20524 * to supply the drag shadow's dimensions and appearance without 20525 * reference to any View object. If they are not overridden, then the result is an 20526 * invisible drag shadow. 20527 */ 20528 public DragShadowBuilder() { 20529 mView = new WeakReference<View>(null); 20530 } 20531 20532 /** 20533 * Returns the View object that had been passed to the 20534 * {@link #View.DragShadowBuilder(View)} 20535 * constructor. If that View parameter was {@code null} or if the 20536 * {@link #View.DragShadowBuilder()} 20537 * constructor was used to instantiate the builder object, this method will return 20538 * null. 20539 * 20540 * @return The View object associate with this builder object. 20541 */ 20542 @SuppressWarnings({"JavadocReference"}) 20543 final public View getView() { 20544 return mView.get(); 20545 } 20546 20547 /** 20548 * Provides the metrics for the shadow image. These include the dimensions of 20549 * the shadow image, and the point within that shadow that should 20550 * be centered under the touch location while dragging. 20551 * <p> 20552 * The default implementation sets the dimensions of the shadow to be the 20553 * same as the dimensions of the View itself and centers the shadow under 20554 * the touch point. 20555 * </p> 20556 * 20557 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20558 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20559 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20560 * image. 20561 * 20562 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20563 * shadow image that should be underneath the touch point during the drag and drop 20564 * operation. Your application must set {@link android.graphics.Point#x} to the 20565 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20566 */ 20567 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20568 final View view = mView.get(); 20569 if (view != null) { 20570 outShadowSize.set(view.getWidth(), view.getHeight()); 20571 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20572 } else { 20573 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20574 } 20575 } 20576 20577 /** 20578 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20579 * based on the dimensions it received from the 20580 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20581 * 20582 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20583 */ 20584 public void onDrawShadow(Canvas canvas) { 20585 final View view = mView.get(); 20586 if (view != null) { 20587 view.draw(canvas); 20588 } else { 20589 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20590 } 20591 } 20592 } 20593 20594 /** 20595 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20596 * startDragAndDrop()} for newer platform versions. 20597 */ 20598 @Deprecated 20599 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20600 Object myLocalState, int flags) { 20601 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20602 } 20603 20604 /** 20605 * Starts a drag and drop operation. When your application calls this method, it passes a 20606 * {@link android.view.View.DragShadowBuilder} object to the system. The 20607 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20608 * to get metrics for the drag shadow, and then calls the object's 20609 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20610 * <p> 20611 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20612 * drag events to all the View objects in your application that are currently visible. It does 20613 * this either by calling the View object's drag listener (an implementation of 20614 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20615 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20616 * Both are passed a {@link android.view.DragEvent} object that has a 20617 * {@link android.view.DragEvent#getAction()} value of 20618 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20619 * </p> 20620 * <p> 20621 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20622 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20623 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20624 * to the View the user selected for dragging. 20625 * </p> 20626 * @param data A {@link android.content.ClipData} object pointing to the data to be 20627 * transferred by the drag and drop operation. 20628 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20629 * drag shadow. 20630 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20631 * drop operation. When dispatching drag events to views in the same activity this object 20632 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 20633 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 20634 * will return null). 20635 * <p> 20636 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20637 * to the target Views. For example, it can contain flags that differentiate between a 20638 * a copy operation and a move operation. 20639 * </p> 20640 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 20641 * flags, or any combination of the following: 20642 * <ul> 20643 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 20644 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 20645 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 20646 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 20647 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 20648 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 20649 * </ul> 20650 * @return {@code true} if the method completes successfully, or 20651 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20652 * do a drag, and so no drag operation is in progress. 20653 */ 20654 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20655 Object myLocalState, int flags) { 20656 if (ViewDebug.DEBUG_DRAG) { 20657 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20658 } 20659 if (mAttachInfo == null) { 20660 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 20661 return false; 20662 } 20663 20664 if (data != null) { 20665 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 20666 } 20667 20668 boolean okay = false; 20669 20670 Point shadowSize = new Point(); 20671 Point shadowTouchPoint = new Point(); 20672 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20673 20674 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20675 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20676 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20677 } 20678 20679 if (ViewDebug.DEBUG_DRAG) { 20680 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20681 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20682 } 20683 if (mAttachInfo.mDragSurface != null) { 20684 mAttachInfo.mDragSurface.release(); 20685 } 20686 mAttachInfo.mDragSurface = new Surface(); 20687 try { 20688 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20689 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20690 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20691 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20692 if (mAttachInfo.mDragToken != null) { 20693 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20694 try { 20695 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20696 shadowBuilder.onDrawShadow(canvas); 20697 } finally { 20698 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20699 } 20700 20701 final ViewRootImpl root = getViewRootImpl(); 20702 20703 // Cache the local state object for delivery with DragEvents 20704 root.setLocalDragState(myLocalState); 20705 20706 // repurpose 'shadowSize' for the last touch point 20707 root.getLastTouchPoint(shadowSize); 20708 20709 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20710 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20711 shadowTouchPoint.x, shadowTouchPoint.y, data); 20712 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20713 } 20714 } catch (Exception e) { 20715 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20716 mAttachInfo.mDragSurface.destroy(); 20717 mAttachInfo.mDragSurface = null; 20718 } 20719 20720 return okay; 20721 } 20722 20723 /** 20724 * Cancels an ongoing drag and drop operation. 20725 * <p> 20726 * A {@link android.view.DragEvent} object with 20727 * {@link android.view.DragEvent#getAction()} value of 20728 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20729 * {@link android.view.DragEvent#getResult()} value of {@code false} 20730 * will be sent to every 20731 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20732 * even if they are not currently visible. 20733 * </p> 20734 * <p> 20735 * This method can be called on any View in the same window as the View on which 20736 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20737 * was called. 20738 * </p> 20739 */ 20740 public final void cancelDragAndDrop() { 20741 if (ViewDebug.DEBUG_DRAG) { 20742 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20743 } 20744 if (mAttachInfo == null) { 20745 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 20746 return; 20747 } 20748 if (mAttachInfo.mDragToken != null) { 20749 try { 20750 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20751 } catch (Exception e) { 20752 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20753 } 20754 mAttachInfo.mDragToken = null; 20755 } else { 20756 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20757 } 20758 } 20759 20760 /** 20761 * Updates the drag shadow for the ongoing drag and drop operation. 20762 * 20763 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20764 * new drag shadow. 20765 */ 20766 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20767 if (ViewDebug.DEBUG_DRAG) { 20768 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20769 } 20770 if (mAttachInfo == null) { 20771 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 20772 return; 20773 } 20774 if (mAttachInfo.mDragToken != null) { 20775 try { 20776 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20777 try { 20778 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20779 shadowBuilder.onDrawShadow(canvas); 20780 } finally { 20781 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20782 } 20783 } catch (Exception e) { 20784 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20785 } 20786 } else { 20787 Log.e(VIEW_LOG_TAG, "No active drag"); 20788 } 20789 } 20790 20791 /** 20792 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20793 * between {startX, startY} and the new cursor positon. 20794 * @param startX horizontal coordinate where the move started. 20795 * @param startY vertical coordinate where the move started. 20796 * @return whether moving was started successfully. 20797 * @hide 20798 */ 20799 public final boolean startMovingTask(float startX, float startY) { 20800 if (ViewDebug.DEBUG_POSITIONING) { 20801 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20802 } 20803 try { 20804 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20805 } catch (RemoteException e) { 20806 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20807 } 20808 return false; 20809 } 20810 20811 /** 20812 * Handles drag events sent by the system following a call to 20813 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20814 * startDragAndDrop()}. 20815 *<p> 20816 * When the system calls this method, it passes a 20817 * {@link android.view.DragEvent} object. A call to 20818 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20819 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20820 * operation. 20821 * @param event The {@link android.view.DragEvent} sent by the system. 20822 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20823 * in DragEvent, indicating the type of drag event represented by this object. 20824 * @return {@code true} if the method was successful, otherwise {@code false}. 20825 * <p> 20826 * The method should return {@code true} in response to an action type of 20827 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20828 * operation. 20829 * </p> 20830 * <p> 20831 * The method should also return {@code true} in response to an action type of 20832 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20833 * {@code false} if it didn't. 20834 * </p> 20835 * <p> 20836 * For all other events, the return value is ignored. 20837 * </p> 20838 */ 20839 public boolean onDragEvent(DragEvent event) { 20840 return false; 20841 } 20842 20843 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 20844 boolean dispatchDragEnterExitInPreN(DragEvent event) { 20845 return callDragEventHandler(event); 20846 } 20847 20848 /** 20849 * Detects if this View is enabled and has a drag event listener. 20850 * If both are true, then it calls the drag event listener with the 20851 * {@link android.view.DragEvent} it received. If the drag event listener returns 20852 * {@code true}, then dispatchDragEvent() returns {@code true}. 20853 * <p> 20854 * For all other cases, the method calls the 20855 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20856 * method and returns its result. 20857 * </p> 20858 * <p> 20859 * This ensures that a drag event is always consumed, even if the View does not have a drag 20860 * event listener. However, if the View has a listener and the listener returns true, then 20861 * onDragEvent() is not called. 20862 * </p> 20863 */ 20864 public boolean dispatchDragEvent(DragEvent event) { 20865 event.mEventHandlerWasCalled = true; 20866 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 20867 event.mAction == DragEvent.ACTION_DROP) { 20868 // About to deliver an event with coordinates to this view. Notify that now this view 20869 // has drag focus. This will send exit/enter events as needed. 20870 getViewRootImpl().setDragFocus(this, event); 20871 } 20872 return callDragEventHandler(event); 20873 } 20874 20875 final boolean callDragEventHandler(DragEvent event) { 20876 final boolean result; 20877 20878 ListenerInfo li = mListenerInfo; 20879 //noinspection SimplifiableIfStatement 20880 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20881 && li.mOnDragListener.onDrag(this, event)) { 20882 result = true; 20883 } else { 20884 result = onDragEvent(event); 20885 } 20886 20887 switch (event.mAction) { 20888 case DragEvent.ACTION_DRAG_ENTERED: { 20889 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 20890 refreshDrawableState(); 20891 } break; 20892 case DragEvent.ACTION_DRAG_EXITED: { 20893 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 20894 refreshDrawableState(); 20895 } break; 20896 case DragEvent.ACTION_DRAG_ENDED: { 20897 mPrivateFlags2 &= ~View.DRAG_MASK; 20898 refreshDrawableState(); 20899 } break; 20900 } 20901 20902 return result; 20903 } 20904 20905 boolean canAcceptDrag() { 20906 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20907 } 20908 20909 /** 20910 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20911 * it is ever exposed at all. 20912 * @hide 20913 */ 20914 public void onCloseSystemDialogs(String reason) { 20915 } 20916 20917 /** 20918 * Given a Drawable whose bounds have been set to draw into this view, 20919 * update a Region being computed for 20920 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20921 * that any non-transparent parts of the Drawable are removed from the 20922 * given transparent region. 20923 * 20924 * @param dr The Drawable whose transparency is to be applied to the region. 20925 * @param region A Region holding the current transparency information, 20926 * where any parts of the region that are set are considered to be 20927 * transparent. On return, this region will be modified to have the 20928 * transparency information reduced by the corresponding parts of the 20929 * Drawable that are not transparent. 20930 * {@hide} 20931 */ 20932 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20933 if (DBG) { 20934 Log.i("View", "Getting transparent region for: " + this); 20935 } 20936 final Region r = dr.getTransparentRegion(); 20937 final Rect db = dr.getBounds(); 20938 final AttachInfo attachInfo = mAttachInfo; 20939 if (r != null && attachInfo != null) { 20940 final int w = getRight()-getLeft(); 20941 final int h = getBottom()-getTop(); 20942 if (db.left > 0) { 20943 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20944 r.op(0, 0, db.left, h, Region.Op.UNION); 20945 } 20946 if (db.right < w) { 20947 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20948 r.op(db.right, 0, w, h, Region.Op.UNION); 20949 } 20950 if (db.top > 0) { 20951 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20952 r.op(0, 0, w, db.top, Region.Op.UNION); 20953 } 20954 if (db.bottom < h) { 20955 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20956 r.op(0, db.bottom, w, h, Region.Op.UNION); 20957 } 20958 final int[] location = attachInfo.mTransparentLocation; 20959 getLocationInWindow(location); 20960 r.translate(location[0], location[1]); 20961 region.op(r, Region.Op.INTERSECT); 20962 } else { 20963 region.op(db, Region.Op.DIFFERENCE); 20964 } 20965 } 20966 20967 private void checkForLongClick(int delayOffset, float x, float y) { 20968 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20969 mHasPerformedLongPress = false; 20970 20971 if (mPendingCheckForLongPress == null) { 20972 mPendingCheckForLongPress = new CheckForLongPress(); 20973 } 20974 mPendingCheckForLongPress.setAnchor(x, y); 20975 mPendingCheckForLongPress.rememberWindowAttachCount(); 20976 postDelayed(mPendingCheckForLongPress, 20977 ViewConfiguration.getLongPressTimeout() - delayOffset); 20978 } 20979 } 20980 20981 /** 20982 * Inflate a view from an XML resource. This convenience method wraps the {@link 20983 * LayoutInflater} class, which provides a full range of options for view inflation. 20984 * 20985 * @param context The Context object for your activity or application. 20986 * @param resource The resource ID to inflate 20987 * @param root A view group that will be the parent. Used to properly inflate the 20988 * layout_* parameters. 20989 * @see LayoutInflater 20990 */ 20991 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20992 LayoutInflater factory = LayoutInflater.from(context); 20993 return factory.inflate(resource, root); 20994 } 20995 20996 /** 20997 * Scroll the view with standard behavior for scrolling beyond the normal 20998 * content boundaries. Views that call this method should override 20999 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 21000 * results of an over-scroll operation. 21001 * 21002 * Views can use this method to handle any touch or fling-based scrolling. 21003 * 21004 * @param deltaX Change in X in pixels 21005 * @param deltaY Change in Y in pixels 21006 * @param scrollX Current X scroll value in pixels before applying deltaX 21007 * @param scrollY Current Y scroll value in pixels before applying deltaY 21008 * @param scrollRangeX Maximum content scroll range along the X axis 21009 * @param scrollRangeY Maximum content scroll range along the Y axis 21010 * @param maxOverScrollX Number of pixels to overscroll by in either direction 21011 * along the X axis. 21012 * @param maxOverScrollY Number of pixels to overscroll by in either direction 21013 * along the Y axis. 21014 * @param isTouchEvent true if this scroll operation is the result of a touch event. 21015 * @return true if scrolling was clamped to an over-scroll boundary along either 21016 * axis, false otherwise. 21017 */ 21018 @SuppressWarnings({"UnusedParameters"}) 21019 protected boolean overScrollBy(int deltaX, int deltaY, 21020 int scrollX, int scrollY, 21021 int scrollRangeX, int scrollRangeY, 21022 int maxOverScrollX, int maxOverScrollY, 21023 boolean isTouchEvent) { 21024 final int overScrollMode = mOverScrollMode; 21025 final boolean canScrollHorizontal = 21026 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 21027 final boolean canScrollVertical = 21028 computeVerticalScrollRange() > computeVerticalScrollExtent(); 21029 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 21030 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 21031 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 21032 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 21033 21034 int newScrollX = scrollX + deltaX; 21035 if (!overScrollHorizontal) { 21036 maxOverScrollX = 0; 21037 } 21038 21039 int newScrollY = scrollY + deltaY; 21040 if (!overScrollVertical) { 21041 maxOverScrollY = 0; 21042 } 21043 21044 // Clamp values if at the limits and record 21045 final int left = -maxOverScrollX; 21046 final int right = maxOverScrollX + scrollRangeX; 21047 final int top = -maxOverScrollY; 21048 final int bottom = maxOverScrollY + scrollRangeY; 21049 21050 boolean clampedX = false; 21051 if (newScrollX > right) { 21052 newScrollX = right; 21053 clampedX = true; 21054 } else if (newScrollX < left) { 21055 newScrollX = left; 21056 clampedX = true; 21057 } 21058 21059 boolean clampedY = false; 21060 if (newScrollY > bottom) { 21061 newScrollY = bottom; 21062 clampedY = true; 21063 } else if (newScrollY < top) { 21064 newScrollY = top; 21065 clampedY = true; 21066 } 21067 21068 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 21069 21070 return clampedX || clampedY; 21071 } 21072 21073 /** 21074 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 21075 * respond to the results of an over-scroll operation. 21076 * 21077 * @param scrollX New X scroll value in pixels 21078 * @param scrollY New Y scroll value in pixels 21079 * @param clampedX True if scrollX was clamped to an over-scroll boundary 21080 * @param clampedY True if scrollY was clamped to an over-scroll boundary 21081 */ 21082 protected void onOverScrolled(int scrollX, int scrollY, 21083 boolean clampedX, boolean clampedY) { 21084 // Intentionally empty. 21085 } 21086 21087 /** 21088 * Returns the over-scroll mode for this view. The result will be 21089 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21090 * (allow over-scrolling only if the view content is larger than the container), 21091 * or {@link #OVER_SCROLL_NEVER}. 21092 * 21093 * @return This view's over-scroll mode. 21094 */ 21095 public int getOverScrollMode() { 21096 return mOverScrollMode; 21097 } 21098 21099 /** 21100 * Set the over-scroll mode for this view. Valid over-scroll modes are 21101 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21102 * (allow over-scrolling only if the view content is larger than the container), 21103 * or {@link #OVER_SCROLL_NEVER}. 21104 * 21105 * Setting the over-scroll mode of a view will have an effect only if the 21106 * view is capable of scrolling. 21107 * 21108 * @param overScrollMode The new over-scroll mode for this view. 21109 */ 21110 public void setOverScrollMode(int overScrollMode) { 21111 if (overScrollMode != OVER_SCROLL_ALWAYS && 21112 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 21113 overScrollMode != OVER_SCROLL_NEVER) { 21114 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 21115 } 21116 mOverScrollMode = overScrollMode; 21117 } 21118 21119 /** 21120 * Enable or disable nested scrolling for this view. 21121 * 21122 * <p>If this property is set to true the view will be permitted to initiate nested 21123 * scrolling operations with a compatible parent view in the current hierarchy. If this 21124 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 21125 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 21126 * the nested scroll.</p> 21127 * 21128 * @param enabled true to enable nested scrolling, false to disable 21129 * 21130 * @see #isNestedScrollingEnabled() 21131 */ 21132 public void setNestedScrollingEnabled(boolean enabled) { 21133 if (enabled) { 21134 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 21135 } else { 21136 stopNestedScroll(); 21137 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 21138 } 21139 } 21140 21141 /** 21142 * Returns true if nested scrolling is enabled for this view. 21143 * 21144 * <p>If nested scrolling is enabled and this View class implementation supports it, 21145 * this view will act as a nested scrolling child view when applicable, forwarding data 21146 * about the scroll operation in progress to a compatible and cooperating nested scrolling 21147 * parent.</p> 21148 * 21149 * @return true if nested scrolling is enabled 21150 * 21151 * @see #setNestedScrollingEnabled(boolean) 21152 */ 21153 public boolean isNestedScrollingEnabled() { 21154 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 21155 PFLAG3_NESTED_SCROLLING_ENABLED; 21156 } 21157 21158 /** 21159 * Begin a nestable scroll operation along the given axes. 21160 * 21161 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 21162 * 21163 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 21164 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 21165 * In the case of touch scrolling the nested scroll will be terminated automatically in 21166 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 21167 * In the event of programmatic scrolling the caller must explicitly call 21168 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 21169 * 21170 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21171 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21172 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21173 * 21174 * <p>At each incremental step of the scroll the caller should invoke 21175 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21176 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21177 * parent at least partially consumed the scroll and the caller should adjust the amount it 21178 * scrolls by.</p> 21179 * 21180 * <p>After applying the remainder of the scroll delta the caller should invoke 21181 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21182 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21183 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21184 * </p> 21185 * 21186 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21187 * {@link #SCROLL_AXIS_VERTICAL}. 21188 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21189 * the current gesture. 21190 * 21191 * @see #stopNestedScroll() 21192 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21193 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21194 */ 21195 public boolean startNestedScroll(int axes) { 21196 if (hasNestedScrollingParent()) { 21197 // Already in progress 21198 return true; 21199 } 21200 if (isNestedScrollingEnabled()) { 21201 ViewParent p = getParent(); 21202 View child = this; 21203 while (p != null) { 21204 try { 21205 if (p.onStartNestedScroll(child, this, axes)) { 21206 mNestedScrollingParent = p; 21207 p.onNestedScrollAccepted(child, this, axes); 21208 return true; 21209 } 21210 } catch (AbstractMethodError e) { 21211 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21212 "method onStartNestedScroll", e); 21213 // Allow the search upward to continue 21214 } 21215 if (p instanceof View) { 21216 child = (View) p; 21217 } 21218 p = p.getParent(); 21219 } 21220 } 21221 return false; 21222 } 21223 21224 /** 21225 * Stop a nested scroll in progress. 21226 * 21227 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21228 * 21229 * @see #startNestedScroll(int) 21230 */ 21231 public void stopNestedScroll() { 21232 if (mNestedScrollingParent != null) { 21233 mNestedScrollingParent.onStopNestedScroll(this); 21234 mNestedScrollingParent = null; 21235 } 21236 } 21237 21238 /** 21239 * Returns true if this view has a nested scrolling parent. 21240 * 21241 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21242 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21243 * 21244 * @return whether this view has a nested scrolling parent 21245 */ 21246 public boolean hasNestedScrollingParent() { 21247 return mNestedScrollingParent != null; 21248 } 21249 21250 /** 21251 * Dispatch one step of a nested scroll in progress. 21252 * 21253 * <p>Implementations of views that support nested scrolling should call this to report 21254 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21255 * is not currently in progress or nested scrolling is not 21256 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21257 * 21258 * <p>Compatible View implementations should also call 21259 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21260 * consuming a component of the scroll event themselves.</p> 21261 * 21262 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21263 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21264 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21265 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21266 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21267 * in local view coordinates of this view from before this operation 21268 * to after it completes. View implementations may use this to adjust 21269 * expected input coordinate tracking. 21270 * @return true if the event was dispatched, false if it could not be dispatched. 21271 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21272 */ 21273 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21274 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21275 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21276 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21277 int startX = 0; 21278 int startY = 0; 21279 if (offsetInWindow != null) { 21280 getLocationInWindow(offsetInWindow); 21281 startX = offsetInWindow[0]; 21282 startY = offsetInWindow[1]; 21283 } 21284 21285 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21286 dxUnconsumed, dyUnconsumed); 21287 21288 if (offsetInWindow != null) { 21289 getLocationInWindow(offsetInWindow); 21290 offsetInWindow[0] -= startX; 21291 offsetInWindow[1] -= startY; 21292 } 21293 return true; 21294 } else if (offsetInWindow != null) { 21295 // No motion, no dispatch. Keep offsetInWindow up to date. 21296 offsetInWindow[0] = 0; 21297 offsetInWindow[1] = 0; 21298 } 21299 } 21300 return false; 21301 } 21302 21303 /** 21304 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21305 * 21306 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21307 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21308 * scrolling operation to consume some or all of the scroll operation before the child view 21309 * consumes it.</p> 21310 * 21311 * @param dx Horizontal scroll distance in pixels 21312 * @param dy Vertical scroll distance in pixels 21313 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21314 * and consumed[1] the consumed dy. 21315 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21316 * in local view coordinates of this view from before this operation 21317 * to after it completes. View implementations may use this to adjust 21318 * expected input coordinate tracking. 21319 * @return true if the parent consumed some or all of the scroll delta 21320 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21321 */ 21322 public boolean dispatchNestedPreScroll(int dx, int dy, 21323 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21324 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21325 if (dx != 0 || dy != 0) { 21326 int startX = 0; 21327 int startY = 0; 21328 if (offsetInWindow != null) { 21329 getLocationInWindow(offsetInWindow); 21330 startX = offsetInWindow[0]; 21331 startY = offsetInWindow[1]; 21332 } 21333 21334 if (consumed == null) { 21335 if (mTempNestedScrollConsumed == null) { 21336 mTempNestedScrollConsumed = new int[2]; 21337 } 21338 consumed = mTempNestedScrollConsumed; 21339 } 21340 consumed[0] = 0; 21341 consumed[1] = 0; 21342 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21343 21344 if (offsetInWindow != null) { 21345 getLocationInWindow(offsetInWindow); 21346 offsetInWindow[0] -= startX; 21347 offsetInWindow[1] -= startY; 21348 } 21349 return consumed[0] != 0 || consumed[1] != 0; 21350 } else if (offsetInWindow != null) { 21351 offsetInWindow[0] = 0; 21352 offsetInWindow[1] = 0; 21353 } 21354 } 21355 return false; 21356 } 21357 21358 /** 21359 * Dispatch a fling to a nested scrolling parent. 21360 * 21361 * <p>This method should be used to indicate that a nested scrolling child has detected 21362 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21363 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21364 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21365 * along a scrollable axis.</p> 21366 * 21367 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21368 * its own content, it can use this method to delegate the fling to its nested scrolling 21369 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21370 * 21371 * @param velocityX Horizontal fling velocity in pixels per second 21372 * @param velocityY Vertical fling velocity in pixels per second 21373 * @param consumed true if the child consumed the fling, false otherwise 21374 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21375 */ 21376 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21377 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21378 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21379 } 21380 return false; 21381 } 21382 21383 /** 21384 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21385 * 21386 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21387 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21388 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21389 * before the child view consumes it. If this method returns <code>true</code>, a nested 21390 * parent view consumed the fling and this view should not scroll as a result.</p> 21391 * 21392 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21393 * the fling at a time. If a parent view consumed the fling this method will return false. 21394 * Custom view implementations should account for this in two ways:</p> 21395 * 21396 * <ul> 21397 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21398 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21399 * position regardless.</li> 21400 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21401 * even to settle back to a valid idle position.</li> 21402 * </ul> 21403 * 21404 * <p>Views should also not offer fling velocities to nested parent views along an axis 21405 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21406 * should not offer a horizontal fling velocity to its parents since scrolling along that 21407 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21408 * 21409 * @param velocityX Horizontal fling velocity in pixels per second 21410 * @param velocityY Vertical fling velocity in pixels per second 21411 * @return true if a nested scrolling parent consumed the fling 21412 */ 21413 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21414 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21415 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21416 } 21417 return false; 21418 } 21419 21420 /** 21421 * Gets a scale factor that determines the distance the view should scroll 21422 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21423 * @return The vertical scroll scale factor. 21424 * @hide 21425 */ 21426 protected float getVerticalScrollFactor() { 21427 if (mVerticalScrollFactor == 0) { 21428 TypedValue outValue = new TypedValue(); 21429 if (!mContext.getTheme().resolveAttribute( 21430 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21431 throw new IllegalStateException( 21432 "Expected theme to define listPreferredItemHeight."); 21433 } 21434 mVerticalScrollFactor = outValue.getDimension( 21435 mContext.getResources().getDisplayMetrics()); 21436 } 21437 return mVerticalScrollFactor; 21438 } 21439 21440 /** 21441 * Gets a scale factor that determines the distance the view should scroll 21442 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21443 * @return The horizontal scroll scale factor. 21444 * @hide 21445 */ 21446 protected float getHorizontalScrollFactor() { 21447 // TODO: Should use something else. 21448 return getVerticalScrollFactor(); 21449 } 21450 21451 /** 21452 * Return the value specifying the text direction or policy that was set with 21453 * {@link #setTextDirection(int)}. 21454 * 21455 * @return the defined text direction. It can be one of: 21456 * 21457 * {@link #TEXT_DIRECTION_INHERIT}, 21458 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21459 * {@link #TEXT_DIRECTION_ANY_RTL}, 21460 * {@link #TEXT_DIRECTION_LTR}, 21461 * {@link #TEXT_DIRECTION_RTL}, 21462 * {@link #TEXT_DIRECTION_LOCALE}, 21463 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21464 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21465 * 21466 * @attr ref android.R.styleable#View_textDirection 21467 * 21468 * @hide 21469 */ 21470 @ViewDebug.ExportedProperty(category = "text", mapping = { 21471 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21472 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21473 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21474 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21475 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21476 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21477 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21478 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21479 }) 21480 public int getRawTextDirection() { 21481 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21482 } 21483 21484 /** 21485 * Set the text direction. 21486 * 21487 * @param textDirection the direction to set. Should be one of: 21488 * 21489 * {@link #TEXT_DIRECTION_INHERIT}, 21490 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21491 * {@link #TEXT_DIRECTION_ANY_RTL}, 21492 * {@link #TEXT_DIRECTION_LTR}, 21493 * {@link #TEXT_DIRECTION_RTL}, 21494 * {@link #TEXT_DIRECTION_LOCALE} 21495 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21496 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21497 * 21498 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21499 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21500 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21501 * 21502 * @attr ref android.R.styleable#View_textDirection 21503 */ 21504 public void setTextDirection(int textDirection) { 21505 if (getRawTextDirection() != textDirection) { 21506 // Reset the current text direction and the resolved one 21507 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21508 resetResolvedTextDirection(); 21509 // Set the new text direction 21510 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21511 // Do resolution 21512 resolveTextDirection(); 21513 // Notify change 21514 onRtlPropertiesChanged(getLayoutDirection()); 21515 // Refresh 21516 requestLayout(); 21517 invalidate(true); 21518 } 21519 } 21520 21521 /** 21522 * Return the resolved text direction. 21523 * 21524 * @return the resolved text direction. Returns one of: 21525 * 21526 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21527 * {@link #TEXT_DIRECTION_ANY_RTL}, 21528 * {@link #TEXT_DIRECTION_LTR}, 21529 * {@link #TEXT_DIRECTION_RTL}, 21530 * {@link #TEXT_DIRECTION_LOCALE}, 21531 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21532 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21533 * 21534 * @attr ref android.R.styleable#View_textDirection 21535 */ 21536 @ViewDebug.ExportedProperty(category = "text", mapping = { 21537 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21538 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21539 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21540 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21541 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21542 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21543 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21544 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21545 }) 21546 public int getTextDirection() { 21547 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21548 } 21549 21550 /** 21551 * Resolve the text direction. 21552 * 21553 * @return true if resolution has been done, false otherwise. 21554 * 21555 * @hide 21556 */ 21557 public boolean resolveTextDirection() { 21558 // Reset any previous text direction resolution 21559 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21560 21561 if (hasRtlSupport()) { 21562 // Set resolved text direction flag depending on text direction flag 21563 final int textDirection = getRawTextDirection(); 21564 switch(textDirection) { 21565 case TEXT_DIRECTION_INHERIT: 21566 if (!canResolveTextDirection()) { 21567 // We cannot do the resolution if there is no parent, so use the default one 21568 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21569 // Resolution will need to happen again later 21570 return false; 21571 } 21572 21573 // Parent has not yet resolved, so we still return the default 21574 try { 21575 if (!mParent.isTextDirectionResolved()) { 21576 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21577 // Resolution will need to happen again later 21578 return false; 21579 } 21580 } catch (AbstractMethodError e) { 21581 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21582 " does not fully implement ViewParent", e); 21583 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21584 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21585 return true; 21586 } 21587 21588 // Set current resolved direction to the same value as the parent's one 21589 int parentResolvedDirection; 21590 try { 21591 parentResolvedDirection = mParent.getTextDirection(); 21592 } catch (AbstractMethodError e) { 21593 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21594 " does not fully implement ViewParent", e); 21595 parentResolvedDirection = TEXT_DIRECTION_LTR; 21596 } 21597 switch (parentResolvedDirection) { 21598 case TEXT_DIRECTION_FIRST_STRONG: 21599 case TEXT_DIRECTION_ANY_RTL: 21600 case TEXT_DIRECTION_LTR: 21601 case TEXT_DIRECTION_RTL: 21602 case TEXT_DIRECTION_LOCALE: 21603 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21604 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21605 mPrivateFlags2 |= 21606 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21607 break; 21608 default: 21609 // Default resolved direction is "first strong" heuristic 21610 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21611 } 21612 break; 21613 case TEXT_DIRECTION_FIRST_STRONG: 21614 case TEXT_DIRECTION_ANY_RTL: 21615 case TEXT_DIRECTION_LTR: 21616 case TEXT_DIRECTION_RTL: 21617 case TEXT_DIRECTION_LOCALE: 21618 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21619 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21620 // Resolved direction is the same as text direction 21621 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21622 break; 21623 default: 21624 // Default resolved direction is "first strong" heuristic 21625 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21626 } 21627 } else { 21628 // Default resolved direction is "first strong" heuristic 21629 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21630 } 21631 21632 // Set to resolved 21633 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21634 return true; 21635 } 21636 21637 /** 21638 * Check if text direction resolution can be done. 21639 * 21640 * @return true if text direction resolution can be done otherwise return false. 21641 */ 21642 public boolean canResolveTextDirection() { 21643 switch (getRawTextDirection()) { 21644 case TEXT_DIRECTION_INHERIT: 21645 if (mParent != null) { 21646 try { 21647 return mParent.canResolveTextDirection(); 21648 } catch (AbstractMethodError e) { 21649 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21650 " does not fully implement ViewParent", e); 21651 } 21652 } 21653 return false; 21654 21655 default: 21656 return true; 21657 } 21658 } 21659 21660 /** 21661 * Reset resolved text direction. Text direction will be resolved during a call to 21662 * {@link #onMeasure(int, int)}. 21663 * 21664 * @hide 21665 */ 21666 public void resetResolvedTextDirection() { 21667 // Reset any previous text direction resolution 21668 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21669 // Set to default value 21670 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21671 } 21672 21673 /** 21674 * @return true if text direction is inherited. 21675 * 21676 * @hide 21677 */ 21678 public boolean isTextDirectionInherited() { 21679 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21680 } 21681 21682 /** 21683 * @return true if text direction is resolved. 21684 */ 21685 public boolean isTextDirectionResolved() { 21686 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21687 } 21688 21689 /** 21690 * Return the value specifying the text alignment or policy that was set with 21691 * {@link #setTextAlignment(int)}. 21692 * 21693 * @return the defined text alignment. It can be one of: 21694 * 21695 * {@link #TEXT_ALIGNMENT_INHERIT}, 21696 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21697 * {@link #TEXT_ALIGNMENT_CENTER}, 21698 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21699 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21700 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21701 * {@link #TEXT_ALIGNMENT_VIEW_END} 21702 * 21703 * @attr ref android.R.styleable#View_textAlignment 21704 * 21705 * @hide 21706 */ 21707 @ViewDebug.ExportedProperty(category = "text", mapping = { 21708 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21709 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21710 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21711 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21712 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21713 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21714 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21715 }) 21716 @TextAlignment 21717 public int getRawTextAlignment() { 21718 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21719 } 21720 21721 /** 21722 * Set the text alignment. 21723 * 21724 * @param textAlignment The text alignment to set. Should be one of 21725 * 21726 * {@link #TEXT_ALIGNMENT_INHERIT}, 21727 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21728 * {@link #TEXT_ALIGNMENT_CENTER}, 21729 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21730 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21731 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21732 * {@link #TEXT_ALIGNMENT_VIEW_END} 21733 * 21734 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21735 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21736 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21737 * 21738 * @attr ref android.R.styleable#View_textAlignment 21739 */ 21740 public void setTextAlignment(@TextAlignment int textAlignment) { 21741 if (textAlignment != getRawTextAlignment()) { 21742 // Reset the current and resolved text alignment 21743 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21744 resetResolvedTextAlignment(); 21745 // Set the new text alignment 21746 mPrivateFlags2 |= 21747 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21748 // Do resolution 21749 resolveTextAlignment(); 21750 // Notify change 21751 onRtlPropertiesChanged(getLayoutDirection()); 21752 // Refresh 21753 requestLayout(); 21754 invalidate(true); 21755 } 21756 } 21757 21758 /** 21759 * Return the resolved text alignment. 21760 * 21761 * @return the resolved text alignment. Returns one of: 21762 * 21763 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21764 * {@link #TEXT_ALIGNMENT_CENTER}, 21765 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21766 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21767 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21768 * {@link #TEXT_ALIGNMENT_VIEW_END} 21769 * 21770 * @attr ref android.R.styleable#View_textAlignment 21771 */ 21772 @ViewDebug.ExportedProperty(category = "text", mapping = { 21773 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21774 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21775 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21776 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21777 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21778 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21779 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21780 }) 21781 @TextAlignment 21782 public int getTextAlignment() { 21783 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21784 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21785 } 21786 21787 /** 21788 * Resolve the text alignment. 21789 * 21790 * @return true if resolution has been done, false otherwise. 21791 * 21792 * @hide 21793 */ 21794 public boolean resolveTextAlignment() { 21795 // Reset any previous text alignment resolution 21796 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21797 21798 if (hasRtlSupport()) { 21799 // Set resolved text alignment flag depending on text alignment flag 21800 final int textAlignment = getRawTextAlignment(); 21801 switch (textAlignment) { 21802 case TEXT_ALIGNMENT_INHERIT: 21803 // Check if we can resolve the text alignment 21804 if (!canResolveTextAlignment()) { 21805 // We cannot do the resolution if there is no parent so use the default 21806 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21807 // Resolution will need to happen again later 21808 return false; 21809 } 21810 21811 // Parent has not yet resolved, so we still return the default 21812 try { 21813 if (!mParent.isTextAlignmentResolved()) { 21814 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21815 // Resolution will need to happen again later 21816 return false; 21817 } 21818 } catch (AbstractMethodError e) { 21819 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21820 " does not fully implement ViewParent", e); 21821 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21822 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21823 return true; 21824 } 21825 21826 int parentResolvedTextAlignment; 21827 try { 21828 parentResolvedTextAlignment = mParent.getTextAlignment(); 21829 } catch (AbstractMethodError e) { 21830 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21831 " does not fully implement ViewParent", e); 21832 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21833 } 21834 switch (parentResolvedTextAlignment) { 21835 case TEXT_ALIGNMENT_GRAVITY: 21836 case TEXT_ALIGNMENT_TEXT_START: 21837 case TEXT_ALIGNMENT_TEXT_END: 21838 case TEXT_ALIGNMENT_CENTER: 21839 case TEXT_ALIGNMENT_VIEW_START: 21840 case TEXT_ALIGNMENT_VIEW_END: 21841 // Resolved text alignment is the same as the parent resolved 21842 // text alignment 21843 mPrivateFlags2 |= 21844 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21845 break; 21846 default: 21847 // Use default resolved text alignment 21848 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21849 } 21850 break; 21851 case TEXT_ALIGNMENT_GRAVITY: 21852 case TEXT_ALIGNMENT_TEXT_START: 21853 case TEXT_ALIGNMENT_TEXT_END: 21854 case TEXT_ALIGNMENT_CENTER: 21855 case TEXT_ALIGNMENT_VIEW_START: 21856 case TEXT_ALIGNMENT_VIEW_END: 21857 // Resolved text alignment is the same as text alignment 21858 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21859 break; 21860 default: 21861 // Use default resolved text alignment 21862 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21863 } 21864 } else { 21865 // Use default resolved text alignment 21866 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21867 } 21868 21869 // Set the resolved 21870 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21871 return true; 21872 } 21873 21874 /** 21875 * Check if text alignment resolution can be done. 21876 * 21877 * @return true if text alignment resolution can be done otherwise return false. 21878 */ 21879 public boolean canResolveTextAlignment() { 21880 switch (getRawTextAlignment()) { 21881 case TEXT_DIRECTION_INHERIT: 21882 if (mParent != null) { 21883 try { 21884 return mParent.canResolveTextAlignment(); 21885 } catch (AbstractMethodError e) { 21886 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21887 " does not fully implement ViewParent", e); 21888 } 21889 } 21890 return false; 21891 21892 default: 21893 return true; 21894 } 21895 } 21896 21897 /** 21898 * Reset resolved text alignment. Text alignment will be resolved during a call to 21899 * {@link #onMeasure(int, int)}. 21900 * 21901 * @hide 21902 */ 21903 public void resetResolvedTextAlignment() { 21904 // Reset any previous text alignment resolution 21905 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21906 // Set to default 21907 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21908 } 21909 21910 /** 21911 * @return true if text alignment is inherited. 21912 * 21913 * @hide 21914 */ 21915 public boolean isTextAlignmentInherited() { 21916 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21917 } 21918 21919 /** 21920 * @return true if text alignment is resolved. 21921 */ 21922 public boolean isTextAlignmentResolved() { 21923 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21924 } 21925 21926 /** 21927 * Generate a value suitable for use in {@link #setId(int)}. 21928 * This value will not collide with ID values generated at build time by aapt for R.id. 21929 * 21930 * @return a generated ID value 21931 */ 21932 public static int generateViewId() { 21933 for (;;) { 21934 final int result = sNextGeneratedId.get(); 21935 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21936 int newValue = result + 1; 21937 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21938 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21939 return result; 21940 } 21941 } 21942 } 21943 21944 /** 21945 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21946 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21947 * a normal View or a ViewGroup with 21948 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21949 * @hide 21950 */ 21951 public void captureTransitioningViews(List<View> transitioningViews) { 21952 if (getVisibility() == View.VISIBLE) { 21953 transitioningViews.add(this); 21954 } 21955 } 21956 21957 /** 21958 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21959 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21960 * @hide 21961 */ 21962 public void findNamedViews(Map<String, View> namedElements) { 21963 if (getVisibility() == VISIBLE || mGhostView != null) { 21964 String transitionName = getTransitionName(); 21965 if (transitionName != null) { 21966 namedElements.put(transitionName, this); 21967 } 21968 } 21969 } 21970 21971 /** 21972 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21973 * The default implementation does not care the location or event types, but some subclasses 21974 * may use it (such as WebViews). 21975 * @param event The MotionEvent from a mouse 21976 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 21977 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 21978 * @see PointerIcon 21979 */ 21980 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 21981 final float x = event.getX(pointerIndex); 21982 final float y = event.getY(pointerIndex); 21983 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21984 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 21985 } 21986 return mPointerIcon; 21987 } 21988 21989 /** 21990 * Set the pointer icon for the current view. 21991 * Passing {@code null} will restore the pointer icon to its default value. 21992 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21993 */ 21994 public void setPointerIcon(PointerIcon pointerIcon) { 21995 mPointerIcon = pointerIcon; 21996 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 21997 return; 21998 } 21999 try { 22000 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 22001 } catch (RemoteException e) { 22002 } 22003 } 22004 22005 /** 22006 * Gets the pointer icon for the current view. 22007 */ 22008 public PointerIcon getPointerIcon() { 22009 return mPointerIcon; 22010 } 22011 22012 // 22013 // Properties 22014 // 22015 /** 22016 * A Property wrapper around the <code>alpha</code> functionality handled by the 22017 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 22018 */ 22019 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 22020 @Override 22021 public void setValue(View object, float value) { 22022 object.setAlpha(value); 22023 } 22024 22025 @Override 22026 public Float get(View object) { 22027 return object.getAlpha(); 22028 } 22029 }; 22030 22031 /** 22032 * A Property wrapper around the <code>translationX</code> functionality handled by the 22033 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 22034 */ 22035 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 22036 @Override 22037 public void setValue(View object, float value) { 22038 object.setTranslationX(value); 22039 } 22040 22041 @Override 22042 public Float get(View object) { 22043 return object.getTranslationX(); 22044 } 22045 }; 22046 22047 /** 22048 * A Property wrapper around the <code>translationY</code> functionality handled by the 22049 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 22050 */ 22051 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 22052 @Override 22053 public void setValue(View object, float value) { 22054 object.setTranslationY(value); 22055 } 22056 22057 @Override 22058 public Float get(View object) { 22059 return object.getTranslationY(); 22060 } 22061 }; 22062 22063 /** 22064 * A Property wrapper around the <code>translationZ</code> functionality handled by the 22065 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 22066 */ 22067 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 22068 @Override 22069 public void setValue(View object, float value) { 22070 object.setTranslationZ(value); 22071 } 22072 22073 @Override 22074 public Float get(View object) { 22075 return object.getTranslationZ(); 22076 } 22077 }; 22078 22079 /** 22080 * A Property wrapper around the <code>x</code> functionality handled by the 22081 * {@link View#setX(float)} and {@link View#getX()} methods. 22082 */ 22083 public static final Property<View, Float> X = new FloatProperty<View>("x") { 22084 @Override 22085 public void setValue(View object, float value) { 22086 object.setX(value); 22087 } 22088 22089 @Override 22090 public Float get(View object) { 22091 return object.getX(); 22092 } 22093 }; 22094 22095 /** 22096 * A Property wrapper around the <code>y</code> functionality handled by the 22097 * {@link View#setY(float)} and {@link View#getY()} methods. 22098 */ 22099 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 22100 @Override 22101 public void setValue(View object, float value) { 22102 object.setY(value); 22103 } 22104 22105 @Override 22106 public Float get(View object) { 22107 return object.getY(); 22108 } 22109 }; 22110 22111 /** 22112 * A Property wrapper around the <code>z</code> functionality handled by the 22113 * {@link View#setZ(float)} and {@link View#getZ()} methods. 22114 */ 22115 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 22116 @Override 22117 public void setValue(View object, float value) { 22118 object.setZ(value); 22119 } 22120 22121 @Override 22122 public Float get(View object) { 22123 return object.getZ(); 22124 } 22125 }; 22126 22127 /** 22128 * A Property wrapper around the <code>rotation</code> functionality handled by the 22129 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22130 */ 22131 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22132 @Override 22133 public void setValue(View object, float value) { 22134 object.setRotation(value); 22135 } 22136 22137 @Override 22138 public Float get(View object) { 22139 return object.getRotation(); 22140 } 22141 }; 22142 22143 /** 22144 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22145 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22146 */ 22147 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22148 @Override 22149 public void setValue(View object, float value) { 22150 object.setRotationX(value); 22151 } 22152 22153 @Override 22154 public Float get(View object) { 22155 return object.getRotationX(); 22156 } 22157 }; 22158 22159 /** 22160 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22161 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22162 */ 22163 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22164 @Override 22165 public void setValue(View object, float value) { 22166 object.setRotationY(value); 22167 } 22168 22169 @Override 22170 public Float get(View object) { 22171 return object.getRotationY(); 22172 } 22173 }; 22174 22175 /** 22176 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22177 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22178 */ 22179 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22180 @Override 22181 public void setValue(View object, float value) { 22182 object.setScaleX(value); 22183 } 22184 22185 @Override 22186 public Float get(View object) { 22187 return object.getScaleX(); 22188 } 22189 }; 22190 22191 /** 22192 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22193 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22194 */ 22195 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22196 @Override 22197 public void setValue(View object, float value) { 22198 object.setScaleY(value); 22199 } 22200 22201 @Override 22202 public Float get(View object) { 22203 return object.getScaleY(); 22204 } 22205 }; 22206 22207 /** 22208 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22209 * Each MeasureSpec represents a requirement for either the width or the height. 22210 * A MeasureSpec is comprised of a size and a mode. There are three possible 22211 * modes: 22212 * <dl> 22213 * <dt>UNSPECIFIED</dt> 22214 * <dd> 22215 * The parent has not imposed any constraint on the child. It can be whatever size 22216 * it wants. 22217 * </dd> 22218 * 22219 * <dt>EXACTLY</dt> 22220 * <dd> 22221 * The parent has determined an exact size for the child. The child is going to be 22222 * given those bounds regardless of how big it wants to be. 22223 * </dd> 22224 * 22225 * <dt>AT_MOST</dt> 22226 * <dd> 22227 * The child can be as large as it wants up to the specified size. 22228 * </dd> 22229 * </dl> 22230 * 22231 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22232 * is provided to pack and unpack the <size, mode> tuple into the int. 22233 */ 22234 public static class MeasureSpec { 22235 private static final int MODE_SHIFT = 30; 22236 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22237 22238 /** @hide */ 22239 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22240 @Retention(RetentionPolicy.SOURCE) 22241 public @interface MeasureSpecMode {} 22242 22243 /** 22244 * Measure specification mode: The parent has not imposed any constraint 22245 * on the child. It can be whatever size it wants. 22246 */ 22247 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22248 22249 /** 22250 * Measure specification mode: The parent has determined an exact size 22251 * for the child. The child is going to be given those bounds regardless 22252 * of how big it wants to be. 22253 */ 22254 public static final int EXACTLY = 1 << MODE_SHIFT; 22255 22256 /** 22257 * Measure specification mode: The child can be as large as it wants up 22258 * to the specified size. 22259 */ 22260 public static final int AT_MOST = 2 << MODE_SHIFT; 22261 22262 /** 22263 * Creates a measure specification based on the supplied size and mode. 22264 * 22265 * The mode must always be one of the following: 22266 * <ul> 22267 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22268 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22269 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22270 * </ul> 22271 * 22272 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22273 * implementation was such that the order of arguments did not matter 22274 * and overflow in either value could impact the resulting MeasureSpec. 22275 * {@link android.widget.RelativeLayout} was affected by this bug. 22276 * Apps targeting API levels greater than 17 will get the fixed, more strict 22277 * behavior.</p> 22278 * 22279 * @param size the size of the measure specification 22280 * @param mode the mode of the measure specification 22281 * @return the measure specification based on size and mode 22282 */ 22283 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22284 @MeasureSpecMode int mode) { 22285 if (sUseBrokenMakeMeasureSpec) { 22286 return size + mode; 22287 } else { 22288 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22289 } 22290 } 22291 22292 /** 22293 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22294 * will automatically get a size of 0. Older apps expect this. 22295 * 22296 * @hide internal use only for compatibility with system widgets and older apps 22297 */ 22298 public static int makeSafeMeasureSpec(int size, int mode) { 22299 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22300 return 0; 22301 } 22302 return makeMeasureSpec(size, mode); 22303 } 22304 22305 /** 22306 * Extracts the mode from the supplied measure specification. 22307 * 22308 * @param measureSpec the measure specification to extract the mode from 22309 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22310 * {@link android.view.View.MeasureSpec#AT_MOST} or 22311 * {@link android.view.View.MeasureSpec#EXACTLY} 22312 */ 22313 @MeasureSpecMode 22314 public static int getMode(int measureSpec) { 22315 //noinspection ResourceType 22316 return (measureSpec & MODE_MASK); 22317 } 22318 22319 /** 22320 * Extracts the size from the supplied measure specification. 22321 * 22322 * @param measureSpec the measure specification to extract the size from 22323 * @return the size in pixels defined in the supplied measure specification 22324 */ 22325 public static int getSize(int measureSpec) { 22326 return (measureSpec & ~MODE_MASK); 22327 } 22328 22329 static int adjust(int measureSpec, int delta) { 22330 final int mode = getMode(measureSpec); 22331 int size = getSize(measureSpec); 22332 if (mode == UNSPECIFIED) { 22333 // No need to adjust size for UNSPECIFIED mode. 22334 return makeMeasureSpec(size, UNSPECIFIED); 22335 } 22336 size += delta; 22337 if (size < 0) { 22338 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22339 ") spec: " + toString(measureSpec) + " delta: " + delta); 22340 size = 0; 22341 } 22342 return makeMeasureSpec(size, mode); 22343 } 22344 22345 /** 22346 * Returns a String representation of the specified measure 22347 * specification. 22348 * 22349 * @param measureSpec the measure specification to convert to a String 22350 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22351 */ 22352 public static String toString(int measureSpec) { 22353 int mode = getMode(measureSpec); 22354 int size = getSize(measureSpec); 22355 22356 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22357 22358 if (mode == UNSPECIFIED) 22359 sb.append("UNSPECIFIED "); 22360 else if (mode == EXACTLY) 22361 sb.append("EXACTLY "); 22362 else if (mode == AT_MOST) 22363 sb.append("AT_MOST "); 22364 else 22365 sb.append(mode).append(" "); 22366 22367 sb.append(size); 22368 return sb.toString(); 22369 } 22370 } 22371 22372 private final class CheckForLongPress implements Runnable { 22373 private int mOriginalWindowAttachCount; 22374 private float mX; 22375 private float mY; 22376 22377 @Override 22378 public void run() { 22379 if (isPressed() && (mParent != null) 22380 && mOriginalWindowAttachCount == mWindowAttachCount) { 22381 if (performLongClick(mX, mY)) { 22382 mHasPerformedLongPress = true; 22383 } 22384 } 22385 } 22386 22387 public void setAnchor(float x, float y) { 22388 mX = x; 22389 mY = y; 22390 } 22391 22392 public void rememberWindowAttachCount() { 22393 mOriginalWindowAttachCount = mWindowAttachCount; 22394 } 22395 } 22396 22397 private final class CheckForTap implements Runnable { 22398 public float x; 22399 public float y; 22400 22401 @Override 22402 public void run() { 22403 mPrivateFlags &= ~PFLAG_PREPRESSED; 22404 setPressed(true, x, y); 22405 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22406 } 22407 } 22408 22409 private final class PerformClick implements Runnable { 22410 @Override 22411 public void run() { 22412 performClick(); 22413 } 22414 } 22415 22416 /** 22417 * This method returns a ViewPropertyAnimator object, which can be used to animate 22418 * specific properties on this View. 22419 * 22420 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22421 */ 22422 public ViewPropertyAnimator animate() { 22423 if (mAnimator == null) { 22424 mAnimator = new ViewPropertyAnimator(this); 22425 } 22426 return mAnimator; 22427 } 22428 22429 /** 22430 * Sets the name of the View to be used to identify Views in Transitions. 22431 * Names should be unique in the View hierarchy. 22432 * 22433 * @param transitionName The name of the View to uniquely identify it for Transitions. 22434 */ 22435 public final void setTransitionName(String transitionName) { 22436 mTransitionName = transitionName; 22437 } 22438 22439 /** 22440 * Returns the name of the View to be used to identify Views in Transitions. 22441 * Names should be unique in the View hierarchy. 22442 * 22443 * <p>This returns null if the View has not been given a name.</p> 22444 * 22445 * @return The name used of the View to be used to identify Views in Transitions or null 22446 * if no name has been given. 22447 */ 22448 @ViewDebug.ExportedProperty 22449 public String getTransitionName() { 22450 return mTransitionName; 22451 } 22452 22453 /** 22454 * @hide 22455 */ 22456 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22457 // Do nothing. 22458 } 22459 22460 /** 22461 * Interface definition for a callback to be invoked when a hardware key event is 22462 * dispatched to this view. The callback will be invoked before the key event is 22463 * given to the view. This is only useful for hardware keyboards; a software input 22464 * method has no obligation to trigger this listener. 22465 */ 22466 public interface OnKeyListener { 22467 /** 22468 * Called when a hardware key is dispatched to a view. This allows listeners to 22469 * get a chance to respond before the target view. 22470 * <p>Key presses in software keyboards will generally NOT trigger this method, 22471 * although some may elect to do so in some situations. Do not assume a 22472 * software input method has to be key-based; even if it is, it may use key presses 22473 * in a different way than you expect, so there is no way to reliably catch soft 22474 * input key presses. 22475 * 22476 * @param v The view the key has been dispatched to. 22477 * @param keyCode The code for the physical key that was pressed 22478 * @param event The KeyEvent object containing full information about 22479 * the event. 22480 * @return True if the listener has consumed the event, false otherwise. 22481 */ 22482 boolean onKey(View v, int keyCode, KeyEvent event); 22483 } 22484 22485 /** 22486 * Interface definition for a callback to be invoked when a touch event is 22487 * dispatched to this view. The callback will be invoked before the touch 22488 * event is given to the view. 22489 */ 22490 public interface OnTouchListener { 22491 /** 22492 * Called when a touch event is dispatched to a view. This allows listeners to 22493 * get a chance to respond before the target view. 22494 * 22495 * @param v The view the touch event has been dispatched to. 22496 * @param event The MotionEvent object containing full information about 22497 * the event. 22498 * @return True if the listener has consumed the event, false otherwise. 22499 */ 22500 boolean onTouch(View v, MotionEvent event); 22501 } 22502 22503 /** 22504 * Interface definition for a callback to be invoked when a hover event is 22505 * dispatched to this view. The callback will be invoked before the hover 22506 * event is given to the view. 22507 */ 22508 public interface OnHoverListener { 22509 /** 22510 * Called when a hover event is dispatched to a view. This allows listeners to 22511 * get a chance to respond before the target view. 22512 * 22513 * @param v The view the hover event has been dispatched to. 22514 * @param event The MotionEvent object containing full information about 22515 * the event. 22516 * @return True if the listener has consumed the event, false otherwise. 22517 */ 22518 boolean onHover(View v, MotionEvent event); 22519 } 22520 22521 /** 22522 * Interface definition for a callback to be invoked when a generic motion event is 22523 * dispatched to this view. The callback will be invoked before the generic motion 22524 * event is given to the view. 22525 */ 22526 public interface OnGenericMotionListener { 22527 /** 22528 * Called when a generic motion event is dispatched to a view. This allows listeners to 22529 * get a chance to respond before the target view. 22530 * 22531 * @param v The view the generic motion event has been dispatched to. 22532 * @param event The MotionEvent object containing full information about 22533 * the event. 22534 * @return True if the listener has consumed the event, false otherwise. 22535 */ 22536 boolean onGenericMotion(View v, MotionEvent event); 22537 } 22538 22539 /** 22540 * Interface definition for a callback to be invoked when a view has been clicked and held. 22541 */ 22542 public interface OnLongClickListener { 22543 /** 22544 * Called when a view has been clicked and held. 22545 * 22546 * @param v The view that was clicked and held. 22547 * 22548 * @return true if the callback consumed the long click, false otherwise. 22549 */ 22550 boolean onLongClick(View v); 22551 } 22552 22553 /** 22554 * Interface definition for a callback to be invoked when a drag is being dispatched 22555 * to this view. The callback will be invoked before the hosting view's own 22556 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22557 * onDrag(event) behavior, it should return 'false' from this callback. 22558 * 22559 * <div class="special reference"> 22560 * <h3>Developer Guides</h3> 22561 * <p>For a guide to implementing drag and drop features, read the 22562 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22563 * </div> 22564 */ 22565 public interface OnDragListener { 22566 /** 22567 * Called when a drag event is dispatched to a view. This allows listeners 22568 * to get a chance to override base View behavior. 22569 * 22570 * @param v The View that received the drag event. 22571 * @param event The {@link android.view.DragEvent} object for the drag event. 22572 * @return {@code true} if the drag event was handled successfully, or {@code false} 22573 * if the drag event was not handled. Note that {@code false} will trigger the View 22574 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22575 */ 22576 boolean onDrag(View v, DragEvent event); 22577 } 22578 22579 /** 22580 * Interface definition for a callback to be invoked when the focus state of 22581 * a view changed. 22582 */ 22583 public interface OnFocusChangeListener { 22584 /** 22585 * Called when the focus state of a view has changed. 22586 * 22587 * @param v The view whose state has changed. 22588 * @param hasFocus The new focus state of v. 22589 */ 22590 void onFocusChange(View v, boolean hasFocus); 22591 } 22592 22593 /** 22594 * Interface definition for a callback to be invoked when a view is clicked. 22595 */ 22596 public interface OnClickListener { 22597 /** 22598 * Called when a view has been clicked. 22599 * 22600 * @param v The view that was clicked. 22601 */ 22602 void onClick(View v); 22603 } 22604 22605 /** 22606 * Interface definition for a callback to be invoked when a view is context clicked. 22607 */ 22608 public interface OnContextClickListener { 22609 /** 22610 * Called when a view is context clicked. 22611 * 22612 * @param v The view that has been context clicked. 22613 * @return true if the callback consumed the context click, false otherwise. 22614 */ 22615 boolean onContextClick(View v); 22616 } 22617 22618 /** 22619 * Interface definition for a callback to be invoked when the context menu 22620 * for this view is being built. 22621 */ 22622 public interface OnCreateContextMenuListener { 22623 /** 22624 * Called when the context menu for this view is being built. It is not 22625 * safe to hold onto the menu after this method returns. 22626 * 22627 * @param menu The context menu that is being built 22628 * @param v The view for which the context menu is being built 22629 * @param menuInfo Extra information about the item for which the 22630 * context menu should be shown. This information will vary 22631 * depending on the class of v. 22632 */ 22633 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22634 } 22635 22636 /** 22637 * Interface definition for a callback to be invoked when the status bar changes 22638 * visibility. This reports <strong>global</strong> changes to the system UI 22639 * state, not what the application is requesting. 22640 * 22641 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22642 */ 22643 public interface OnSystemUiVisibilityChangeListener { 22644 /** 22645 * Called when the status bar changes visibility because of a call to 22646 * {@link View#setSystemUiVisibility(int)}. 22647 * 22648 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22649 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22650 * This tells you the <strong>global</strong> state of these UI visibility 22651 * flags, not what your app is currently applying. 22652 */ 22653 public void onSystemUiVisibilityChange(int visibility); 22654 } 22655 22656 /** 22657 * Interface definition for a callback to be invoked when this view is attached 22658 * or detached from its window. 22659 */ 22660 public interface OnAttachStateChangeListener { 22661 /** 22662 * Called when the view is attached to a window. 22663 * @param v The view that was attached 22664 */ 22665 public void onViewAttachedToWindow(View v); 22666 /** 22667 * Called when the view is detached from a window. 22668 * @param v The view that was detached 22669 */ 22670 public void onViewDetachedFromWindow(View v); 22671 } 22672 22673 /** 22674 * Listener for applying window insets on a view in a custom way. 22675 * 22676 * <p>Apps may choose to implement this interface if they want to apply custom policy 22677 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22678 * is set, its 22679 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22680 * method will be called instead of the View's own 22681 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22682 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22683 * the View's normal behavior as part of its own.</p> 22684 */ 22685 public interface OnApplyWindowInsetsListener { 22686 /** 22687 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22688 * on a View, this listener method will be called instead of the view's own 22689 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22690 * 22691 * @param v The view applying window insets 22692 * @param insets The insets to apply 22693 * @return The insets supplied, minus any insets that were consumed 22694 */ 22695 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22696 } 22697 22698 private final class UnsetPressedState implements Runnable { 22699 @Override 22700 public void run() { 22701 setPressed(false); 22702 } 22703 } 22704 22705 /** 22706 * Base class for derived classes that want to save and restore their own 22707 * state in {@link android.view.View#onSaveInstanceState()}. 22708 */ 22709 public static class BaseSavedState extends AbsSavedState { 22710 String mStartActivityRequestWhoSaved; 22711 22712 /** 22713 * Constructor used when reading from a parcel. Reads the state of the superclass. 22714 * 22715 * @param source parcel to read from 22716 */ 22717 public BaseSavedState(Parcel source) { 22718 this(source, null); 22719 } 22720 22721 /** 22722 * Constructor used when reading from a parcel using a given class loader. 22723 * Reads the state of the superclass. 22724 * 22725 * @param source parcel to read from 22726 * @param loader ClassLoader to use for reading 22727 */ 22728 public BaseSavedState(Parcel source, ClassLoader loader) { 22729 super(source, loader); 22730 mStartActivityRequestWhoSaved = source.readString(); 22731 } 22732 22733 /** 22734 * Constructor called by derived classes when creating their SavedState objects 22735 * 22736 * @param superState The state of the superclass of this view 22737 */ 22738 public BaseSavedState(Parcelable superState) { 22739 super(superState); 22740 } 22741 22742 @Override 22743 public void writeToParcel(Parcel out, int flags) { 22744 super.writeToParcel(out, flags); 22745 out.writeString(mStartActivityRequestWhoSaved); 22746 } 22747 22748 public static final Parcelable.Creator<BaseSavedState> CREATOR 22749 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 22750 @Override 22751 public BaseSavedState createFromParcel(Parcel in) { 22752 return new BaseSavedState(in); 22753 } 22754 22755 @Override 22756 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 22757 return new BaseSavedState(in, loader); 22758 } 22759 22760 @Override 22761 public BaseSavedState[] newArray(int size) { 22762 return new BaseSavedState[size]; 22763 } 22764 }; 22765 } 22766 22767 /** 22768 * A set of information given to a view when it is attached to its parent 22769 * window. 22770 */ 22771 final static class AttachInfo { 22772 interface Callbacks { 22773 void playSoundEffect(int effectId); 22774 boolean performHapticFeedback(int effectId, boolean always); 22775 } 22776 22777 /** 22778 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22779 * to a Handler. This class contains the target (View) to invalidate and 22780 * the coordinates of the dirty rectangle. 22781 * 22782 * For performance purposes, this class also implements a pool of up to 22783 * POOL_LIMIT objects that get reused. This reduces memory allocations 22784 * whenever possible. 22785 */ 22786 static class InvalidateInfo { 22787 private static final int POOL_LIMIT = 10; 22788 22789 private static final SynchronizedPool<InvalidateInfo> sPool = 22790 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22791 22792 View target; 22793 22794 int left; 22795 int top; 22796 int right; 22797 int bottom; 22798 22799 public static InvalidateInfo obtain() { 22800 InvalidateInfo instance = sPool.acquire(); 22801 return (instance != null) ? instance : new InvalidateInfo(); 22802 } 22803 22804 public void recycle() { 22805 target = null; 22806 sPool.release(this); 22807 } 22808 } 22809 22810 final IWindowSession mSession; 22811 22812 final IWindow mWindow; 22813 22814 final IBinder mWindowToken; 22815 22816 final Display mDisplay; 22817 22818 final Callbacks mRootCallbacks; 22819 22820 IWindowId mIWindowId; 22821 WindowId mWindowId; 22822 22823 /** 22824 * The top view of the hierarchy. 22825 */ 22826 View mRootView; 22827 22828 IBinder mPanelParentWindowToken; 22829 22830 boolean mHardwareAccelerated; 22831 boolean mHardwareAccelerationRequested; 22832 ThreadedRenderer mThreadedRenderer; 22833 List<RenderNode> mPendingAnimatingRenderNodes; 22834 22835 /** 22836 * The state of the display to which the window is attached, as reported 22837 * by {@link Display#getState()}. Note that the display state constants 22838 * declared by {@link Display} do not exactly line up with the screen state 22839 * constants declared by {@link View} (there are more display states than 22840 * screen states). 22841 */ 22842 int mDisplayState = Display.STATE_UNKNOWN; 22843 22844 /** 22845 * Scale factor used by the compatibility mode 22846 */ 22847 float mApplicationScale; 22848 22849 /** 22850 * Indicates whether the application is in compatibility mode 22851 */ 22852 boolean mScalingRequired; 22853 22854 /** 22855 * Left position of this view's window 22856 */ 22857 int mWindowLeft; 22858 22859 /** 22860 * Top position of this view's window 22861 */ 22862 int mWindowTop; 22863 22864 /** 22865 * Indicates whether views need to use 32-bit drawing caches 22866 */ 22867 boolean mUse32BitDrawingCache; 22868 22869 /** 22870 * For windows that are full-screen but using insets to layout inside 22871 * of the screen areas, these are the current insets to appear inside 22872 * the overscan area of the display. 22873 */ 22874 final Rect mOverscanInsets = new Rect(); 22875 22876 /** 22877 * For windows that are full-screen but using insets to layout inside 22878 * of the screen decorations, these are the current insets for the 22879 * content of the window. 22880 */ 22881 final Rect mContentInsets = new Rect(); 22882 22883 /** 22884 * For windows that are full-screen but using insets to layout inside 22885 * of the screen decorations, these are the current insets for the 22886 * actual visible parts of the window. 22887 */ 22888 final Rect mVisibleInsets = new Rect(); 22889 22890 /** 22891 * For windows that are full-screen but using insets to layout inside 22892 * of the screen decorations, these are the current insets for the 22893 * stable system windows. 22894 */ 22895 final Rect mStableInsets = new Rect(); 22896 22897 /** 22898 * For windows that include areas that are not covered by real surface these are the outsets 22899 * for real surface. 22900 */ 22901 final Rect mOutsets = new Rect(); 22902 22903 /** 22904 * In multi-window we force show the navigation bar. Because we don't want that the surface 22905 * size changes in this mode, we instead have a flag whether the navigation bar size should 22906 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22907 */ 22908 boolean mAlwaysConsumeNavBar; 22909 22910 /** 22911 * The internal insets given by this window. This value is 22912 * supplied by the client (through 22913 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22914 * be given to the window manager when changed to be used in laying 22915 * out windows behind it. 22916 */ 22917 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22918 = new ViewTreeObserver.InternalInsetsInfo(); 22919 22920 /** 22921 * Set to true when mGivenInternalInsets is non-empty. 22922 */ 22923 boolean mHasNonEmptyGivenInternalInsets; 22924 22925 /** 22926 * All views in the window's hierarchy that serve as scroll containers, 22927 * used to determine if the window can be resized or must be panned 22928 * to adjust for a soft input area. 22929 */ 22930 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22931 22932 final KeyEvent.DispatcherState mKeyDispatchState 22933 = new KeyEvent.DispatcherState(); 22934 22935 /** 22936 * Indicates whether the view's window currently has the focus. 22937 */ 22938 boolean mHasWindowFocus; 22939 22940 /** 22941 * The current visibility of the window. 22942 */ 22943 int mWindowVisibility; 22944 22945 /** 22946 * Indicates the time at which drawing started to occur. 22947 */ 22948 long mDrawingTime; 22949 22950 /** 22951 * Indicates whether or not ignoring the DIRTY_MASK flags. 22952 */ 22953 boolean mIgnoreDirtyState; 22954 22955 /** 22956 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22957 * to avoid clearing that flag prematurely. 22958 */ 22959 boolean mSetIgnoreDirtyState = false; 22960 22961 /** 22962 * Indicates whether the view's window is currently in touch mode. 22963 */ 22964 boolean mInTouchMode; 22965 22966 /** 22967 * Indicates whether the view has requested unbuffered input dispatching for the current 22968 * event stream. 22969 */ 22970 boolean mUnbufferedDispatchRequested; 22971 22972 /** 22973 * Indicates that ViewAncestor should trigger a global layout change 22974 * the next time it performs a traversal 22975 */ 22976 boolean mRecomputeGlobalAttributes; 22977 22978 /** 22979 * Always report new attributes at next traversal. 22980 */ 22981 boolean mForceReportNewAttributes; 22982 22983 /** 22984 * Set during a traveral if any views want to keep the screen on. 22985 */ 22986 boolean mKeepScreenOn; 22987 22988 /** 22989 * Set during a traveral if the light center needs to be updated. 22990 */ 22991 boolean mNeedsUpdateLightCenter; 22992 22993 /** 22994 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22995 */ 22996 int mSystemUiVisibility; 22997 22998 /** 22999 * Hack to force certain system UI visibility flags to be cleared. 23000 */ 23001 int mDisabledSystemUiVisibility; 23002 23003 /** 23004 * Last global system UI visibility reported by the window manager. 23005 */ 23006 int mGlobalSystemUiVisibility = -1; 23007 23008 /** 23009 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 23010 * attached. 23011 */ 23012 boolean mHasSystemUiListeners; 23013 23014 /** 23015 * Set if the window has requested to extend into the overscan region 23016 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 23017 */ 23018 boolean mOverscanRequested; 23019 23020 /** 23021 * Set if the visibility of any views has changed. 23022 */ 23023 boolean mViewVisibilityChanged; 23024 23025 /** 23026 * Set to true if a view has been scrolled. 23027 */ 23028 boolean mViewScrollChanged; 23029 23030 /** 23031 * Set to true if high contrast mode enabled 23032 */ 23033 boolean mHighContrastText; 23034 23035 /** 23036 * Set to true if a pointer event is currently being handled. 23037 */ 23038 boolean mHandlingPointerEvent; 23039 23040 /** 23041 * Global to the view hierarchy used as a temporary for dealing with 23042 * x/y points in the transparent region computations. 23043 */ 23044 final int[] mTransparentLocation = new int[2]; 23045 23046 /** 23047 * Global to the view hierarchy used as a temporary for dealing with 23048 * x/y points in the ViewGroup.invalidateChild implementation. 23049 */ 23050 final int[] mInvalidateChildLocation = new int[2]; 23051 23052 /** 23053 * Global to the view hierarchy used as a temporary for dealing with 23054 * computing absolute on-screen location. 23055 */ 23056 final int[] mTmpLocation = new int[2]; 23057 23058 /** 23059 * Global to the view hierarchy used as a temporary for dealing with 23060 * x/y location when view is transformed. 23061 */ 23062 final float[] mTmpTransformLocation = new float[2]; 23063 23064 /** 23065 * The view tree observer used to dispatch global events like 23066 * layout, pre-draw, touch mode change, etc. 23067 */ 23068 final ViewTreeObserver mTreeObserver; 23069 23070 /** 23071 * A Canvas used by the view hierarchy to perform bitmap caching. 23072 */ 23073 Canvas mCanvas; 23074 23075 /** 23076 * The view root impl. 23077 */ 23078 final ViewRootImpl mViewRootImpl; 23079 23080 /** 23081 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 23082 * handler can be used to pump events in the UI events queue. 23083 */ 23084 final Handler mHandler; 23085 23086 /** 23087 * Temporary for use in computing invalidate rectangles while 23088 * calling up the hierarchy. 23089 */ 23090 final Rect mTmpInvalRect = new Rect(); 23091 23092 /** 23093 * Temporary for use in computing hit areas with transformed views 23094 */ 23095 final RectF mTmpTransformRect = new RectF(); 23096 23097 /** 23098 * Temporary for use in computing hit areas with transformed views 23099 */ 23100 final RectF mTmpTransformRect1 = new RectF(); 23101 23102 /** 23103 * Temporary list of rectanges. 23104 */ 23105 final List<RectF> mTmpRectList = new ArrayList<>(); 23106 23107 /** 23108 * Temporary for use in transforming invalidation rect 23109 */ 23110 final Matrix mTmpMatrix = new Matrix(); 23111 23112 /** 23113 * Temporary for use in transforming invalidation rect 23114 */ 23115 final Transformation mTmpTransformation = new Transformation(); 23116 23117 /** 23118 * Temporary for use in querying outlines from OutlineProviders 23119 */ 23120 final Outline mTmpOutline = new Outline(); 23121 23122 /** 23123 * Temporary list for use in collecting focusable descendents of a view. 23124 */ 23125 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 23126 23127 /** 23128 * The id of the window for accessibility purposes. 23129 */ 23130 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 23131 23132 /** 23133 * Flags related to accessibility processing. 23134 * 23135 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23136 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23137 */ 23138 int mAccessibilityFetchFlags; 23139 23140 /** 23141 * The drawable for highlighting accessibility focus. 23142 */ 23143 Drawable mAccessibilityFocusDrawable; 23144 23145 /** 23146 * Show where the margins, bounds and layout bounds are for each view. 23147 */ 23148 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23149 23150 /** 23151 * Point used to compute visible regions. 23152 */ 23153 final Point mPoint = new Point(); 23154 23155 /** 23156 * Used to track which View originated a requestLayout() call, used when 23157 * requestLayout() is called during layout. 23158 */ 23159 View mViewRequestingLayout; 23160 23161 /** 23162 * Used to track views that need (at least) a partial relayout at their current size 23163 * during the next traversal. 23164 */ 23165 List<View> mPartialLayoutViews = new ArrayList<>(); 23166 23167 /** 23168 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23169 * modification. Lazily assigned during ViewRootImpl layout. 23170 */ 23171 List<View> mEmptyPartialLayoutViews; 23172 23173 /** 23174 * Used to track the identity of the current drag operation. 23175 */ 23176 IBinder mDragToken; 23177 23178 /** 23179 * The drag shadow surface for the current drag operation. 23180 */ 23181 public Surface mDragSurface; 23182 23183 /** 23184 * Creates a new set of attachment information with the specified 23185 * events handler and thread. 23186 * 23187 * @param handler the events handler the view must use 23188 */ 23189 AttachInfo(IWindowSession session, IWindow window, Display display, 23190 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 23191 Context context) { 23192 mSession = session; 23193 mWindow = window; 23194 mWindowToken = window.asBinder(); 23195 mDisplay = display; 23196 mViewRootImpl = viewRootImpl; 23197 mHandler = handler; 23198 mRootCallbacks = effectPlayer; 23199 mTreeObserver = new ViewTreeObserver(context); 23200 } 23201 } 23202 23203 /** 23204 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23205 * is supported. This avoids keeping too many unused fields in most 23206 * instances of View.</p> 23207 */ 23208 private static class ScrollabilityCache implements Runnable { 23209 23210 /** 23211 * Scrollbars are not visible 23212 */ 23213 public static final int OFF = 0; 23214 23215 /** 23216 * Scrollbars are visible 23217 */ 23218 public static final int ON = 1; 23219 23220 /** 23221 * Scrollbars are fading away 23222 */ 23223 public static final int FADING = 2; 23224 23225 public boolean fadeScrollBars; 23226 23227 public int fadingEdgeLength; 23228 public int scrollBarDefaultDelayBeforeFade; 23229 public int scrollBarFadeDuration; 23230 23231 public int scrollBarSize; 23232 public ScrollBarDrawable scrollBar; 23233 public float[] interpolatorValues; 23234 public View host; 23235 23236 public final Paint paint; 23237 public final Matrix matrix; 23238 public Shader shader; 23239 23240 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23241 23242 private static final float[] OPAQUE = { 255 }; 23243 private static final float[] TRANSPARENT = { 0.0f }; 23244 23245 /** 23246 * When fading should start. This time moves into the future every time 23247 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23248 */ 23249 public long fadeStartTime; 23250 23251 23252 /** 23253 * The current state of the scrollbars: ON, OFF, or FADING 23254 */ 23255 public int state = OFF; 23256 23257 private int mLastColor; 23258 23259 public final Rect mScrollBarBounds = new Rect(); 23260 23261 public static final int NOT_DRAGGING = 0; 23262 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23263 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23264 public int mScrollBarDraggingState = NOT_DRAGGING; 23265 23266 public float mScrollBarDraggingPos = 0; 23267 23268 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23269 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23270 scrollBarSize = configuration.getScaledScrollBarSize(); 23271 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23272 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23273 23274 paint = new Paint(); 23275 matrix = new Matrix(); 23276 // use use a height of 1, and then wack the matrix each time we 23277 // actually use it. 23278 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23279 paint.setShader(shader); 23280 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23281 23282 this.host = host; 23283 } 23284 23285 public void setFadeColor(int color) { 23286 if (color != mLastColor) { 23287 mLastColor = color; 23288 23289 if (color != 0) { 23290 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23291 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23292 paint.setShader(shader); 23293 // Restore the default transfer mode (src_over) 23294 paint.setXfermode(null); 23295 } else { 23296 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23297 paint.setShader(shader); 23298 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23299 } 23300 } 23301 } 23302 23303 public void run() { 23304 long now = AnimationUtils.currentAnimationTimeMillis(); 23305 if (now >= fadeStartTime) { 23306 23307 // the animation fades the scrollbars out by changing 23308 // the opacity (alpha) from fully opaque to fully 23309 // transparent 23310 int nextFrame = (int) now; 23311 int framesCount = 0; 23312 23313 Interpolator interpolator = scrollBarInterpolator; 23314 23315 // Start opaque 23316 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23317 23318 // End transparent 23319 nextFrame += scrollBarFadeDuration; 23320 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23321 23322 state = FADING; 23323 23324 // Kick off the fade animation 23325 host.invalidate(true); 23326 } 23327 } 23328 } 23329 23330 /** 23331 * Resuable callback for sending 23332 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23333 */ 23334 private class SendViewScrolledAccessibilityEvent implements Runnable { 23335 public volatile boolean mIsPending; 23336 23337 public void run() { 23338 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23339 mIsPending = false; 23340 } 23341 } 23342 23343 /** 23344 * <p> 23345 * This class represents a delegate that can be registered in a {@link View} 23346 * to enhance accessibility support via composition rather via inheritance. 23347 * It is specifically targeted to widget developers that extend basic View 23348 * classes i.e. classes in package android.view, that would like their 23349 * applications to be backwards compatible. 23350 * </p> 23351 * <div class="special reference"> 23352 * <h3>Developer Guides</h3> 23353 * <p>For more information about making applications accessible, read the 23354 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23355 * developer guide.</p> 23356 * </div> 23357 * <p> 23358 * A scenario in which a developer would like to use an accessibility delegate 23359 * is overriding a method introduced in a later API version than the minimal API 23360 * version supported by the application. For example, the method 23361 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23362 * in API version 4 when the accessibility APIs were first introduced. If a 23363 * developer would like his application to run on API version 4 devices (assuming 23364 * all other APIs used by the application are version 4 or lower) and take advantage 23365 * of this method, instead of overriding the method which would break the application's 23366 * backwards compatibility, he can override the corresponding method in this 23367 * delegate and register the delegate in the target View if the API version of 23368 * the system is high enough, i.e. the API version is the same as or higher than the API 23369 * version that introduced 23370 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23371 * </p> 23372 * <p> 23373 * Here is an example implementation: 23374 * </p> 23375 * <code><pre><p> 23376 * if (Build.VERSION.SDK_INT >= 14) { 23377 * // If the API version is equal of higher than the version in 23378 * // which onInitializeAccessibilityNodeInfo was introduced we 23379 * // register a delegate with a customized implementation. 23380 * View view = findViewById(R.id.view_id); 23381 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23382 * public void onInitializeAccessibilityNodeInfo(View host, 23383 * AccessibilityNodeInfo info) { 23384 * // Let the default implementation populate the info. 23385 * super.onInitializeAccessibilityNodeInfo(host, info); 23386 * // Set some other information. 23387 * info.setEnabled(host.isEnabled()); 23388 * } 23389 * }); 23390 * } 23391 * </code></pre></p> 23392 * <p> 23393 * This delegate contains methods that correspond to the accessibility methods 23394 * in View. If a delegate has been specified the implementation in View hands 23395 * off handling to the corresponding method in this delegate. The default 23396 * implementation the delegate methods behaves exactly as the corresponding 23397 * method in View for the case of no accessibility delegate been set. Hence, 23398 * to customize the behavior of a View method, clients can override only the 23399 * corresponding delegate method without altering the behavior of the rest 23400 * accessibility related methods of the host view. 23401 * </p> 23402 * <p> 23403 * <strong>Note:</strong> On platform versions prior to 23404 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23405 * views in the {@code android.widget.*} package are called <i>before</i> 23406 * host methods. This prevents certain properties such as class name from 23407 * being modified by overriding 23408 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23409 * as any changes will be overwritten by the host class. 23410 * <p> 23411 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23412 * methods are called <i>after</i> host methods, which all properties to be 23413 * modified without being overwritten by the host class. 23414 */ 23415 public static class AccessibilityDelegate { 23416 23417 /** 23418 * Sends an accessibility event of the given type. If accessibility is not 23419 * enabled this method has no effect. 23420 * <p> 23421 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23422 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23423 * been set. 23424 * </p> 23425 * 23426 * @param host The View hosting the delegate. 23427 * @param eventType The type of the event to send. 23428 * 23429 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23430 */ 23431 public void sendAccessibilityEvent(View host, int eventType) { 23432 host.sendAccessibilityEventInternal(eventType); 23433 } 23434 23435 /** 23436 * Performs the specified accessibility action on the view. For 23437 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23438 * <p> 23439 * The default implementation behaves as 23440 * {@link View#performAccessibilityAction(int, Bundle) 23441 * View#performAccessibilityAction(int, Bundle)} for the case of 23442 * no accessibility delegate been set. 23443 * </p> 23444 * 23445 * @param action The action to perform. 23446 * @return Whether the action was performed. 23447 * 23448 * @see View#performAccessibilityAction(int, Bundle) 23449 * View#performAccessibilityAction(int, Bundle) 23450 */ 23451 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23452 return host.performAccessibilityActionInternal(action, args); 23453 } 23454 23455 /** 23456 * Sends an accessibility event. This method behaves exactly as 23457 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23458 * empty {@link AccessibilityEvent} and does not perform a check whether 23459 * accessibility is enabled. 23460 * <p> 23461 * The default implementation behaves as 23462 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23463 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23464 * the case of no accessibility delegate been set. 23465 * </p> 23466 * 23467 * @param host The View hosting the delegate. 23468 * @param event The event to send. 23469 * 23470 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23471 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23472 */ 23473 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23474 host.sendAccessibilityEventUncheckedInternal(event); 23475 } 23476 23477 /** 23478 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23479 * to its children for adding their text content to the event. 23480 * <p> 23481 * The default implementation behaves as 23482 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23483 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23484 * the case of no accessibility delegate been set. 23485 * </p> 23486 * 23487 * @param host The View hosting the delegate. 23488 * @param event The event. 23489 * @return True if the event population was completed. 23490 * 23491 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23492 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23493 */ 23494 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23495 return host.dispatchPopulateAccessibilityEventInternal(event); 23496 } 23497 23498 /** 23499 * Gives a chance to the host View to populate the accessibility event with its 23500 * text content. 23501 * <p> 23502 * The default implementation behaves as 23503 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23504 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23505 * the case of no accessibility delegate been set. 23506 * </p> 23507 * 23508 * @param host The View hosting the delegate. 23509 * @param event The accessibility event which to populate. 23510 * 23511 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23512 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23513 */ 23514 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23515 host.onPopulateAccessibilityEventInternal(event); 23516 } 23517 23518 /** 23519 * Initializes an {@link AccessibilityEvent} with information about the 23520 * the host View which is the event source. 23521 * <p> 23522 * The default implementation behaves as 23523 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23524 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23525 * the case of no accessibility delegate been set. 23526 * </p> 23527 * 23528 * @param host The View hosting the delegate. 23529 * @param event The event to initialize. 23530 * 23531 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23532 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23533 */ 23534 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23535 host.onInitializeAccessibilityEventInternal(event); 23536 } 23537 23538 /** 23539 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23540 * <p> 23541 * The default implementation behaves as 23542 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23543 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23544 * the case of no accessibility delegate been set. 23545 * </p> 23546 * 23547 * @param host The View hosting the delegate. 23548 * @param info The instance to initialize. 23549 * 23550 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23551 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23552 */ 23553 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23554 host.onInitializeAccessibilityNodeInfoInternal(info); 23555 } 23556 23557 /** 23558 * Called when a child of the host View has requested sending an 23559 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23560 * to augment the event. 23561 * <p> 23562 * The default implementation behaves as 23563 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23564 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23565 * the case of no accessibility delegate been set. 23566 * </p> 23567 * 23568 * @param host The View hosting the delegate. 23569 * @param child The child which requests sending the event. 23570 * @param event The event to be sent. 23571 * @return True if the event should be sent 23572 * 23573 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23574 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23575 */ 23576 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23577 AccessibilityEvent event) { 23578 return host.onRequestSendAccessibilityEventInternal(child, event); 23579 } 23580 23581 /** 23582 * Gets the provider for managing a virtual view hierarchy rooted at this View 23583 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23584 * that explore the window content. 23585 * <p> 23586 * The default implementation behaves as 23587 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23588 * the case of no accessibility delegate been set. 23589 * </p> 23590 * 23591 * @return The provider. 23592 * 23593 * @see AccessibilityNodeProvider 23594 */ 23595 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23596 return null; 23597 } 23598 23599 /** 23600 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23601 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23602 * This method is responsible for obtaining an accessibility node info from a 23603 * pool of reusable instances and calling 23604 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23605 * view to initialize the former. 23606 * <p> 23607 * <strong>Note:</strong> The client is responsible for recycling the obtained 23608 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23609 * creation. 23610 * </p> 23611 * <p> 23612 * The default implementation behaves as 23613 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23614 * the case of no accessibility delegate been set. 23615 * </p> 23616 * @return A populated {@link AccessibilityNodeInfo}. 23617 * 23618 * @see AccessibilityNodeInfo 23619 * 23620 * @hide 23621 */ 23622 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23623 return host.createAccessibilityNodeInfoInternal(); 23624 } 23625 } 23626 23627 private class MatchIdPredicate implements Predicate<View> { 23628 public int mId; 23629 23630 @Override 23631 public boolean apply(View view) { 23632 return (view.mID == mId); 23633 } 23634 } 23635 23636 private class MatchLabelForPredicate implements Predicate<View> { 23637 private int mLabeledId; 23638 23639 @Override 23640 public boolean apply(View view) { 23641 return (view.mLabelForId == mLabeledId); 23642 } 23643 } 23644 23645 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23646 private int mChangeTypes = 0; 23647 private boolean mPosted; 23648 private boolean mPostedWithDelay; 23649 private long mLastEventTimeMillis; 23650 23651 @Override 23652 public void run() { 23653 mPosted = false; 23654 mPostedWithDelay = false; 23655 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23656 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23657 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23658 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23659 event.setContentChangeTypes(mChangeTypes); 23660 sendAccessibilityEventUnchecked(event); 23661 } 23662 mChangeTypes = 0; 23663 } 23664 23665 public void runOrPost(int changeType) { 23666 mChangeTypes |= changeType; 23667 23668 // If this is a live region or the child of a live region, collect 23669 // all events from this frame and send them on the next frame. 23670 if (inLiveRegion()) { 23671 // If we're already posted with a delay, remove that. 23672 if (mPostedWithDelay) { 23673 removeCallbacks(this); 23674 mPostedWithDelay = false; 23675 } 23676 // Only post if we're not already posted. 23677 if (!mPosted) { 23678 post(this); 23679 mPosted = true; 23680 } 23681 return; 23682 } 23683 23684 if (mPosted) { 23685 return; 23686 } 23687 23688 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23689 final long minEventIntevalMillis = 23690 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23691 if (timeSinceLastMillis >= minEventIntevalMillis) { 23692 removeCallbacks(this); 23693 run(); 23694 } else { 23695 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23696 mPostedWithDelay = true; 23697 } 23698 } 23699 } 23700 23701 private boolean inLiveRegion() { 23702 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23703 return true; 23704 } 23705 23706 ViewParent parent = getParent(); 23707 while (parent instanceof View) { 23708 if (((View) parent).getAccessibilityLiveRegion() 23709 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23710 return true; 23711 } 23712 parent = parent.getParent(); 23713 } 23714 23715 return false; 23716 } 23717 23718 /** 23719 * Dump all private flags in readable format, useful for documentation and 23720 * sanity checking. 23721 */ 23722 private static void dumpFlags() { 23723 final HashMap<String, String> found = Maps.newHashMap(); 23724 try { 23725 for (Field field : View.class.getDeclaredFields()) { 23726 final int modifiers = field.getModifiers(); 23727 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23728 if (field.getType().equals(int.class)) { 23729 final int value = field.getInt(null); 23730 dumpFlag(found, field.getName(), value); 23731 } else if (field.getType().equals(int[].class)) { 23732 final int[] values = (int[]) field.get(null); 23733 for (int i = 0; i < values.length; i++) { 23734 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23735 } 23736 } 23737 } 23738 } 23739 } catch (IllegalAccessException e) { 23740 throw new RuntimeException(e); 23741 } 23742 23743 final ArrayList<String> keys = Lists.newArrayList(); 23744 keys.addAll(found.keySet()); 23745 Collections.sort(keys); 23746 for (String key : keys) { 23747 Log.d(VIEW_LOG_TAG, found.get(key)); 23748 } 23749 } 23750 23751 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23752 // Sort flags by prefix, then by bits, always keeping unique keys 23753 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23754 final int prefix = name.indexOf('_'); 23755 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23756 final String output = bits + " " + name; 23757 found.put(key, output); 23758 } 23759 23760 /** {@hide} */ 23761 public void encode(@NonNull ViewHierarchyEncoder stream) { 23762 stream.beginObject(this); 23763 encodeProperties(stream); 23764 stream.endObject(); 23765 } 23766 23767 /** {@hide} */ 23768 @CallSuper 23769 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23770 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23771 if (resolveId instanceof String) { 23772 stream.addProperty("id", (String) resolveId); 23773 } else { 23774 stream.addProperty("id", mID); 23775 } 23776 23777 stream.addProperty("misc:transformation.alpha", 23778 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23779 stream.addProperty("misc:transitionName", getTransitionName()); 23780 23781 // layout 23782 stream.addProperty("layout:left", mLeft); 23783 stream.addProperty("layout:right", mRight); 23784 stream.addProperty("layout:top", mTop); 23785 stream.addProperty("layout:bottom", mBottom); 23786 stream.addProperty("layout:width", getWidth()); 23787 stream.addProperty("layout:height", getHeight()); 23788 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23789 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23790 stream.addProperty("layout:hasTransientState", hasTransientState()); 23791 stream.addProperty("layout:baseline", getBaseline()); 23792 23793 // layout params 23794 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23795 if (layoutParams != null) { 23796 stream.addPropertyKey("layoutParams"); 23797 layoutParams.encode(stream); 23798 } 23799 23800 // scrolling 23801 stream.addProperty("scrolling:scrollX", mScrollX); 23802 stream.addProperty("scrolling:scrollY", mScrollY); 23803 23804 // padding 23805 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23806 stream.addProperty("padding:paddingRight", mPaddingRight); 23807 stream.addProperty("padding:paddingTop", mPaddingTop); 23808 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23809 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23810 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23811 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23812 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23813 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23814 23815 // measurement 23816 stream.addProperty("measurement:minHeight", mMinHeight); 23817 stream.addProperty("measurement:minWidth", mMinWidth); 23818 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23819 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23820 23821 // drawing 23822 stream.addProperty("drawing:elevation", getElevation()); 23823 stream.addProperty("drawing:translationX", getTranslationX()); 23824 stream.addProperty("drawing:translationY", getTranslationY()); 23825 stream.addProperty("drawing:translationZ", getTranslationZ()); 23826 stream.addProperty("drawing:rotation", getRotation()); 23827 stream.addProperty("drawing:rotationX", getRotationX()); 23828 stream.addProperty("drawing:rotationY", getRotationY()); 23829 stream.addProperty("drawing:scaleX", getScaleX()); 23830 stream.addProperty("drawing:scaleY", getScaleY()); 23831 stream.addProperty("drawing:pivotX", getPivotX()); 23832 stream.addProperty("drawing:pivotY", getPivotY()); 23833 stream.addProperty("drawing:opaque", isOpaque()); 23834 stream.addProperty("drawing:alpha", getAlpha()); 23835 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23836 stream.addProperty("drawing:shadow", hasShadow()); 23837 stream.addProperty("drawing:solidColor", getSolidColor()); 23838 stream.addProperty("drawing:layerType", mLayerType); 23839 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23840 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23841 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23842 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23843 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23844 23845 // focus 23846 stream.addProperty("focus:hasFocus", hasFocus()); 23847 stream.addProperty("focus:isFocused", isFocused()); 23848 stream.addProperty("focus:isFocusable", isFocusable()); 23849 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23850 23851 stream.addProperty("misc:clickable", isClickable()); 23852 stream.addProperty("misc:pressed", isPressed()); 23853 stream.addProperty("misc:selected", isSelected()); 23854 stream.addProperty("misc:touchMode", isInTouchMode()); 23855 stream.addProperty("misc:hovered", isHovered()); 23856 stream.addProperty("misc:activated", isActivated()); 23857 23858 stream.addProperty("misc:visibility", getVisibility()); 23859 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23860 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23861 23862 stream.addProperty("misc:enabled", isEnabled()); 23863 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23864 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23865 23866 // theme attributes 23867 Resources.Theme theme = getContext().getTheme(); 23868 if (theme != null) { 23869 stream.addPropertyKey("theme"); 23870 theme.encode(stream); 23871 } 23872 23873 // view attribute information 23874 int n = mAttributes != null ? mAttributes.length : 0; 23875 stream.addProperty("meta:__attrCount__", n/2); 23876 for (int i = 0; i < n; i += 2) { 23877 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23878 } 23879 23880 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23881 23882 // text 23883 stream.addProperty("text:textDirection", getTextDirection()); 23884 stream.addProperty("text:textAlignment", getTextAlignment()); 23885 23886 // accessibility 23887 CharSequence contentDescription = getContentDescription(); 23888 stream.addProperty("accessibility:contentDescription", 23889 contentDescription == null ? "" : contentDescription.toString()); 23890 stream.addProperty("accessibility:labelFor", getLabelFor()); 23891 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23892 } 23893 23894 /** 23895 * Determine if this view is rendered on a round wearable device and is the main view 23896 * on the screen. 23897 */ 23898 private boolean shouldDrawRoundScrollbar() { 23899 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 23900 return false; 23901 } 23902 23903 final View rootView = getRootView(); 23904 final WindowInsets insets = getRootWindowInsets(); 23905 23906 int height = getHeight(); 23907 int width = getWidth(); 23908 int displayHeight = rootView.getHeight(); 23909 int displayWidth = rootView.getWidth(); 23910 23911 if (height != displayHeight || width != displayWidth) { 23912 return false; 23913 } 23914 23915 getLocationOnScreen(mAttachInfo.mTmpLocation); 23916 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 23917 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 23918 } 23919} 23920