View.java revision f0503b0b6fa7ad963dd4bb9b63eb5528b191bfea
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; 20import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; 21import static android.os.Build.VERSION_CODES.KITKAT; 22import static android.os.Build.VERSION_CODES.M; 23import static android.os.Build.VERSION_CODES.N; 24 25import static java.lang.Math.max; 26 27import android.animation.AnimatorInflater; 28import android.animation.StateListAnimator; 29import android.annotation.CallSuper; 30import android.annotation.ColorInt; 31import android.annotation.DrawableRes; 32import android.annotation.FloatRange; 33import android.annotation.IdRes; 34import android.annotation.IntDef; 35import android.annotation.IntRange; 36import android.annotation.LayoutRes; 37import android.annotation.NonNull; 38import android.annotation.Nullable; 39import android.annotation.Size; 40import android.annotation.UiThread; 41import android.content.ClipData; 42import android.content.Context; 43import android.content.ContextWrapper; 44import android.content.Intent; 45import android.content.res.ColorStateList; 46import android.content.res.Configuration; 47import android.content.res.Resources; 48import android.content.res.TypedArray; 49import android.graphics.Bitmap; 50import android.graphics.Canvas; 51import android.graphics.Color; 52import android.graphics.Insets; 53import android.graphics.Interpolator; 54import android.graphics.LinearGradient; 55import android.graphics.Matrix; 56import android.graphics.Outline; 57import android.graphics.Paint; 58import android.graphics.PixelFormat; 59import android.graphics.Point; 60import android.graphics.PorterDuff; 61import android.graphics.PorterDuffXfermode; 62import android.graphics.Rect; 63import android.graphics.RectF; 64import android.graphics.Region; 65import android.graphics.Shader; 66import android.graphics.drawable.ColorDrawable; 67import android.graphics.drawable.Drawable; 68import android.hardware.display.DisplayManagerGlobal; 69import android.os.Build.VERSION_CODES; 70import android.os.Bundle; 71import android.os.Handler; 72import android.os.IBinder; 73import android.os.Parcel; 74import android.os.Parcelable; 75import android.os.RemoteException; 76import android.os.SystemClock; 77import android.os.SystemProperties; 78import android.os.Trace; 79import android.text.TextUtils; 80import android.util.AttributeSet; 81import android.util.FloatProperty; 82import android.util.LayoutDirection; 83import android.util.Log; 84import android.util.LongSparseLongArray; 85import android.util.Pools.SynchronizedPool; 86import android.util.Property; 87import android.util.SparseArray; 88import android.util.StateSet; 89import android.util.SuperNotCalledException; 90import android.util.TypedValue; 91import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 92import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 93import android.view.AccessibilityIterators.TextSegmentIterator; 94import android.view.AccessibilityIterators.WordTextSegmentIterator; 95import android.view.ContextMenu.ContextMenuInfo; 96import android.view.accessibility.AccessibilityEvent; 97import android.view.accessibility.AccessibilityEventSource; 98import android.view.accessibility.AccessibilityManager; 99import android.view.accessibility.AccessibilityNodeInfo; 100import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 101import android.view.accessibility.AccessibilityNodeProvider; 102import android.view.animation.Animation; 103import android.view.animation.AnimationUtils; 104import android.view.animation.Transformation; 105import android.view.inputmethod.EditorInfo; 106import android.view.inputmethod.InputConnection; 107import android.view.inputmethod.InputMethodManager; 108import android.widget.Checkable; 109import android.widget.FrameLayout; 110import android.widget.ScrollBarDrawable; 111 112import com.android.internal.R; 113import com.android.internal.util.Predicate; 114import com.android.internal.view.menu.MenuBuilder; 115import com.android.internal.widget.ScrollBarUtils; 116 117import com.google.android.collect.Lists; 118import com.google.android.collect.Maps; 119 120import java.lang.annotation.Retention; 121import java.lang.annotation.RetentionPolicy; 122import java.lang.ref.WeakReference; 123import java.lang.reflect.Field; 124import java.lang.reflect.InvocationTargetException; 125import java.lang.reflect.Method; 126import java.lang.reflect.Modifier; 127import java.util.ArrayList; 128import java.util.Arrays; 129import java.util.Collections; 130import java.util.HashMap; 131import java.util.List; 132import java.util.Locale; 133import java.util.Map; 134import java.util.concurrent.CopyOnWriteArrayList; 135import java.util.concurrent.atomic.AtomicInteger; 136 137/** 138 * <p> 139 * This class represents the basic building block for user interface components. A View 140 * occupies a rectangular area on the screen and is responsible for drawing and 141 * event handling. View is the base class for <em>widgets</em>, which are 142 * used to create interactive UI components (buttons, text fields, etc.). The 143 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 144 * are invisible containers that hold other Views (or other ViewGroups) and define 145 * their layout properties. 146 * </p> 147 * 148 * <div class="special reference"> 149 * <h3>Developer Guides</h3> 150 * <p>For information about using this class to develop your application's user interface, 151 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 152 * </div> 153 * 154 * <a name="Using"></a> 155 * <h3>Using Views</h3> 156 * <p> 157 * All of the views in a window are arranged in a single tree. You can add views 158 * either from code or by specifying a tree of views in one or more XML layout 159 * files. There are many specialized subclasses of views that act as controls or 160 * are capable of displaying text, images, or other content. 161 * </p> 162 * <p> 163 * Once you have created a tree of views, there are typically a few types of 164 * common operations you may wish to perform: 165 * <ul> 166 * <li><strong>Set properties:</strong> for example setting the text of a 167 * {@link android.widget.TextView}. The available properties and the methods 168 * that set them will vary among the different subclasses of views. Note that 169 * properties that are known at build time can be set in the XML layout 170 * files.</li> 171 * <li><strong>Set focus:</strong> The framework will handle moving focus in 172 * response to user input. To force focus to a specific view, call 173 * {@link #requestFocus}.</li> 174 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 175 * that will be notified when something interesting happens to the view. For 176 * example, all views will let you set a listener to be notified when the view 177 * gains or loses focus. You can register such a listener using 178 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 179 * Other view subclasses offer more specialized listeners. For example, a Button 180 * exposes a listener to notify clients when the button is clicked.</li> 181 * <li><strong>Set visibility:</strong> You can hide or show views using 182 * {@link #setVisibility(int)}.</li> 183 * </ul> 184 * </p> 185 * <p><em> 186 * Note: The Android framework is responsible for measuring, laying out and 187 * drawing views. You should not call methods that perform these actions on 188 * views yourself unless you are actually implementing a 189 * {@link android.view.ViewGroup}. 190 * </em></p> 191 * 192 * <a name="Lifecycle"></a> 193 * <h3>Implementing a Custom View</h3> 194 * 195 * <p> 196 * To implement a custom view, you will usually begin by providing overrides for 197 * some of the standard methods that the framework calls on all views. You do 198 * not need to override all of these methods. In fact, you can start by just 199 * overriding {@link #onDraw(android.graphics.Canvas)}. 200 * <table border="2" width="85%" align="center" cellpadding="5"> 201 * <thead> 202 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 203 * </thead> 204 * 205 * <tbody> 206 * <tr> 207 * <td rowspan="2">Creation</td> 208 * <td>Constructors</td> 209 * <td>There is a form of the constructor that are called when the view 210 * is created from code and a form that is called when the view is 211 * inflated from a layout file. The second form should parse and apply 212 * any attributes defined in the layout file. 213 * </td> 214 * </tr> 215 * <tr> 216 * <td><code>{@link #onFinishInflate()}</code></td> 217 * <td>Called after a view and all of its children has been inflated 218 * from XML.</td> 219 * </tr> 220 * 221 * <tr> 222 * <td rowspan="3">Layout</td> 223 * <td><code>{@link #onMeasure(int, int)}</code></td> 224 * <td>Called to determine the size requirements for this view and all 225 * of its children. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 230 * <td>Called when this view should assign a size and position to all 231 * of its children. 232 * </td> 233 * </tr> 234 * <tr> 235 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 236 * <td>Called when the size of this view has changed. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td>Drawing</td> 242 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 243 * <td>Called when the view should render its content. 244 * </td> 245 * </tr> 246 * 247 * <tr> 248 * <td rowspan="4">Event processing</td> 249 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 250 * <td>Called when a new hardware key event occurs. 251 * </td> 252 * </tr> 253 * <tr> 254 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 255 * <td>Called when a hardware key up event occurs. 256 * </td> 257 * </tr> 258 * <tr> 259 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 260 * <td>Called when a trackball motion event occurs. 261 * </td> 262 * </tr> 263 * <tr> 264 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 265 * <td>Called when a touch screen motion event occurs. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td rowspan="2">Focus</td> 271 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 272 * <td>Called when the view gains or loses focus. 273 * </td> 274 * </tr> 275 * 276 * <tr> 277 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 278 * <td>Called when the window containing the view gains or loses focus. 279 * </td> 280 * </tr> 281 * 282 * <tr> 283 * <td rowspan="3">Attaching</td> 284 * <td><code>{@link #onAttachedToWindow()}</code></td> 285 * <td>Called when the view is attached to a window. 286 * </td> 287 * </tr> 288 * 289 * <tr> 290 * <td><code>{@link #onDetachedFromWindow}</code></td> 291 * <td>Called when the view is detached from its window. 292 * </td> 293 * </tr> 294 * 295 * <tr> 296 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 297 * <td>Called when the visibility of the window containing the view 298 * has changed. 299 * </td> 300 * </tr> 301 * </tbody> 302 * 303 * </table> 304 * </p> 305 * 306 * <a name="IDs"></a> 307 * <h3>IDs</h3> 308 * Views may have an integer id associated with them. These ids are typically 309 * assigned in the layout XML files, and are used to find specific views within 310 * the view tree. A common pattern is to: 311 * <ul> 312 * <li>Define a Button in the layout file and assign it a unique ID. 313 * <pre> 314 * <Button 315 * android:id="@+id/my_button" 316 * android:layout_width="wrap_content" 317 * android:layout_height="wrap_content" 318 * android:text="@string/my_button_text"/> 319 * </pre></li> 320 * <li>From the onCreate method of an Activity, find the Button 321 * <pre class="prettyprint"> 322 * Button myButton = (Button) findViewById(R.id.my_button); 323 * </pre></li> 324 * </ul> 325 * <p> 326 * View IDs need not be unique throughout the tree, but it is good practice to 327 * ensure that they are at least unique within the part of the tree you are 328 * searching. 329 * </p> 330 * 331 * <a name="Position"></a> 332 * <h3>Position</h3> 333 * <p> 334 * The geometry of a view is that of a rectangle. A view has a location, 335 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 336 * two dimensions, expressed as a width and a height. The unit for location 337 * and dimensions is the pixel. 338 * </p> 339 * 340 * <p> 341 * It is possible to retrieve the location of a view by invoking the methods 342 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 343 * coordinate of the rectangle representing the view. The latter returns the 344 * top, or Y, coordinate of the rectangle representing the view. These methods 345 * both return the location of the view relative to its parent. For instance, 346 * when getLeft() returns 20, that means the view is located 20 pixels to the 347 * right of the left edge of its direct parent. 348 * </p> 349 * 350 * <p> 351 * In addition, several convenience methods are offered to avoid unnecessary 352 * computations, namely {@link #getRight()} and {@link #getBottom()}. 353 * These methods return the coordinates of the right and bottom edges of the 354 * rectangle representing the view. For instance, calling {@link #getRight()} 355 * is similar to the following computation: <code>getLeft() + getWidth()</code> 356 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 357 * </p> 358 * 359 * <a name="SizePaddingMargins"></a> 360 * <h3>Size, padding and margins</h3> 361 * <p> 362 * The size of a view is expressed with a width and a height. A view actually 363 * possess two pairs of width and height values. 364 * </p> 365 * 366 * <p> 367 * The first pair is known as <em>measured width</em> and 368 * <em>measured height</em>. These dimensions define how big a view wants to be 369 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 370 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 371 * and {@link #getMeasuredHeight()}. 372 * </p> 373 * 374 * <p> 375 * The second pair is simply known as <em>width</em> and <em>height</em>, or 376 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 377 * dimensions define the actual size of the view on screen, at drawing time and 378 * after layout. These values may, but do not have to, be different from the 379 * measured width and height. The width and height can be obtained by calling 380 * {@link #getWidth()} and {@link #getHeight()}. 381 * </p> 382 * 383 * <p> 384 * To measure its dimensions, a view takes into account its padding. The padding 385 * is expressed in pixels for the left, top, right and bottom parts of the view. 386 * Padding can be used to offset the content of the view by a specific amount of 387 * pixels. For instance, a left padding of 2 will push the view's content by 388 * 2 pixels to the right of the left edge. Padding can be set using the 389 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 390 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 391 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 392 * {@link #getPaddingEnd()}. 393 * </p> 394 * 395 * <p> 396 * Even though a view can define a padding, it does not provide any support for 397 * margins. However, view groups provide such a support. Refer to 398 * {@link android.view.ViewGroup} and 399 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 400 * </p> 401 * 402 * <a name="Layout"></a> 403 * <h3>Layout</h3> 404 * <p> 405 * Layout is a two pass process: a measure pass and a layout pass. The measuring 406 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 407 * of the view tree. Each view pushes dimension specifications down the tree 408 * during the recursion. At the end of the measure pass, every view has stored 409 * its measurements. The second pass happens in 410 * {@link #layout(int,int,int,int)} and is also top-down. During 411 * this pass each parent is responsible for positioning all of its children 412 * using the sizes computed in the measure pass. 413 * </p> 414 * 415 * <p> 416 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 417 * {@link #getMeasuredHeight()} values must be set, along with those for all of 418 * that view's descendants. A view's measured width and measured height values 419 * must respect the constraints imposed by the view's parents. This guarantees 420 * that at the end of the measure pass, all parents accept all of their 421 * children's measurements. A parent view may call measure() more than once on 422 * its children. For example, the parent may measure each child once with 423 * unspecified dimensions to find out how big they want to be, then call 424 * measure() on them again with actual numbers if the sum of all the children's 425 * unconstrained sizes is too big or too small. 426 * </p> 427 * 428 * <p> 429 * The measure pass uses two classes to communicate dimensions. The 430 * {@link MeasureSpec} class is used by views to tell their parents how they 431 * want to be measured and positioned. The base LayoutParams class just 432 * describes how big the view wants to be for both width and height. For each 433 * dimension, it can specify one of: 434 * <ul> 435 * <li> an exact number 436 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 437 * (minus padding) 438 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 439 * enclose its content (plus padding). 440 * </ul> 441 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 442 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 443 * an X and Y value. 444 * </p> 445 * 446 * <p> 447 * MeasureSpecs are used to push requirements down the tree from parent to 448 * child. A MeasureSpec can be in one of three modes: 449 * <ul> 450 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 451 * of a child view. For example, a LinearLayout may call measure() on its child 452 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 453 * tall the child view wants to be given a width of 240 pixels. 454 * <li>EXACTLY: This is used by the parent to impose an exact size on the 455 * child. The child must use this size, and guarantee that all of its 456 * descendants will fit within this size. 457 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 458 * child. The child must guarantee that it and all of its descendants will fit 459 * within this size. 460 * </ul> 461 * </p> 462 * 463 * <p> 464 * To initiate a layout, call {@link #requestLayout}. This method is typically 465 * called by a view on itself when it believes that is can no longer fit within 466 * its current bounds. 467 * </p> 468 * 469 * <a name="Drawing"></a> 470 * <h3>Drawing</h3> 471 * <p> 472 * Drawing is handled by walking the tree and recording the drawing commands of 473 * any View that needs to update. After this, the drawing commands of the 474 * entire tree are issued to screen, clipped to the newly damaged area. 475 * </p> 476 * 477 * <p> 478 * The tree is largely recorded and drawn in order, with parents drawn before 479 * (i.e., behind) their children, with siblings drawn in the order they appear 480 * in the tree. If you set a background drawable for a View, then the View will 481 * draw it before calling back to its <code>onDraw()</code> method. The child 482 * drawing order can be overridden with 483 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 484 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 485 * </p> 486 * 487 * <p> 488 * To force a view to draw, call {@link #invalidate()}. 489 * </p> 490 * 491 * <a name="EventHandlingThreading"></a> 492 * <h3>Event Handling and Threading</h3> 493 * <p> 494 * The basic cycle of a view is as follows: 495 * <ol> 496 * <li>An event comes in and is dispatched to the appropriate view. The view 497 * handles the event and notifies any listeners.</li> 498 * <li>If in the course of processing the event, the view's bounds may need 499 * to be changed, the view will call {@link #requestLayout()}.</li> 500 * <li>Similarly, if in the course of processing the event the view's appearance 501 * may need to be changed, the view will call {@link #invalidate()}.</li> 502 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 503 * the framework will take care of measuring, laying out, and drawing the tree 504 * as appropriate.</li> 505 * </ol> 506 * </p> 507 * 508 * <p><em>Note: The entire view tree is single threaded. You must always be on 509 * the UI thread when calling any method on any view.</em> 510 * If you are doing work on other threads and want to update the state of a view 511 * from that thread, you should use a {@link Handler}. 512 * </p> 513 * 514 * <a name="FocusHandling"></a> 515 * <h3>Focus Handling</h3> 516 * <p> 517 * The framework will handle routine focus movement in response to user input. 518 * This includes changing the focus as views are removed or hidden, or as new 519 * views become available. Views indicate their willingness to take focus 520 * through the {@link #isFocusable} method. To change whether a view can take 521 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 522 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 523 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 524 * </p> 525 * <p> 526 * Focus movement is based on an algorithm which finds the nearest neighbor in a 527 * given direction. In rare cases, the default algorithm may not match the 528 * intended behavior of the developer. In these situations, you can provide 529 * explicit overrides by using these XML attributes in the layout file: 530 * <pre> 531 * nextFocusDown 532 * nextFocusLeft 533 * nextFocusRight 534 * nextFocusUp 535 * </pre> 536 * </p> 537 * 538 * 539 * <p> 540 * To get a particular view to take focus, call {@link #requestFocus()}. 541 * </p> 542 * 543 * <a name="TouchMode"></a> 544 * <h3>Touch Mode</h3> 545 * <p> 546 * When a user is navigating a user interface via directional keys such as a D-pad, it is 547 * necessary to give focus to actionable items such as buttons so the user can see 548 * what will take input. If the device has touch capabilities, however, and the user 549 * begins interacting with the interface by touching it, it is no longer necessary to 550 * always highlight, or give focus to, a particular view. This motivates a mode 551 * for interaction named 'touch mode'. 552 * </p> 553 * <p> 554 * For a touch capable device, once the user touches the screen, the device 555 * will enter touch mode. From this point onward, only views for which 556 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 557 * Other views that are touchable, like buttons, will not take focus when touched; they will 558 * only fire the on click listeners. 559 * </p> 560 * <p> 561 * Any time a user hits a directional key, such as a D-pad direction, the view device will 562 * exit touch mode, and find a view to take focus, so that the user may resume interacting 563 * with the user interface without touching the screen again. 564 * </p> 565 * <p> 566 * The touch mode state is maintained across {@link android.app.Activity}s. Call 567 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 568 * </p> 569 * 570 * <a name="Scrolling"></a> 571 * <h3>Scrolling</h3> 572 * <p> 573 * The framework provides basic support for views that wish to internally 574 * scroll their content. This includes keeping track of the X and Y scroll 575 * offset as well as mechanisms for drawing scrollbars. See 576 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 577 * {@link #awakenScrollBars()} for more details. 578 * </p> 579 * 580 * <a name="Tags"></a> 581 * <h3>Tags</h3> 582 * <p> 583 * Unlike IDs, tags are not used to identify views. Tags are essentially an 584 * extra piece of information that can be associated with a view. They are most 585 * often used as a convenience to store data related to views in the views 586 * themselves rather than by putting them in a separate structure. 587 * </p> 588 * <p> 589 * Tags may be specified with character sequence values in layout XML as either 590 * a single tag using the {@link android.R.styleable#View_tag android:tag} 591 * attribute or multiple tags using the {@code <tag>} child element: 592 * <pre> 593 * <View ... 594 * android:tag="@string/mytag_value" /> 595 * <View ...> 596 * <tag android:id="@+id/mytag" 597 * android:value="@string/mytag_value" /> 598 * </View> 599 * </pre> 600 * </p> 601 * <p> 602 * Tags may also be specified with arbitrary objects from code using 603 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 604 * </p> 605 * 606 * <a name="Themes"></a> 607 * <h3>Themes</h3> 608 * <p> 609 * By default, Views are created using the theme of the Context object supplied 610 * to their constructor; however, a different theme may be specified by using 611 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 612 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 613 * code. 614 * </p> 615 * <p> 616 * When the {@link android.R.styleable#View_theme android:theme} attribute is 617 * used in XML, the specified theme is applied on top of the inflation 618 * context's theme (see {@link LayoutInflater}) and used for the view itself as 619 * well as any child elements. 620 * </p> 621 * <p> 622 * In the following example, both views will be created using the Material dark 623 * color scheme; however, because an overlay theme is used which only defines a 624 * subset of attributes, the value of 625 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 626 * the inflation context's theme (e.g. the Activity theme) will be preserved. 627 * <pre> 628 * <LinearLayout 629 * ... 630 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 631 * <View ...> 632 * </LinearLayout> 633 * </pre> 634 * </p> 635 * 636 * <a name="Properties"></a> 637 * <h3>Properties</h3> 638 * <p> 639 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 640 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 641 * available both in the {@link Property} form as well as in similarly-named setter/getter 642 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 643 * be used to set persistent state associated with these rendering-related properties on the view. 644 * The properties and methods can also be used in conjunction with 645 * {@link android.animation.Animator Animator}-based animations, described more in the 646 * <a href="#Animation">Animation</a> section. 647 * </p> 648 * 649 * <a name="Animation"></a> 650 * <h3>Animation</h3> 651 * <p> 652 * Starting with Android 3.0, the preferred way of animating views is to use the 653 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 654 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 655 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 656 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 657 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 658 * makes animating these View properties particularly easy and efficient. 659 * </p> 660 * <p> 661 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 662 * You can attach an {@link Animation} object to a view using 663 * {@link #setAnimation(Animation)} or 664 * {@link #startAnimation(Animation)}. The animation can alter the scale, 665 * rotation, translation and alpha of a view over time. If the animation is 666 * attached to a view that has children, the animation will affect the entire 667 * subtree rooted by that node. When an animation is started, the framework will 668 * take care of redrawing the appropriate views until the animation completes. 669 * </p> 670 * 671 * <a name="Security"></a> 672 * <h3>Security</h3> 673 * <p> 674 * Sometimes it is essential that an application be able to verify that an action 675 * is being performed with the full knowledge and consent of the user, such as 676 * granting a permission request, making a purchase or clicking on an advertisement. 677 * Unfortunately, a malicious application could try to spoof the user into 678 * performing these actions, unaware, by concealing the intended purpose of the view. 679 * As a remedy, the framework offers a touch filtering mechanism that can be used to 680 * improve the security of views that provide access to sensitive functionality. 681 * </p><p> 682 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 683 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 684 * will discard touches that are received whenever the view's window is obscured by 685 * another visible window. As a result, the view will not receive touches whenever a 686 * toast, dialog or other window appears above the view's window. 687 * </p><p> 688 * For more fine-grained control over security, consider overriding the 689 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 690 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 691 * </p> 692 * 693 * @attr ref android.R.styleable#View_alpha 694 * @attr ref android.R.styleable#View_background 695 * @attr ref android.R.styleable#View_clickable 696 * @attr ref android.R.styleable#View_contentDescription 697 * @attr ref android.R.styleable#View_drawingCacheQuality 698 * @attr ref android.R.styleable#View_duplicateParentState 699 * @attr ref android.R.styleable#View_id 700 * @attr ref android.R.styleable#View_requiresFadingEdge 701 * @attr ref android.R.styleable#View_fadeScrollbars 702 * @attr ref android.R.styleable#View_fadingEdgeLength 703 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 704 * @attr ref android.R.styleable#View_fitsSystemWindows 705 * @attr ref android.R.styleable#View_isScrollContainer 706 * @attr ref android.R.styleable#View_focusable 707 * @attr ref android.R.styleable#View_focusableInTouchMode 708 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 709 * @attr ref android.R.styleable#View_keepScreenOn 710 * @attr ref android.R.styleable#View_layerType 711 * @attr ref android.R.styleable#View_layoutDirection 712 * @attr ref android.R.styleable#View_longClickable 713 * @attr ref android.R.styleable#View_minHeight 714 * @attr ref android.R.styleable#View_minWidth 715 * @attr ref android.R.styleable#View_nextFocusDown 716 * @attr ref android.R.styleable#View_nextFocusLeft 717 * @attr ref android.R.styleable#View_nextFocusRight 718 * @attr ref android.R.styleable#View_nextFocusUp 719 * @attr ref android.R.styleable#View_onClick 720 * @attr ref android.R.styleable#View_padding 721 * @attr ref android.R.styleable#View_paddingBottom 722 * @attr ref android.R.styleable#View_paddingLeft 723 * @attr ref android.R.styleable#View_paddingRight 724 * @attr ref android.R.styleable#View_paddingTop 725 * @attr ref android.R.styleable#View_paddingStart 726 * @attr ref android.R.styleable#View_paddingEnd 727 * @attr ref android.R.styleable#View_saveEnabled 728 * @attr ref android.R.styleable#View_rotation 729 * @attr ref android.R.styleable#View_rotationX 730 * @attr ref android.R.styleable#View_rotationY 731 * @attr ref android.R.styleable#View_scaleX 732 * @attr ref android.R.styleable#View_scaleY 733 * @attr ref android.R.styleable#View_scrollX 734 * @attr ref android.R.styleable#View_scrollY 735 * @attr ref android.R.styleable#View_scrollbarSize 736 * @attr ref android.R.styleable#View_scrollbarStyle 737 * @attr ref android.R.styleable#View_scrollbars 738 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 739 * @attr ref android.R.styleable#View_scrollbarFadeDuration 740 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 741 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 742 * @attr ref android.R.styleable#View_scrollbarThumbVertical 743 * @attr ref android.R.styleable#View_scrollbarTrackVertical 744 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 745 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 746 * @attr ref android.R.styleable#View_stateListAnimator 747 * @attr ref android.R.styleable#View_transitionName 748 * @attr ref android.R.styleable#View_soundEffectsEnabled 749 * @attr ref android.R.styleable#View_tag 750 * @attr ref android.R.styleable#View_textAlignment 751 * @attr ref android.R.styleable#View_textDirection 752 * @attr ref android.R.styleable#View_transformPivotX 753 * @attr ref android.R.styleable#View_transformPivotY 754 * @attr ref android.R.styleable#View_translationX 755 * @attr ref android.R.styleable#View_translationY 756 * @attr ref android.R.styleable#View_translationZ 757 * @attr ref android.R.styleable#View_visibility 758 * @attr ref android.R.styleable#View_theme 759 * 760 * @see android.view.ViewGroup 761 */ 762@UiThread 763public class View implements Drawable.Callback, KeyEvent.Callback, 764 AccessibilityEventSource { 765 private static final boolean DBG = false; 766 767 /** @hide */ 768 public static boolean DEBUG_DRAW = false; 769 770 /** 771 * The logging tag used by this class with android.util.Log. 772 */ 773 protected static final String VIEW_LOG_TAG = "View"; 774 775 /** 776 * When set to true, apps will draw debugging information about their layouts. 777 * 778 * @hide 779 */ 780 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 781 782 /** 783 * When set to true, this view will save its attribute data. 784 * 785 * @hide 786 */ 787 public static boolean mDebugViewAttributes = false; 788 789 /** 790 * Used to mark a View that has no ID. 791 */ 792 public static final int NO_ID = -1; 793 794 /** 795 * Signals that compatibility booleans have been initialized according to 796 * target SDK versions. 797 */ 798 private static boolean sCompatibilityDone = false; 799 800 /** 801 * Use the old (broken) way of building MeasureSpecs. 802 */ 803 private static boolean sUseBrokenMakeMeasureSpec = false; 804 805 /** 806 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 807 */ 808 static boolean sUseZeroUnspecifiedMeasureSpec = false; 809 810 /** 811 * Ignore any optimizations using the measure cache. 812 */ 813 private static boolean sIgnoreMeasureCache = false; 814 815 /** 816 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 817 */ 818 private static boolean sAlwaysRemeasureExactly = false; 819 820 /** 821 * Relax constraints around whether setLayoutParams() must be called after 822 * modifying the layout params. 823 */ 824 private static boolean sLayoutParamsAlwaysChanged = false; 825 826 /** 827 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 828 * without throwing 829 */ 830 static boolean sTextureViewIgnoresDrawableSetters = false; 831 832 /** 833 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 834 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 835 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 836 * check is implemented for backwards compatibility. 837 * 838 * {@hide} 839 */ 840 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 841 842 /** 843 * Prior to N, when drag enters into child of a view that has already received an 844 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 845 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 846 * false from its event handler for these events. 847 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 848 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 849 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 850 */ 851 static boolean sCascadedDragDrop; 852 853 /** 854 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 855 * calling setFlags. 856 */ 857 private static final int NOT_FOCUSABLE = 0x00000000; 858 859 /** 860 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 861 * setFlags. 862 */ 863 private static final int FOCUSABLE = 0x00000001; 864 865 /** 866 * Mask for use with setFlags indicating bits used for focus. 867 */ 868 private static final int FOCUSABLE_MASK = 0x00000001; 869 870 /** 871 * This view will adjust its padding to fit sytem windows (e.g. status bar) 872 */ 873 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 874 875 /** @hide */ 876 @IntDef({VISIBLE, INVISIBLE, GONE}) 877 @Retention(RetentionPolicy.SOURCE) 878 public @interface Visibility {} 879 880 /** 881 * This view is visible. 882 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 883 * android:visibility}. 884 */ 885 public static final int VISIBLE = 0x00000000; 886 887 /** 888 * This view is invisible, but it still takes up space for layout purposes. 889 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 890 * android:visibility}. 891 */ 892 public static final int INVISIBLE = 0x00000004; 893 894 /** 895 * This view is invisible, and it doesn't take any space for layout 896 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 897 * android:visibility}. 898 */ 899 public static final int GONE = 0x00000008; 900 901 /** 902 * Mask for use with setFlags indicating bits used for visibility. 903 * {@hide} 904 */ 905 static final int VISIBILITY_MASK = 0x0000000C; 906 907 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 908 909 /** 910 * This view is enabled. Interpretation varies by subclass. 911 * Use with ENABLED_MASK when calling setFlags. 912 * {@hide} 913 */ 914 static final int ENABLED = 0x00000000; 915 916 /** 917 * This view is disabled. Interpretation varies by subclass. 918 * Use with ENABLED_MASK when calling setFlags. 919 * {@hide} 920 */ 921 static final int DISABLED = 0x00000020; 922 923 /** 924 * Mask for use with setFlags indicating bits used for indicating whether 925 * this view is enabled 926 * {@hide} 927 */ 928 static final int ENABLED_MASK = 0x00000020; 929 930 /** 931 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 932 * called and further optimizations will be performed. It is okay to have 933 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 934 * {@hide} 935 */ 936 static final int WILL_NOT_DRAW = 0x00000080; 937 938 /** 939 * Mask for use with setFlags indicating bits used for indicating whether 940 * this view is will draw 941 * {@hide} 942 */ 943 static final int DRAW_MASK = 0x00000080; 944 945 /** 946 * <p>This view doesn't show scrollbars.</p> 947 * {@hide} 948 */ 949 static final int SCROLLBARS_NONE = 0x00000000; 950 951 /** 952 * <p>This view shows horizontal scrollbars.</p> 953 * {@hide} 954 */ 955 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 956 957 /** 958 * <p>This view shows vertical scrollbars.</p> 959 * {@hide} 960 */ 961 static final int SCROLLBARS_VERTICAL = 0x00000200; 962 963 /** 964 * <p>Mask for use with setFlags indicating bits used for indicating which 965 * scrollbars are enabled.</p> 966 * {@hide} 967 */ 968 static final int SCROLLBARS_MASK = 0x00000300; 969 970 /** 971 * Indicates that the view should filter touches when its window is obscured. 972 * Refer to the class comments for more information about this security feature. 973 * {@hide} 974 */ 975 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 976 977 /** 978 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 979 * that they are optional and should be skipped if the window has 980 * requested system UI flags that ignore those insets for layout. 981 */ 982 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 983 984 /** 985 * <p>This view doesn't show fading edges.</p> 986 * {@hide} 987 */ 988 static final int FADING_EDGE_NONE = 0x00000000; 989 990 /** 991 * <p>This view shows horizontal fading edges.</p> 992 * {@hide} 993 */ 994 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 995 996 /** 997 * <p>This view shows vertical fading edges.</p> 998 * {@hide} 999 */ 1000 static final int FADING_EDGE_VERTICAL = 0x00002000; 1001 1002 /** 1003 * <p>Mask for use with setFlags indicating bits used for indicating which 1004 * fading edges are enabled.</p> 1005 * {@hide} 1006 */ 1007 static final int FADING_EDGE_MASK = 0x00003000; 1008 1009 /** 1010 * <p>Indicates this view can be clicked. When clickable, a View reacts 1011 * to clicks by notifying the OnClickListener.<p> 1012 * {@hide} 1013 */ 1014 static final int CLICKABLE = 0x00004000; 1015 1016 /** 1017 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1018 * {@hide} 1019 */ 1020 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1021 1022 /** 1023 * <p>Indicates that no icicle should be saved for this view.<p> 1024 * {@hide} 1025 */ 1026 static final int SAVE_DISABLED = 0x000010000; 1027 1028 /** 1029 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1030 * property.</p> 1031 * {@hide} 1032 */ 1033 static final int SAVE_DISABLED_MASK = 0x000010000; 1034 1035 /** 1036 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1037 * {@hide} 1038 */ 1039 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1040 1041 /** 1042 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1043 * {@hide} 1044 */ 1045 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1046 1047 /** @hide */ 1048 @Retention(RetentionPolicy.SOURCE) 1049 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1050 public @interface DrawingCacheQuality {} 1051 1052 /** 1053 * <p>Enables low quality mode for the drawing cache.</p> 1054 */ 1055 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1056 1057 /** 1058 * <p>Enables high quality mode for the drawing cache.</p> 1059 */ 1060 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1061 1062 /** 1063 * <p>Enables automatic quality mode for the drawing cache.</p> 1064 */ 1065 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1066 1067 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1068 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1069 }; 1070 1071 /** 1072 * <p>Mask for use with setFlags indicating bits used for the cache 1073 * quality property.</p> 1074 * {@hide} 1075 */ 1076 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1077 1078 /** 1079 * <p> 1080 * Indicates this view can be long clicked. When long clickable, a View 1081 * reacts to long clicks by notifying the OnLongClickListener or showing a 1082 * context menu. 1083 * </p> 1084 * {@hide} 1085 */ 1086 static final int LONG_CLICKABLE = 0x00200000; 1087 1088 /** 1089 * <p>Indicates that this view gets its drawable states from its direct parent 1090 * and ignores its original internal states.</p> 1091 * 1092 * @hide 1093 */ 1094 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1095 1096 /** 1097 * <p> 1098 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1099 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1100 * OnContextClickListener. 1101 * </p> 1102 * {@hide} 1103 */ 1104 static final int CONTEXT_CLICKABLE = 0x00800000; 1105 1106 1107 /** @hide */ 1108 @IntDef({ 1109 SCROLLBARS_INSIDE_OVERLAY, 1110 SCROLLBARS_INSIDE_INSET, 1111 SCROLLBARS_OUTSIDE_OVERLAY, 1112 SCROLLBARS_OUTSIDE_INSET 1113 }) 1114 @Retention(RetentionPolicy.SOURCE) 1115 public @interface ScrollBarStyle {} 1116 1117 /** 1118 * The scrollbar style to display the scrollbars inside the content area, 1119 * without increasing the padding. The scrollbars will be overlaid with 1120 * translucency on the view's content. 1121 */ 1122 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1123 1124 /** 1125 * The scrollbar style to display the scrollbars inside the padded area, 1126 * increasing the padding of the view. The scrollbars will not overlap the 1127 * content area of the view. 1128 */ 1129 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1130 1131 /** 1132 * The scrollbar style to display the scrollbars at the edge of the view, 1133 * without increasing the padding. The scrollbars will be overlaid with 1134 * translucency. 1135 */ 1136 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1137 1138 /** 1139 * The scrollbar style to display the scrollbars at the edge of the view, 1140 * increasing the padding of the view. The scrollbars will only overlap the 1141 * background, if any. 1142 */ 1143 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1144 1145 /** 1146 * Mask to check if the scrollbar style is overlay or inset. 1147 * {@hide} 1148 */ 1149 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1150 1151 /** 1152 * Mask to check if the scrollbar style is inside or outside. 1153 * {@hide} 1154 */ 1155 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1156 1157 /** 1158 * Mask for scrollbar style. 1159 * {@hide} 1160 */ 1161 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1162 1163 /** 1164 * View flag indicating that the screen should remain on while the 1165 * window containing this view is visible to the user. This effectively 1166 * takes care of automatically setting the WindowManager's 1167 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1168 */ 1169 public static final int KEEP_SCREEN_ON = 0x04000000; 1170 1171 /** 1172 * View flag indicating whether this view should have sound effects enabled 1173 * for events such as clicking and touching. 1174 */ 1175 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1176 1177 /** 1178 * View flag indicating whether this view should have haptic feedback 1179 * enabled for events such as long presses. 1180 */ 1181 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1182 1183 /** 1184 * <p>Indicates that the view hierarchy should stop saving state when 1185 * it reaches this view. If state saving is initiated immediately at 1186 * the view, it will be allowed. 1187 * {@hide} 1188 */ 1189 static final int PARENT_SAVE_DISABLED = 0x20000000; 1190 1191 /** 1192 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1193 * {@hide} 1194 */ 1195 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1196 1197 private static Paint sDebugPaint; 1198 1199 /** @hide */ 1200 @IntDef(flag = true, 1201 value = { 1202 FOCUSABLES_ALL, 1203 FOCUSABLES_TOUCH_MODE 1204 }) 1205 @Retention(RetentionPolicy.SOURCE) 1206 public @interface FocusableMode {} 1207 1208 /** 1209 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1210 * should add all focusable Views regardless if they are focusable in touch mode. 1211 */ 1212 public static final int FOCUSABLES_ALL = 0x00000000; 1213 1214 /** 1215 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1216 * should add only Views focusable in touch mode. 1217 */ 1218 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1219 1220 /** @hide */ 1221 @IntDef({ 1222 FOCUS_BACKWARD, 1223 FOCUS_FORWARD, 1224 FOCUS_LEFT, 1225 FOCUS_UP, 1226 FOCUS_RIGHT, 1227 FOCUS_DOWN 1228 }) 1229 @Retention(RetentionPolicy.SOURCE) 1230 public @interface FocusDirection {} 1231 1232 /** @hide */ 1233 @IntDef({ 1234 FOCUS_LEFT, 1235 FOCUS_UP, 1236 FOCUS_RIGHT, 1237 FOCUS_DOWN 1238 }) 1239 @Retention(RetentionPolicy.SOURCE) 1240 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1241 1242 /** 1243 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1244 * item. 1245 */ 1246 public static final int FOCUS_BACKWARD = 0x00000001; 1247 1248 /** 1249 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1250 * item. 1251 */ 1252 public static final int FOCUS_FORWARD = 0x00000002; 1253 1254 /** 1255 * Use with {@link #focusSearch(int)}. Move focus to the left. 1256 */ 1257 public static final int FOCUS_LEFT = 0x00000011; 1258 1259 /** 1260 * Use with {@link #focusSearch(int)}. Move focus up. 1261 */ 1262 public static final int FOCUS_UP = 0x00000021; 1263 1264 /** 1265 * Use with {@link #focusSearch(int)}. Move focus to the right. 1266 */ 1267 public static final int FOCUS_RIGHT = 0x00000042; 1268 1269 /** 1270 * Use with {@link #focusSearch(int)}. Move focus down. 1271 */ 1272 public static final int FOCUS_DOWN = 0x00000082; 1273 1274 /** 1275 * Bits of {@link #getMeasuredWidthAndState()} and 1276 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1277 */ 1278 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1279 1280 /** 1281 * Bits of {@link #getMeasuredWidthAndState()} and 1282 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1283 */ 1284 public static final int MEASURED_STATE_MASK = 0xff000000; 1285 1286 /** 1287 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1288 * for functions that combine both width and height into a single int, 1289 * such as {@link #getMeasuredState()} and the childState argument of 1290 * {@link #resolveSizeAndState(int, int, int)}. 1291 */ 1292 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1293 1294 /** 1295 * Bit of {@link #getMeasuredWidthAndState()} and 1296 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1297 * is smaller that the space the view would like to have. 1298 */ 1299 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1300 1301 /** 1302 * Base View state sets 1303 */ 1304 // Singles 1305 /** 1306 * Indicates the view has no states set. States are used with 1307 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1308 * view depending on its state. 1309 * 1310 * @see android.graphics.drawable.Drawable 1311 * @see #getDrawableState() 1312 */ 1313 protected static final int[] EMPTY_STATE_SET; 1314 /** 1315 * Indicates the view is enabled. States are used with 1316 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1317 * view depending on its state. 1318 * 1319 * @see android.graphics.drawable.Drawable 1320 * @see #getDrawableState() 1321 */ 1322 protected static final int[] ENABLED_STATE_SET; 1323 /** 1324 * Indicates the view is focused. States are used with 1325 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1326 * view depending on its state. 1327 * 1328 * @see android.graphics.drawable.Drawable 1329 * @see #getDrawableState() 1330 */ 1331 protected static final int[] FOCUSED_STATE_SET; 1332 /** 1333 * Indicates the view is selected. States are used with 1334 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1335 * view depending on its state. 1336 * 1337 * @see android.graphics.drawable.Drawable 1338 * @see #getDrawableState() 1339 */ 1340 protected static final int[] SELECTED_STATE_SET; 1341 /** 1342 * Indicates the view is pressed. States are used with 1343 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1344 * view depending on its state. 1345 * 1346 * @see android.graphics.drawable.Drawable 1347 * @see #getDrawableState() 1348 */ 1349 protected static final int[] PRESSED_STATE_SET; 1350 /** 1351 * Indicates the view's window has focus. States are used with 1352 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1353 * view depending on its state. 1354 * 1355 * @see android.graphics.drawable.Drawable 1356 * @see #getDrawableState() 1357 */ 1358 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1359 // Doubles 1360 /** 1361 * Indicates the view is enabled and has the focus. 1362 * 1363 * @see #ENABLED_STATE_SET 1364 * @see #FOCUSED_STATE_SET 1365 */ 1366 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1367 /** 1368 * Indicates the view is enabled and selected. 1369 * 1370 * @see #ENABLED_STATE_SET 1371 * @see #SELECTED_STATE_SET 1372 */ 1373 protected static final int[] ENABLED_SELECTED_STATE_SET; 1374 /** 1375 * Indicates the view is enabled and that its window has focus. 1376 * 1377 * @see #ENABLED_STATE_SET 1378 * @see #WINDOW_FOCUSED_STATE_SET 1379 */ 1380 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1381 /** 1382 * Indicates the view is focused and selected. 1383 * 1384 * @see #FOCUSED_STATE_SET 1385 * @see #SELECTED_STATE_SET 1386 */ 1387 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1388 /** 1389 * Indicates the view has the focus and that its window has the focus. 1390 * 1391 * @see #FOCUSED_STATE_SET 1392 * @see #WINDOW_FOCUSED_STATE_SET 1393 */ 1394 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1395 /** 1396 * Indicates the view is selected and that its window has the focus. 1397 * 1398 * @see #SELECTED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1402 // Triples 1403 /** 1404 * Indicates the view is enabled, focused and selected. 1405 * 1406 * @see #ENABLED_STATE_SET 1407 * @see #FOCUSED_STATE_SET 1408 * @see #SELECTED_STATE_SET 1409 */ 1410 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1411 /** 1412 * Indicates the view is enabled, focused and its window has the focus. 1413 * 1414 * @see #ENABLED_STATE_SET 1415 * @see #FOCUSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is enabled, selected and its window has the focus. 1421 * 1422 * @see #ENABLED_STATE_SET 1423 * @see #SELECTED_STATE_SET 1424 * @see #WINDOW_FOCUSED_STATE_SET 1425 */ 1426 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1427 /** 1428 * Indicates the view is focused, selected and its window has the focus. 1429 * 1430 * @see #FOCUSED_STATE_SET 1431 * @see #SELECTED_STATE_SET 1432 * @see #WINDOW_FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1435 /** 1436 * Indicates the view is enabled, focused, selected and its window 1437 * has the focus. 1438 * 1439 * @see #ENABLED_STATE_SET 1440 * @see #FOCUSED_STATE_SET 1441 * @see #SELECTED_STATE_SET 1442 * @see #WINDOW_FOCUSED_STATE_SET 1443 */ 1444 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1445 /** 1446 * Indicates the view is pressed and its window has the focus. 1447 * 1448 * @see #PRESSED_STATE_SET 1449 * @see #WINDOW_FOCUSED_STATE_SET 1450 */ 1451 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1452 /** 1453 * Indicates the view is pressed and selected. 1454 * 1455 * @see #PRESSED_STATE_SET 1456 * @see #SELECTED_STATE_SET 1457 */ 1458 protected static final int[] PRESSED_SELECTED_STATE_SET; 1459 /** 1460 * Indicates the view is pressed, selected and its window has the focus. 1461 * 1462 * @see #PRESSED_STATE_SET 1463 * @see #SELECTED_STATE_SET 1464 * @see #WINDOW_FOCUSED_STATE_SET 1465 */ 1466 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1467 /** 1468 * Indicates the view is pressed and focused. 1469 * 1470 * @see #PRESSED_STATE_SET 1471 * @see #FOCUSED_STATE_SET 1472 */ 1473 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1474 /** 1475 * Indicates the view is pressed, focused and its window has the focus. 1476 * 1477 * @see #PRESSED_STATE_SET 1478 * @see #FOCUSED_STATE_SET 1479 * @see #WINDOW_FOCUSED_STATE_SET 1480 */ 1481 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1482 /** 1483 * Indicates the view is pressed, focused and selected. 1484 * 1485 * @see #PRESSED_STATE_SET 1486 * @see #SELECTED_STATE_SET 1487 * @see #FOCUSED_STATE_SET 1488 */ 1489 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1490 /** 1491 * Indicates the view is pressed, focused, selected and its window has the focus. 1492 * 1493 * @see #PRESSED_STATE_SET 1494 * @see #FOCUSED_STATE_SET 1495 * @see #SELECTED_STATE_SET 1496 * @see #WINDOW_FOCUSED_STATE_SET 1497 */ 1498 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1499 /** 1500 * Indicates the view is pressed and enabled. 1501 * 1502 * @see #PRESSED_STATE_SET 1503 * @see #ENABLED_STATE_SET 1504 */ 1505 protected static final int[] PRESSED_ENABLED_STATE_SET; 1506 /** 1507 * Indicates the view is pressed, enabled and its window has the focus. 1508 * 1509 * @see #PRESSED_STATE_SET 1510 * @see #ENABLED_STATE_SET 1511 * @see #WINDOW_FOCUSED_STATE_SET 1512 */ 1513 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1514 /** 1515 * Indicates the view is pressed, enabled and selected. 1516 * 1517 * @see #PRESSED_STATE_SET 1518 * @see #ENABLED_STATE_SET 1519 * @see #SELECTED_STATE_SET 1520 */ 1521 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1522 /** 1523 * Indicates the view is pressed, enabled, selected and its window has the 1524 * focus. 1525 * 1526 * @see #PRESSED_STATE_SET 1527 * @see #ENABLED_STATE_SET 1528 * @see #SELECTED_STATE_SET 1529 * @see #WINDOW_FOCUSED_STATE_SET 1530 */ 1531 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1532 /** 1533 * Indicates the view is pressed, enabled and focused. 1534 * 1535 * @see #PRESSED_STATE_SET 1536 * @see #ENABLED_STATE_SET 1537 * @see #FOCUSED_STATE_SET 1538 */ 1539 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1540 /** 1541 * Indicates the view is pressed, enabled, focused and its window has the 1542 * focus. 1543 * 1544 * @see #PRESSED_STATE_SET 1545 * @see #ENABLED_STATE_SET 1546 * @see #FOCUSED_STATE_SET 1547 * @see #WINDOW_FOCUSED_STATE_SET 1548 */ 1549 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1550 /** 1551 * Indicates the view is pressed, enabled, focused and selected. 1552 * 1553 * @see #PRESSED_STATE_SET 1554 * @see #ENABLED_STATE_SET 1555 * @see #SELECTED_STATE_SET 1556 * @see #FOCUSED_STATE_SET 1557 */ 1558 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1559 /** 1560 * Indicates the view is pressed, enabled, focused, selected and its window 1561 * has the focus. 1562 * 1563 * @see #PRESSED_STATE_SET 1564 * @see #ENABLED_STATE_SET 1565 * @see #SELECTED_STATE_SET 1566 * @see #FOCUSED_STATE_SET 1567 * @see #WINDOW_FOCUSED_STATE_SET 1568 */ 1569 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1570 1571 static { 1572 EMPTY_STATE_SET = StateSet.get(0); 1573 1574 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1575 1576 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1577 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1578 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1579 1580 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1581 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1582 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1583 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1584 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1585 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1586 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1587 | StateSet.VIEW_STATE_FOCUSED); 1588 1589 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1590 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1591 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1592 ENABLED_SELECTED_STATE_SET = StateSet.get( 1593 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1594 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1595 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1596 | StateSet.VIEW_STATE_ENABLED); 1597 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1598 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1599 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1600 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1601 | StateSet.VIEW_STATE_ENABLED); 1602 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1603 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1604 | StateSet.VIEW_STATE_ENABLED); 1605 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1606 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1607 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1608 1609 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1610 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1611 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1612 PRESSED_SELECTED_STATE_SET = StateSet.get( 1613 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1614 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1615 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1616 | StateSet.VIEW_STATE_PRESSED); 1617 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1618 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1619 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1620 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1621 | StateSet.VIEW_STATE_PRESSED); 1622 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1623 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1624 | StateSet.VIEW_STATE_PRESSED); 1625 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1626 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1627 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1628 PRESSED_ENABLED_STATE_SET = StateSet.get( 1629 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1630 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1631 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1632 | StateSet.VIEW_STATE_PRESSED); 1633 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1634 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1635 | StateSet.VIEW_STATE_PRESSED); 1636 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1637 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1638 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1639 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1640 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1641 | StateSet.VIEW_STATE_PRESSED); 1642 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1643 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1644 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1645 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1646 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1647 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1648 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1649 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1650 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1651 | StateSet.VIEW_STATE_PRESSED); 1652 } 1653 1654 /** 1655 * Accessibility event types that are dispatched for text population. 1656 */ 1657 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1658 AccessibilityEvent.TYPE_VIEW_CLICKED 1659 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1660 | AccessibilityEvent.TYPE_VIEW_SELECTED 1661 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1662 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1663 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1664 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1665 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1666 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1667 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1668 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1669 1670 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255); 1671 1672 static final int DEBUG_CORNERS_SIZE_DIP = 8; 1673 1674 /** 1675 * Temporary Rect currently for use in setBackground(). This will probably 1676 * be extended in the future to hold our own class with more than just 1677 * a Rect. :) 1678 */ 1679 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1680 1681 /** 1682 * Map used to store views' tags. 1683 */ 1684 private SparseArray<Object> mKeyedTags; 1685 1686 /** 1687 * The next available accessibility id. 1688 */ 1689 private static int sNextAccessibilityViewId; 1690 1691 /** 1692 * The animation currently associated with this view. 1693 * @hide 1694 */ 1695 protected Animation mCurrentAnimation = null; 1696 1697 /** 1698 * Width as measured during measure pass. 1699 * {@hide} 1700 */ 1701 @ViewDebug.ExportedProperty(category = "measurement") 1702 int mMeasuredWidth; 1703 1704 /** 1705 * Height as measured during measure pass. 1706 * {@hide} 1707 */ 1708 @ViewDebug.ExportedProperty(category = "measurement") 1709 int mMeasuredHeight; 1710 1711 /** 1712 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1713 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1714 * its display list. This flag, used only when hw accelerated, allows us to clear the 1715 * flag while retaining this information until it's needed (at getDisplayList() time and 1716 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1717 * 1718 * {@hide} 1719 */ 1720 boolean mRecreateDisplayList = false; 1721 1722 /** 1723 * The view's identifier. 1724 * {@hide} 1725 * 1726 * @see #setId(int) 1727 * @see #getId() 1728 */ 1729 @IdRes 1730 @ViewDebug.ExportedProperty(resolveId = true) 1731 int mID = NO_ID; 1732 1733 /** 1734 * The stable ID of this view for accessibility purposes. 1735 */ 1736 int mAccessibilityViewId = NO_ID; 1737 1738 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1739 1740 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1741 1742 /** 1743 * The view's tag. 1744 * {@hide} 1745 * 1746 * @see #setTag(Object) 1747 * @see #getTag() 1748 */ 1749 protected Object mTag = null; 1750 1751 // for mPrivateFlags: 1752 /** {@hide} */ 1753 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1754 /** {@hide} */ 1755 static final int PFLAG_FOCUSED = 0x00000002; 1756 /** {@hide} */ 1757 static final int PFLAG_SELECTED = 0x00000004; 1758 /** {@hide} */ 1759 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1760 /** {@hide} */ 1761 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1762 /** {@hide} */ 1763 static final int PFLAG_DRAWN = 0x00000020; 1764 /** 1765 * When this flag is set, this view is running an animation on behalf of its 1766 * children and should therefore not cancel invalidate requests, even if they 1767 * lie outside of this view's bounds. 1768 * 1769 * {@hide} 1770 */ 1771 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1772 /** {@hide} */ 1773 static final int PFLAG_SKIP_DRAW = 0x00000080; 1774 /** {@hide} */ 1775 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1776 /** {@hide} */ 1777 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1778 /** {@hide} */ 1779 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1780 /** {@hide} */ 1781 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1782 /** {@hide} */ 1783 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1784 1785 private static final int PFLAG_PRESSED = 0x00004000; 1786 1787 /** {@hide} */ 1788 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1789 /** 1790 * Flag used to indicate that this view should be drawn once more (and only once 1791 * more) after its animation has completed. 1792 * {@hide} 1793 */ 1794 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1795 1796 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1797 1798 /** 1799 * Indicates that the View returned true when onSetAlpha() was called and that 1800 * the alpha must be restored. 1801 * {@hide} 1802 */ 1803 static final int PFLAG_ALPHA_SET = 0x00040000; 1804 1805 /** 1806 * Set by {@link #setScrollContainer(boolean)}. 1807 */ 1808 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1809 1810 /** 1811 * Set by {@link #setScrollContainer(boolean)}. 1812 */ 1813 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1814 1815 /** 1816 * View flag indicating whether this view was invalidated (fully or partially.) 1817 * 1818 * @hide 1819 */ 1820 static final int PFLAG_DIRTY = 0x00200000; 1821 1822 /** 1823 * View flag indicating whether this view was invalidated by an opaque 1824 * invalidate request. 1825 * 1826 * @hide 1827 */ 1828 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1829 1830 /** 1831 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1832 * 1833 * @hide 1834 */ 1835 static final int PFLAG_DIRTY_MASK = 0x00600000; 1836 1837 /** 1838 * Indicates whether the background is opaque. 1839 * 1840 * @hide 1841 */ 1842 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1843 1844 /** 1845 * Indicates whether the scrollbars are opaque. 1846 * 1847 * @hide 1848 */ 1849 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1850 1851 /** 1852 * Indicates whether the view is opaque. 1853 * 1854 * @hide 1855 */ 1856 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1857 1858 /** 1859 * Indicates a prepressed state; 1860 * the short time between ACTION_DOWN and recognizing 1861 * a 'real' press. Prepressed is used to recognize quick taps 1862 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1863 * 1864 * @hide 1865 */ 1866 private static final int PFLAG_PREPRESSED = 0x02000000; 1867 1868 /** 1869 * Indicates whether the view is temporarily detached. 1870 * 1871 * @hide 1872 */ 1873 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1874 1875 /** 1876 * Indicates that we should awaken scroll bars once attached 1877 * 1878 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1879 * during window attachment and it is no longer needed. Feel free to repurpose it. 1880 * 1881 * @hide 1882 */ 1883 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1884 1885 /** 1886 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1887 * @hide 1888 */ 1889 private static final int PFLAG_HOVERED = 0x10000000; 1890 1891 /** 1892 * no longer needed, should be reused 1893 */ 1894 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1895 1896 /** {@hide} */ 1897 static final int PFLAG_ACTIVATED = 0x40000000; 1898 1899 /** 1900 * Indicates that this view was specifically invalidated, not just dirtied because some 1901 * child view was invalidated. The flag is used to determine when we need to recreate 1902 * a view's display list (as opposed to just returning a reference to its existing 1903 * display list). 1904 * 1905 * @hide 1906 */ 1907 static final int PFLAG_INVALIDATED = 0x80000000; 1908 1909 /** 1910 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1911 * 1912 * |-------|-------|-------|-------| 1913 * 1 PFLAG2_DRAG_CAN_ACCEPT 1914 * 1 PFLAG2_DRAG_HOVERED 1915 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1916 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1917 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1918 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1919 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1920 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1921 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1922 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1923 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1924 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1925 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1926 * 111 PFLAG2_TEXT_DIRECTION_MASK 1927 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1928 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1929 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1930 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1931 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1932 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1933 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1934 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1935 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1936 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1937 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1938 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1939 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1940 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1941 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1942 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1943 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1944 * 1 PFLAG2_VIEW_QUICK_REJECTED 1945 * 1 PFLAG2_PADDING_RESOLVED 1946 * 1 PFLAG2_DRAWABLE_RESOLVED 1947 * 1 PFLAG2_HAS_TRANSIENT_STATE 1948 * |-------|-------|-------|-------| 1949 */ 1950 1951 /** 1952 * Indicates that this view has reported that it can accept the current drag's content. 1953 * Cleared when the drag operation concludes. 1954 * @hide 1955 */ 1956 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1957 1958 /** 1959 * Indicates that this view is currently directly under the drag location in a 1960 * drag-and-drop operation involving content that it can accept. Cleared when 1961 * the drag exits the view, or when the drag operation concludes. 1962 * @hide 1963 */ 1964 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1965 1966 /** @hide */ 1967 @IntDef({ 1968 LAYOUT_DIRECTION_LTR, 1969 LAYOUT_DIRECTION_RTL, 1970 LAYOUT_DIRECTION_INHERIT, 1971 LAYOUT_DIRECTION_LOCALE 1972 }) 1973 @Retention(RetentionPolicy.SOURCE) 1974 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1975 public @interface LayoutDir {} 1976 1977 /** @hide */ 1978 @IntDef({ 1979 LAYOUT_DIRECTION_LTR, 1980 LAYOUT_DIRECTION_RTL 1981 }) 1982 @Retention(RetentionPolicy.SOURCE) 1983 public @interface ResolvedLayoutDir {} 1984 1985 /** 1986 * A flag to indicate that the layout direction of this view has not been defined yet. 1987 * @hide 1988 */ 1989 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1990 1991 /** 1992 * Horizontal layout direction of this view is from Left to Right. 1993 * Use with {@link #setLayoutDirection}. 1994 */ 1995 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1996 1997 /** 1998 * Horizontal layout direction of this view is from Right to Left. 1999 * Use with {@link #setLayoutDirection}. 2000 */ 2001 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 2002 2003 /** 2004 * Horizontal layout direction of this view is inherited from its parent. 2005 * Use with {@link #setLayoutDirection}. 2006 */ 2007 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 2008 2009 /** 2010 * Horizontal layout direction of this view is from deduced from the default language 2011 * script for the locale. Use with {@link #setLayoutDirection}. 2012 */ 2013 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 2014 2015 /** 2016 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2017 * @hide 2018 */ 2019 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2020 2021 /** 2022 * Mask for use with private flags indicating bits used for horizontal layout direction. 2023 * @hide 2024 */ 2025 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2026 2027 /** 2028 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2029 * right-to-left direction. 2030 * @hide 2031 */ 2032 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2033 2034 /** 2035 * Indicates whether the view horizontal layout direction has been resolved. 2036 * @hide 2037 */ 2038 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2039 2040 /** 2041 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2042 * @hide 2043 */ 2044 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2045 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2046 2047 /* 2048 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2049 * flag value. 2050 * @hide 2051 */ 2052 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2053 LAYOUT_DIRECTION_LTR, 2054 LAYOUT_DIRECTION_RTL, 2055 LAYOUT_DIRECTION_INHERIT, 2056 LAYOUT_DIRECTION_LOCALE 2057 }; 2058 2059 /** 2060 * Default horizontal layout direction. 2061 */ 2062 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2063 2064 /** 2065 * Default horizontal layout direction. 2066 * @hide 2067 */ 2068 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2069 2070 /** 2071 * Text direction is inherited through {@link ViewGroup} 2072 */ 2073 public static final int TEXT_DIRECTION_INHERIT = 0; 2074 2075 /** 2076 * Text direction is using "first strong algorithm". The first strong directional character 2077 * determines the paragraph direction. If there is no strong directional character, the 2078 * paragraph direction is the view's resolved layout direction. 2079 */ 2080 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2081 2082 /** 2083 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2084 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2085 * If there are neither, the paragraph direction is the view's resolved layout direction. 2086 */ 2087 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2088 2089 /** 2090 * Text direction is forced to LTR. 2091 */ 2092 public static final int TEXT_DIRECTION_LTR = 3; 2093 2094 /** 2095 * Text direction is forced to RTL. 2096 */ 2097 public static final int TEXT_DIRECTION_RTL = 4; 2098 2099 /** 2100 * Text direction is coming from the system Locale. 2101 */ 2102 public static final int TEXT_DIRECTION_LOCALE = 5; 2103 2104 /** 2105 * Text direction is using "first strong algorithm". The first strong directional character 2106 * determines the paragraph direction. If there is no strong directional character, the 2107 * paragraph direction is LTR. 2108 */ 2109 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2110 2111 /** 2112 * Text direction is using "first strong algorithm". The first strong directional character 2113 * determines the paragraph direction. If there is no strong directional character, the 2114 * paragraph direction is RTL. 2115 */ 2116 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2117 2118 /** 2119 * Default text direction is inherited 2120 */ 2121 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2122 2123 /** 2124 * Default resolved text direction 2125 * @hide 2126 */ 2127 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2128 2129 /** 2130 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2131 * @hide 2132 */ 2133 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2134 2135 /** 2136 * Mask for use with private flags indicating bits used for text direction. 2137 * @hide 2138 */ 2139 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2140 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2141 2142 /** 2143 * Array of text direction flags for mapping attribute "textDirection" to correct 2144 * flag value. 2145 * @hide 2146 */ 2147 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2148 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2149 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2150 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2151 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2152 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2153 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2154 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2155 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2156 }; 2157 2158 /** 2159 * Indicates whether the view text direction has been resolved. 2160 * @hide 2161 */ 2162 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2163 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2164 2165 /** 2166 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2167 * @hide 2168 */ 2169 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2170 2171 /** 2172 * Mask for use with private flags indicating bits used for resolved text direction. 2173 * @hide 2174 */ 2175 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2176 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2177 2178 /** 2179 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2180 * @hide 2181 */ 2182 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2183 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2184 2185 /** @hide */ 2186 @IntDef({ 2187 TEXT_ALIGNMENT_INHERIT, 2188 TEXT_ALIGNMENT_GRAVITY, 2189 TEXT_ALIGNMENT_CENTER, 2190 TEXT_ALIGNMENT_TEXT_START, 2191 TEXT_ALIGNMENT_TEXT_END, 2192 TEXT_ALIGNMENT_VIEW_START, 2193 TEXT_ALIGNMENT_VIEW_END 2194 }) 2195 @Retention(RetentionPolicy.SOURCE) 2196 public @interface TextAlignment {} 2197 2198 /** 2199 * Default text alignment. The text alignment of this View is inherited from its parent. 2200 * Use with {@link #setTextAlignment(int)} 2201 */ 2202 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2203 2204 /** 2205 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2206 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2207 * 2208 * Use with {@link #setTextAlignment(int)} 2209 */ 2210 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2211 2212 /** 2213 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2214 * 2215 * Use with {@link #setTextAlignment(int)} 2216 */ 2217 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2218 2219 /** 2220 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2221 * 2222 * Use with {@link #setTextAlignment(int)} 2223 */ 2224 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2225 2226 /** 2227 * Center the paragraph, e.g. ALIGN_CENTER. 2228 * 2229 * Use with {@link #setTextAlignment(int)} 2230 */ 2231 public static final int TEXT_ALIGNMENT_CENTER = 4; 2232 2233 /** 2234 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2235 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2236 * 2237 * Use with {@link #setTextAlignment(int)} 2238 */ 2239 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2240 2241 /** 2242 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2243 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2244 * 2245 * Use with {@link #setTextAlignment(int)} 2246 */ 2247 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2248 2249 /** 2250 * Default text alignment is inherited 2251 */ 2252 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2253 2254 /** 2255 * Default resolved text alignment 2256 * @hide 2257 */ 2258 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2259 2260 /** 2261 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2262 * @hide 2263 */ 2264 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2265 2266 /** 2267 * Mask for use with private flags indicating bits used for text alignment. 2268 * @hide 2269 */ 2270 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2271 2272 /** 2273 * Array of text direction flags for mapping attribute "textAlignment" to correct 2274 * flag value. 2275 * @hide 2276 */ 2277 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2278 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2279 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2280 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2281 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2282 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2283 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2284 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2285 }; 2286 2287 /** 2288 * Indicates whether the view text alignment has been resolved. 2289 * @hide 2290 */ 2291 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2292 2293 /** 2294 * Bit shift to get the resolved text alignment. 2295 * @hide 2296 */ 2297 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2298 2299 /** 2300 * Mask for use with private flags indicating bits used for text alignment. 2301 * @hide 2302 */ 2303 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2304 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2305 2306 /** 2307 * Indicates whether if the view text alignment has been resolved to gravity 2308 */ 2309 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2310 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2311 2312 // Accessiblity constants for mPrivateFlags2 2313 2314 /** 2315 * Shift for the bits in {@link #mPrivateFlags2} related to the 2316 * "importantForAccessibility" attribute. 2317 */ 2318 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2319 2320 /** 2321 * Automatically determine whether a view is important for accessibility. 2322 */ 2323 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2324 2325 /** 2326 * The view is important for accessibility. 2327 */ 2328 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2329 2330 /** 2331 * The view is not important for accessibility. 2332 */ 2333 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2334 2335 /** 2336 * The view is not important for accessibility, nor are any of its 2337 * descendant views. 2338 */ 2339 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2340 2341 /** 2342 * The default whether the view is important for accessibility. 2343 */ 2344 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2345 2346 /** 2347 * Mask for obtaining the bits which specify how to determine 2348 * whether a view is important for accessibility. 2349 */ 2350 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2351 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2352 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2353 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2354 2355 /** 2356 * Shift for the bits in {@link #mPrivateFlags2} related to the 2357 * "accessibilityLiveRegion" attribute. 2358 */ 2359 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2360 2361 /** 2362 * Live region mode specifying that accessibility services should not 2363 * automatically announce changes to this view. This is the default live 2364 * region mode for most views. 2365 * <p> 2366 * Use with {@link #setAccessibilityLiveRegion(int)}. 2367 */ 2368 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2369 2370 /** 2371 * Live region mode specifying that accessibility services should announce 2372 * changes to this view. 2373 * <p> 2374 * Use with {@link #setAccessibilityLiveRegion(int)}. 2375 */ 2376 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2377 2378 /** 2379 * Live region mode specifying that accessibility services should interrupt 2380 * ongoing speech to immediately announce changes to this view. 2381 * <p> 2382 * Use with {@link #setAccessibilityLiveRegion(int)}. 2383 */ 2384 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2385 2386 /** 2387 * The default whether the view is important for accessibility. 2388 */ 2389 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2390 2391 /** 2392 * Mask for obtaining the bits which specify a view's accessibility live 2393 * region mode. 2394 */ 2395 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2396 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2397 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2398 2399 /** 2400 * Flag indicating whether a view has accessibility focus. 2401 */ 2402 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2403 2404 /** 2405 * Flag whether the accessibility state of the subtree rooted at this view changed. 2406 */ 2407 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2408 2409 /** 2410 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2411 * is used to check whether later changes to the view's transform should invalidate the 2412 * view to force the quickReject test to run again. 2413 */ 2414 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2415 2416 /** 2417 * Flag indicating that start/end padding has been resolved into left/right padding 2418 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2419 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2420 * during measurement. In some special cases this is required such as when an adapter-based 2421 * view measures prospective children without attaching them to a window. 2422 */ 2423 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2424 2425 /** 2426 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2427 */ 2428 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2429 2430 /** 2431 * Indicates that the view is tracking some sort of transient state 2432 * that the app should not need to be aware of, but that the framework 2433 * should take special care to preserve. 2434 */ 2435 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2436 2437 /** 2438 * Group of bits indicating that RTL properties resolution is done. 2439 */ 2440 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2441 PFLAG2_TEXT_DIRECTION_RESOLVED | 2442 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2443 PFLAG2_PADDING_RESOLVED | 2444 PFLAG2_DRAWABLE_RESOLVED; 2445 2446 // There are a couple of flags left in mPrivateFlags2 2447 2448 /* End of masks for mPrivateFlags2 */ 2449 2450 /** 2451 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2452 * 2453 * |-------|-------|-------|-------| 2454 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2455 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2456 * 1 PFLAG3_IS_LAID_OUT 2457 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2458 * 1 PFLAG3_CALLED_SUPER 2459 * 1 PFLAG3_APPLYING_INSETS 2460 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2461 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2462 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2463 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2464 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2465 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2466 * 1 PFLAG3_SCROLL_INDICATOR_START 2467 * 1 PFLAG3_SCROLL_INDICATOR_END 2468 * 1 PFLAG3_ASSIST_BLOCKED 2469 * xxxxxxxx * NO LONGER NEEDED, SHOULD BE REUSED * 2470 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2471 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2472 * 1 PFLAG3_TEMPORARY_DETACH 2473 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2474 * |-------|-------|-------|-------| 2475 */ 2476 2477 /** 2478 * Flag indicating that view has a transform animation set on it. This is used to track whether 2479 * an animation is cleared between successive frames, in order to tell the associated 2480 * DisplayList to clear its animation matrix. 2481 */ 2482 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2483 2484 /** 2485 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2486 * animation is cleared between successive frames, in order to tell the associated 2487 * DisplayList to restore its alpha value. 2488 */ 2489 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2490 2491 /** 2492 * Flag indicating that the view has been through at least one layout since it 2493 * was last attached to a window. 2494 */ 2495 static final int PFLAG3_IS_LAID_OUT = 0x4; 2496 2497 /** 2498 * Flag indicating that a call to measure() was skipped and should be done 2499 * instead when layout() is invoked. 2500 */ 2501 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2502 2503 /** 2504 * Flag indicating that an overridden method correctly called down to 2505 * the superclass implementation as required by the API spec. 2506 */ 2507 static final int PFLAG3_CALLED_SUPER = 0x10; 2508 2509 /** 2510 * Flag indicating that we're in the process of applying window insets. 2511 */ 2512 static final int PFLAG3_APPLYING_INSETS = 0x20; 2513 2514 /** 2515 * Flag indicating that we're in the process of fitting system windows using the old method. 2516 */ 2517 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2518 2519 /** 2520 * Flag indicating that nested scrolling is enabled for this view. 2521 * The view will optionally cooperate with views up its parent chain to allow for 2522 * integrated nested scrolling along the same axis. 2523 */ 2524 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2525 2526 /** 2527 * Flag indicating that the bottom scroll indicator should be displayed 2528 * when this view can scroll up. 2529 */ 2530 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2531 2532 /** 2533 * Flag indicating that the bottom scroll indicator should be displayed 2534 * when this view can scroll down. 2535 */ 2536 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2537 2538 /** 2539 * Flag indicating that the left scroll indicator should be displayed 2540 * when this view can scroll left. 2541 */ 2542 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2543 2544 /** 2545 * Flag indicating that the right scroll indicator should be displayed 2546 * when this view can scroll right. 2547 */ 2548 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2549 2550 /** 2551 * Flag indicating that the start scroll indicator should be displayed 2552 * when this view can scroll in the start direction. 2553 */ 2554 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2555 2556 /** 2557 * Flag indicating that the end scroll indicator should be displayed 2558 * when this view can scroll in the end direction. 2559 */ 2560 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2561 2562 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2563 2564 static final int SCROLL_INDICATORS_NONE = 0x0000; 2565 2566 /** 2567 * Mask for use with setFlags indicating bits used for indicating which 2568 * scroll indicators are enabled. 2569 */ 2570 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2571 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2572 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2573 | PFLAG3_SCROLL_INDICATOR_END; 2574 2575 /** 2576 * Left-shift required to translate between public scroll indicator flags 2577 * and internal PFLAGS3 flags. When used as a right-shift, translates 2578 * PFLAGS3 flags to public flags. 2579 */ 2580 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2581 2582 /** @hide */ 2583 @Retention(RetentionPolicy.SOURCE) 2584 @IntDef(flag = true, 2585 value = { 2586 SCROLL_INDICATOR_TOP, 2587 SCROLL_INDICATOR_BOTTOM, 2588 SCROLL_INDICATOR_LEFT, 2589 SCROLL_INDICATOR_RIGHT, 2590 SCROLL_INDICATOR_START, 2591 SCROLL_INDICATOR_END, 2592 }) 2593 public @interface ScrollIndicators {} 2594 2595 /** 2596 * Scroll indicator direction for the top edge of the view. 2597 * 2598 * @see #setScrollIndicators(int) 2599 * @see #setScrollIndicators(int, int) 2600 * @see #getScrollIndicators() 2601 */ 2602 public static final int SCROLL_INDICATOR_TOP = 2603 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2604 2605 /** 2606 * Scroll indicator direction for the bottom edge of the view. 2607 * 2608 * @see #setScrollIndicators(int) 2609 * @see #setScrollIndicators(int, int) 2610 * @see #getScrollIndicators() 2611 */ 2612 public static final int SCROLL_INDICATOR_BOTTOM = 2613 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2614 2615 /** 2616 * Scroll indicator direction for the left edge of the view. 2617 * 2618 * @see #setScrollIndicators(int) 2619 * @see #setScrollIndicators(int, int) 2620 * @see #getScrollIndicators() 2621 */ 2622 public static final int SCROLL_INDICATOR_LEFT = 2623 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2624 2625 /** 2626 * Scroll indicator direction for the right edge of the view. 2627 * 2628 * @see #setScrollIndicators(int) 2629 * @see #setScrollIndicators(int, int) 2630 * @see #getScrollIndicators() 2631 */ 2632 public static final int SCROLL_INDICATOR_RIGHT = 2633 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2634 2635 /** 2636 * Scroll indicator direction for the starting edge of the view. 2637 * <p> 2638 * Resolved according to the view's layout direction, see 2639 * {@link #getLayoutDirection()} for more information. 2640 * 2641 * @see #setScrollIndicators(int) 2642 * @see #setScrollIndicators(int, int) 2643 * @see #getScrollIndicators() 2644 */ 2645 public static final int SCROLL_INDICATOR_START = 2646 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2647 2648 /** 2649 * Scroll indicator direction for the ending edge of the view. 2650 * <p> 2651 * Resolved according to the view's layout direction, see 2652 * {@link #getLayoutDirection()} for more information. 2653 * 2654 * @see #setScrollIndicators(int) 2655 * @see #setScrollIndicators(int, int) 2656 * @see #getScrollIndicators() 2657 */ 2658 public static final int SCROLL_INDICATOR_END = 2659 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2660 2661 /** 2662 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2663 * into this view.<p> 2664 */ 2665 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2666 2667 /** 2668 * Whether this view has rendered elements that overlap (see {@link 2669 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 2670 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 2671 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 2672 * determined by whatever {@link #hasOverlappingRendering()} returns. 2673 */ 2674 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 2675 2676 /** 2677 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 2678 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 2679 */ 2680 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 2681 2682 /** 2683 * Flag indicating that the view is temporarily detached from the parent view. 2684 * 2685 * @see #onStartTemporaryDetach() 2686 * @see #onFinishTemporaryDetach() 2687 */ 2688 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 2689 2690 /** 2691 * Flag indicating that the view does not wish to be revealed within its parent 2692 * hierarchy when it gains focus. Expressed in the negative since the historical 2693 * default behavior is to reveal on focus; this flag suppresses that behavior. 2694 * 2695 * @see #setRevealOnFocusHint(boolean) 2696 * @see #getRevealOnFocusHint() 2697 */ 2698 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 2699 2700 /* End of masks for mPrivateFlags3 */ 2701 2702 /** 2703 * Always allow a user to over-scroll this view, provided it is a 2704 * view that can scroll. 2705 * 2706 * @see #getOverScrollMode() 2707 * @see #setOverScrollMode(int) 2708 */ 2709 public static final int OVER_SCROLL_ALWAYS = 0; 2710 2711 /** 2712 * Allow a user to over-scroll this view only if the content is large 2713 * enough to meaningfully scroll, provided it is a view that can scroll. 2714 * 2715 * @see #getOverScrollMode() 2716 * @see #setOverScrollMode(int) 2717 */ 2718 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2719 2720 /** 2721 * Never allow a user to over-scroll this view. 2722 * 2723 * @see #getOverScrollMode() 2724 * @see #setOverScrollMode(int) 2725 */ 2726 public static final int OVER_SCROLL_NEVER = 2; 2727 2728 /** 2729 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2730 * requested the system UI (status bar) to be visible (the default). 2731 * 2732 * @see #setSystemUiVisibility(int) 2733 */ 2734 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2735 2736 /** 2737 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2738 * system UI to enter an unobtrusive "low profile" mode. 2739 * 2740 * <p>This is for use in games, book readers, video players, or any other 2741 * "immersive" application where the usual system chrome is deemed too distracting. 2742 * 2743 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2744 * 2745 * @see #setSystemUiVisibility(int) 2746 */ 2747 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2748 2749 /** 2750 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2751 * system navigation be temporarily hidden. 2752 * 2753 * <p>This is an even less obtrusive state than that called for by 2754 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2755 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2756 * those to disappear. This is useful (in conjunction with the 2757 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2758 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2759 * window flags) for displaying content using every last pixel on the display. 2760 * 2761 * <p>There is a limitation: because navigation controls are so important, the least user 2762 * interaction will cause them to reappear immediately. When this happens, both 2763 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2764 * so that both elements reappear at the same time. 2765 * 2766 * @see #setSystemUiVisibility(int) 2767 */ 2768 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2769 2770 /** 2771 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2772 * into the normal fullscreen mode so that its content can take over the screen 2773 * while still allowing the user to interact with the application. 2774 * 2775 * <p>This has the same visual effect as 2776 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2777 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2778 * meaning that non-critical screen decorations (such as the status bar) will be 2779 * hidden while the user is in the View's window, focusing the experience on 2780 * that content. Unlike the window flag, if you are using ActionBar in 2781 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2782 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2783 * hide the action bar. 2784 * 2785 * <p>This approach to going fullscreen is best used over the window flag when 2786 * it is a transient state -- that is, the application does this at certain 2787 * points in its user interaction where it wants to allow the user to focus 2788 * on content, but not as a continuous state. For situations where the application 2789 * would like to simply stay full screen the entire time (such as a game that 2790 * wants to take over the screen), the 2791 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2792 * is usually a better approach. The state set here will be removed by the system 2793 * in various situations (such as the user moving to another application) like 2794 * the other system UI states. 2795 * 2796 * <p>When using this flag, the application should provide some easy facility 2797 * for the user to go out of it. A common example would be in an e-book 2798 * reader, where tapping on the screen brings back whatever screen and UI 2799 * decorations that had been hidden while the user was immersed in reading 2800 * the book. 2801 * 2802 * @see #setSystemUiVisibility(int) 2803 */ 2804 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2805 2806 /** 2807 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2808 * flags, we would like a stable view of the content insets given to 2809 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2810 * will always represent the worst case that the application can expect 2811 * as a continuous state. In the stock Android UI this is the space for 2812 * the system bar, nav bar, and status bar, but not more transient elements 2813 * such as an input method. 2814 * 2815 * The stable layout your UI sees is based on the system UI modes you can 2816 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2817 * then you will get a stable layout for changes of the 2818 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2819 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2820 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2821 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2822 * with a stable layout. (Note that you should avoid using 2823 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2824 * 2825 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2826 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2827 * then a hidden status bar will be considered a "stable" state for purposes 2828 * here. This allows your UI to continually hide the status bar, while still 2829 * using the system UI flags to hide the action bar while still retaining 2830 * a stable layout. Note that changing the window fullscreen flag will never 2831 * provide a stable layout for a clean transition. 2832 * 2833 * <p>If you are using ActionBar in 2834 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2835 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2836 * insets it adds to those given to the application. 2837 */ 2838 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2839 2840 /** 2841 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2842 * to be laid out as if it has requested 2843 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2844 * allows it to avoid artifacts when switching in and out of that mode, at 2845 * the expense that some of its user interface may be covered by screen 2846 * decorations when they are shown. You can perform layout of your inner 2847 * UI elements to account for the navigation system UI through the 2848 * {@link #fitSystemWindows(Rect)} method. 2849 */ 2850 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2851 2852 /** 2853 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2854 * to be laid out as if it has requested 2855 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2856 * allows it to avoid artifacts when switching in and out of that mode, at 2857 * the expense that some of its user interface may be covered by screen 2858 * decorations when they are shown. You can perform layout of your inner 2859 * UI elements to account for non-fullscreen system UI through the 2860 * {@link #fitSystemWindows(Rect)} method. 2861 */ 2862 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2863 2864 /** 2865 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2866 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2867 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2868 * user interaction. 2869 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2870 * has an effect when used in combination with that flag.</p> 2871 */ 2872 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2873 2874 /** 2875 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2876 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2877 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2878 * experience while also hiding the system bars. If this flag is not set, 2879 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2880 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2881 * if the user swipes from the top of the screen. 2882 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2883 * system gestures, such as swiping from the top of the screen. These transient system bars 2884 * will overlay app’s content, may have some degree of transparency, and will automatically 2885 * hide after a short timeout. 2886 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2887 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2888 * with one or both of those flags.</p> 2889 */ 2890 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2891 2892 /** 2893 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2894 * is compatible with light status bar backgrounds. 2895 * 2896 * <p>For this to take effect, the window must request 2897 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2898 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2899 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2900 * FLAG_TRANSLUCENT_STATUS}. 2901 * 2902 * @see android.R.attr#windowLightStatusBar 2903 */ 2904 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2905 2906 /** 2907 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2908 */ 2909 @Deprecated 2910 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2911 2912 /** 2913 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2914 */ 2915 @Deprecated 2916 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2917 2918 /** 2919 * @hide 2920 * 2921 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2922 * out of the public fields to keep the undefined bits out of the developer's way. 2923 * 2924 * Flag to make the status bar not expandable. Unless you also 2925 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2926 */ 2927 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2928 2929 /** 2930 * @hide 2931 * 2932 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2933 * out of the public fields to keep the undefined bits out of the developer's way. 2934 * 2935 * Flag to hide notification icons and scrolling ticker text. 2936 */ 2937 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2938 2939 /** 2940 * @hide 2941 * 2942 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2943 * out of the public fields to keep the undefined bits out of the developer's way. 2944 * 2945 * Flag to disable incoming notification alerts. This will not block 2946 * icons, but it will block sound, vibrating and other visual or aural notifications. 2947 */ 2948 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2949 2950 /** 2951 * @hide 2952 * 2953 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2954 * out of the public fields to keep the undefined bits out of the developer's way. 2955 * 2956 * Flag to hide only the scrolling ticker. Note that 2957 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2958 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2959 */ 2960 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2961 2962 /** 2963 * @hide 2964 * 2965 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2966 * out of the public fields to keep the undefined bits out of the developer's way. 2967 * 2968 * Flag to hide the center system info area. 2969 */ 2970 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2971 2972 /** 2973 * @hide 2974 * 2975 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2976 * out of the public fields to keep the undefined bits out of the developer's way. 2977 * 2978 * Flag to hide only the home button. Don't use this 2979 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2980 */ 2981 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2982 2983 /** 2984 * @hide 2985 * 2986 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2987 * out of the public fields to keep the undefined bits out of the developer's way. 2988 * 2989 * Flag to hide only the back button. Don't use this 2990 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2991 */ 2992 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2993 2994 /** 2995 * @hide 2996 * 2997 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2998 * out of the public fields to keep the undefined bits out of the developer's way. 2999 * 3000 * Flag to hide only the clock. You might use this if your activity has 3001 * its own clock making the status bar's clock redundant. 3002 */ 3003 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 3004 3005 /** 3006 * @hide 3007 * 3008 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3009 * out of the public fields to keep the undefined bits out of the developer's way. 3010 * 3011 * Flag to hide only the recent apps button. Don't use this 3012 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3013 */ 3014 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 3015 3016 /** 3017 * @hide 3018 * 3019 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3020 * out of the public fields to keep the undefined bits out of the developer's way. 3021 * 3022 * Flag to disable the global search gesture. Don't use this 3023 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3024 */ 3025 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3026 3027 /** 3028 * @hide 3029 * 3030 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3031 * out of the public fields to keep the undefined bits out of the developer's way. 3032 * 3033 * Flag to specify that the status bar is displayed in transient mode. 3034 */ 3035 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3036 3037 /** 3038 * @hide 3039 * 3040 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3041 * out of the public fields to keep the undefined bits out of the developer's way. 3042 * 3043 * Flag to specify that the navigation bar is displayed in transient mode. 3044 */ 3045 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3046 3047 /** 3048 * @hide 3049 * 3050 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3051 * out of the public fields to keep the undefined bits out of the developer's way. 3052 * 3053 * Flag to specify that the hidden status bar would like to be shown. 3054 */ 3055 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3056 3057 /** 3058 * @hide 3059 * 3060 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3061 * out of the public fields to keep the undefined bits out of the developer's way. 3062 * 3063 * Flag to specify that the hidden navigation bar would like to be shown. 3064 */ 3065 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3066 3067 /** 3068 * @hide 3069 * 3070 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3071 * out of the public fields to keep the undefined bits out of the developer's way. 3072 * 3073 * Flag to specify that the status bar is displayed in translucent mode. 3074 */ 3075 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3076 3077 /** 3078 * @hide 3079 * 3080 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3081 * out of the public fields to keep the undefined bits out of the developer's way. 3082 * 3083 * Flag to specify that the navigation bar is displayed in translucent mode. 3084 */ 3085 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3086 3087 /** 3088 * @hide 3089 * 3090 * Makes navigation bar transparent (but not the status bar). 3091 */ 3092 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3093 3094 /** 3095 * @hide 3096 * 3097 * Makes status bar transparent (but not the navigation bar). 3098 */ 3099 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3100 3101 /** 3102 * @hide 3103 * 3104 * Makes both status bar and navigation bar transparent. 3105 */ 3106 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3107 | STATUS_BAR_TRANSPARENT; 3108 3109 /** 3110 * @hide 3111 */ 3112 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3113 3114 /** 3115 * These are the system UI flags that can be cleared by events outside 3116 * of an application. Currently this is just the ability to tap on the 3117 * screen while hiding the navigation bar to have it return. 3118 * @hide 3119 */ 3120 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3121 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3122 | SYSTEM_UI_FLAG_FULLSCREEN; 3123 3124 /** 3125 * Flags that can impact the layout in relation to system UI. 3126 */ 3127 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3128 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3129 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3130 3131 /** @hide */ 3132 @IntDef(flag = true, 3133 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3134 @Retention(RetentionPolicy.SOURCE) 3135 public @interface FindViewFlags {} 3136 3137 /** 3138 * Find views that render the specified text. 3139 * 3140 * @see #findViewsWithText(ArrayList, CharSequence, int) 3141 */ 3142 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3143 3144 /** 3145 * Find find views that contain the specified content description. 3146 * 3147 * @see #findViewsWithText(ArrayList, CharSequence, int) 3148 */ 3149 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3150 3151 /** 3152 * Find views that contain {@link AccessibilityNodeProvider}. Such 3153 * a View is a root of virtual view hierarchy and may contain the searched 3154 * text. If this flag is set Views with providers are automatically 3155 * added and it is a responsibility of the client to call the APIs of 3156 * the provider to determine whether the virtual tree rooted at this View 3157 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3158 * representing the virtual views with this text. 3159 * 3160 * @see #findViewsWithText(ArrayList, CharSequence, int) 3161 * 3162 * @hide 3163 */ 3164 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3165 3166 /** 3167 * The undefined cursor position. 3168 * 3169 * @hide 3170 */ 3171 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3172 3173 /** 3174 * Indicates that the screen has changed state and is now off. 3175 * 3176 * @see #onScreenStateChanged(int) 3177 */ 3178 public static final int SCREEN_STATE_OFF = 0x0; 3179 3180 /** 3181 * Indicates that the screen has changed state and is now on. 3182 * 3183 * @see #onScreenStateChanged(int) 3184 */ 3185 public static final int SCREEN_STATE_ON = 0x1; 3186 3187 /** 3188 * Indicates no axis of view scrolling. 3189 */ 3190 public static final int SCROLL_AXIS_NONE = 0; 3191 3192 /** 3193 * Indicates scrolling along the horizontal axis. 3194 */ 3195 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3196 3197 /** 3198 * Indicates scrolling along the vertical axis. 3199 */ 3200 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3201 3202 /** 3203 * Controls the over-scroll mode for this view. 3204 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3205 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3206 * and {@link #OVER_SCROLL_NEVER}. 3207 */ 3208 private int mOverScrollMode; 3209 3210 /** 3211 * The parent this view is attached to. 3212 * {@hide} 3213 * 3214 * @see #getParent() 3215 */ 3216 protected ViewParent mParent; 3217 3218 /** 3219 * {@hide} 3220 */ 3221 AttachInfo mAttachInfo; 3222 3223 /** 3224 * {@hide} 3225 */ 3226 @ViewDebug.ExportedProperty(flagMapping = { 3227 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3228 name = "FORCE_LAYOUT"), 3229 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3230 name = "LAYOUT_REQUIRED"), 3231 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3232 name = "DRAWING_CACHE_INVALID", outputIf = false), 3233 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3234 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3235 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3236 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3237 }, formatToHexString = true) 3238 int mPrivateFlags; 3239 int mPrivateFlags2; 3240 int mPrivateFlags3; 3241 3242 /** 3243 * This view's request for the visibility of the status bar. 3244 * @hide 3245 */ 3246 @ViewDebug.ExportedProperty(flagMapping = { 3247 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3248 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3249 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3250 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3251 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3252 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3253 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3254 equals = SYSTEM_UI_FLAG_VISIBLE, 3255 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3256 }, formatToHexString = true) 3257 int mSystemUiVisibility; 3258 3259 /** 3260 * Reference count for transient state. 3261 * @see #setHasTransientState(boolean) 3262 */ 3263 int mTransientStateCount = 0; 3264 3265 /** 3266 * Count of how many windows this view has been attached to. 3267 */ 3268 int mWindowAttachCount; 3269 3270 /** 3271 * The layout parameters associated with this view and used by the parent 3272 * {@link android.view.ViewGroup} to determine how this view should be 3273 * laid out. 3274 * {@hide} 3275 */ 3276 protected ViewGroup.LayoutParams mLayoutParams; 3277 3278 /** 3279 * The view flags hold various views states. 3280 * {@hide} 3281 */ 3282 @ViewDebug.ExportedProperty(formatToHexString = true) 3283 int mViewFlags; 3284 3285 static class TransformationInfo { 3286 /** 3287 * The transform matrix for the View. This transform is calculated internally 3288 * based on the translation, rotation, and scale properties. 3289 * 3290 * Do *not* use this variable directly; instead call getMatrix(), which will 3291 * load the value from the View's RenderNode. 3292 */ 3293 private final Matrix mMatrix = new Matrix(); 3294 3295 /** 3296 * The inverse transform matrix for the View. This transform is calculated 3297 * internally based on the translation, rotation, and scale properties. 3298 * 3299 * Do *not* use this variable directly; instead call getInverseMatrix(), 3300 * which will load the value from the View's RenderNode. 3301 */ 3302 private Matrix mInverseMatrix; 3303 3304 /** 3305 * The opacity of the View. This is a value from 0 to 1, where 0 means 3306 * completely transparent and 1 means completely opaque. 3307 */ 3308 @ViewDebug.ExportedProperty 3309 float mAlpha = 1f; 3310 3311 /** 3312 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3313 * property only used by transitions, which is composited with the other alpha 3314 * values to calculate the final visual alpha value. 3315 */ 3316 float mTransitionAlpha = 1f; 3317 } 3318 3319 TransformationInfo mTransformationInfo; 3320 3321 /** 3322 * Current clip bounds. to which all drawing of this view are constrained. 3323 */ 3324 Rect mClipBounds = null; 3325 3326 private boolean mLastIsOpaque; 3327 3328 /** 3329 * The distance in pixels from the left edge of this view's parent 3330 * to the left edge of this view. 3331 * {@hide} 3332 */ 3333 @ViewDebug.ExportedProperty(category = "layout") 3334 protected int mLeft; 3335 /** 3336 * The distance in pixels from the left edge of this view's parent 3337 * to the right edge of this view. 3338 * {@hide} 3339 */ 3340 @ViewDebug.ExportedProperty(category = "layout") 3341 protected int mRight; 3342 /** 3343 * The distance in pixels from the top edge of this view's parent 3344 * to the top edge of this view. 3345 * {@hide} 3346 */ 3347 @ViewDebug.ExportedProperty(category = "layout") 3348 protected int mTop; 3349 /** 3350 * The distance in pixels from the top edge of this view's parent 3351 * to the bottom edge of this view. 3352 * {@hide} 3353 */ 3354 @ViewDebug.ExportedProperty(category = "layout") 3355 protected int mBottom; 3356 3357 /** 3358 * The offset, in pixels, by which the content of this view is scrolled 3359 * horizontally. 3360 * {@hide} 3361 */ 3362 @ViewDebug.ExportedProperty(category = "scrolling") 3363 protected int mScrollX; 3364 /** 3365 * The offset, in pixels, by which the content of this view is scrolled 3366 * vertically. 3367 * {@hide} 3368 */ 3369 @ViewDebug.ExportedProperty(category = "scrolling") 3370 protected int mScrollY; 3371 3372 /** 3373 * The left padding in pixels, that is the distance in pixels between the 3374 * left edge of this view and the left edge of its content. 3375 * {@hide} 3376 */ 3377 @ViewDebug.ExportedProperty(category = "padding") 3378 protected int mPaddingLeft = 0; 3379 /** 3380 * The right padding in pixels, that is the distance in pixels between the 3381 * right edge of this view and the right edge of its content. 3382 * {@hide} 3383 */ 3384 @ViewDebug.ExportedProperty(category = "padding") 3385 protected int mPaddingRight = 0; 3386 /** 3387 * The top padding in pixels, that is the distance in pixels between the 3388 * top edge of this view and the top edge of its content. 3389 * {@hide} 3390 */ 3391 @ViewDebug.ExportedProperty(category = "padding") 3392 protected int mPaddingTop; 3393 /** 3394 * The bottom padding in pixels, that is the distance in pixels between the 3395 * bottom edge of this view and the bottom edge of its content. 3396 * {@hide} 3397 */ 3398 @ViewDebug.ExportedProperty(category = "padding") 3399 protected int mPaddingBottom; 3400 3401 /** 3402 * The layout insets in pixels, that is the distance in pixels between the 3403 * visible edges of this view its bounds. 3404 */ 3405 private Insets mLayoutInsets; 3406 3407 /** 3408 * Briefly describes the view and is primarily used for accessibility support. 3409 */ 3410 private CharSequence mContentDescription; 3411 3412 /** 3413 * Specifies the id of a view for which this view serves as a label for 3414 * accessibility purposes. 3415 */ 3416 private int mLabelForId = View.NO_ID; 3417 3418 /** 3419 * Predicate for matching labeled view id with its label for 3420 * accessibility purposes. 3421 */ 3422 private MatchLabelForPredicate mMatchLabelForPredicate; 3423 3424 /** 3425 * Specifies a view before which this one is visited in accessibility traversal. 3426 */ 3427 private int mAccessibilityTraversalBeforeId = NO_ID; 3428 3429 /** 3430 * Specifies a view after which this one is visited in accessibility traversal. 3431 */ 3432 private int mAccessibilityTraversalAfterId = NO_ID; 3433 3434 /** 3435 * Predicate for matching a view by its id. 3436 */ 3437 private MatchIdPredicate mMatchIdPredicate; 3438 3439 /** 3440 * Cache the paddingRight set by the user to append to the scrollbar's size. 3441 * 3442 * @hide 3443 */ 3444 @ViewDebug.ExportedProperty(category = "padding") 3445 protected int mUserPaddingRight; 3446 3447 /** 3448 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3449 * 3450 * @hide 3451 */ 3452 @ViewDebug.ExportedProperty(category = "padding") 3453 protected int mUserPaddingBottom; 3454 3455 /** 3456 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3457 * 3458 * @hide 3459 */ 3460 @ViewDebug.ExportedProperty(category = "padding") 3461 protected int mUserPaddingLeft; 3462 3463 /** 3464 * Cache the paddingStart set by the user to append to the scrollbar's size. 3465 * 3466 */ 3467 @ViewDebug.ExportedProperty(category = "padding") 3468 int mUserPaddingStart; 3469 3470 /** 3471 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3472 * 3473 */ 3474 @ViewDebug.ExportedProperty(category = "padding") 3475 int mUserPaddingEnd; 3476 3477 /** 3478 * Cache initial left padding. 3479 * 3480 * @hide 3481 */ 3482 int mUserPaddingLeftInitial; 3483 3484 /** 3485 * Cache initial right padding. 3486 * 3487 * @hide 3488 */ 3489 int mUserPaddingRightInitial; 3490 3491 /** 3492 * Default undefined padding 3493 */ 3494 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3495 3496 /** 3497 * Cache if a left padding has been defined 3498 */ 3499 private boolean mLeftPaddingDefined = false; 3500 3501 /** 3502 * Cache if a right padding has been defined 3503 */ 3504 private boolean mRightPaddingDefined = false; 3505 3506 /** 3507 * @hide 3508 */ 3509 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3510 /** 3511 * @hide 3512 */ 3513 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3514 3515 private LongSparseLongArray mMeasureCache; 3516 3517 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3518 private Drawable mBackground; 3519 private TintInfo mBackgroundTint; 3520 3521 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3522 private ForegroundInfo mForegroundInfo; 3523 3524 private Drawable mScrollIndicatorDrawable; 3525 3526 /** 3527 * RenderNode used for backgrounds. 3528 * <p> 3529 * When non-null and valid, this is expected to contain an up-to-date copy 3530 * of the background drawable. It is cleared on temporary detach, and reset 3531 * on cleanup. 3532 */ 3533 private RenderNode mBackgroundRenderNode; 3534 3535 private int mBackgroundResource; 3536 private boolean mBackgroundSizeChanged; 3537 3538 private String mTransitionName; 3539 3540 static class TintInfo { 3541 ColorStateList mTintList; 3542 PorterDuff.Mode mTintMode; 3543 boolean mHasTintMode; 3544 boolean mHasTintList; 3545 } 3546 3547 private static class ForegroundInfo { 3548 private Drawable mDrawable; 3549 private TintInfo mTintInfo; 3550 private int mGravity = Gravity.FILL; 3551 private boolean mInsidePadding = true; 3552 private boolean mBoundsChanged = true; 3553 private final Rect mSelfBounds = new Rect(); 3554 private final Rect mOverlayBounds = new Rect(); 3555 } 3556 3557 static class ListenerInfo { 3558 /** 3559 * Listener used to dispatch focus change events. 3560 * This field should be made private, so it is hidden from the SDK. 3561 * {@hide} 3562 */ 3563 protected OnFocusChangeListener mOnFocusChangeListener; 3564 3565 /** 3566 * Listeners for layout change events. 3567 */ 3568 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3569 3570 protected OnScrollChangeListener mOnScrollChangeListener; 3571 3572 /** 3573 * Listeners for attach events. 3574 */ 3575 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3576 3577 /** 3578 * Listener used to dispatch click events. 3579 * This field should be made private, so it is hidden from the SDK. 3580 * {@hide} 3581 */ 3582 public OnClickListener mOnClickListener; 3583 3584 /** 3585 * Listener used to dispatch long click events. 3586 * This field should be made private, so it is hidden from the SDK. 3587 * {@hide} 3588 */ 3589 protected OnLongClickListener mOnLongClickListener; 3590 3591 /** 3592 * Listener used to dispatch context click events. This field should be made private, so it 3593 * is hidden from the SDK. 3594 * {@hide} 3595 */ 3596 protected OnContextClickListener mOnContextClickListener; 3597 3598 /** 3599 * Listener used to build the context menu. 3600 * This field should be made private, so it is hidden from the SDK. 3601 * {@hide} 3602 */ 3603 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3604 3605 private OnKeyListener mOnKeyListener; 3606 3607 private OnTouchListener mOnTouchListener; 3608 3609 private OnHoverListener mOnHoverListener; 3610 3611 private OnGenericMotionListener mOnGenericMotionListener; 3612 3613 private OnDragListener mOnDragListener; 3614 3615 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3616 3617 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3618 } 3619 3620 ListenerInfo mListenerInfo; 3621 3622 // Temporary values used to hold (x,y) coordinates when delegating from the 3623 // two-arg performLongClick() method to the legacy no-arg version. 3624 private float mLongClickX = Float.NaN; 3625 private float mLongClickY = Float.NaN; 3626 3627 /** 3628 * The application environment this view lives in. 3629 * This field should be made private, so it is hidden from the SDK. 3630 * {@hide} 3631 */ 3632 @ViewDebug.ExportedProperty(deepExport = true) 3633 protected Context mContext; 3634 3635 private final Resources mResources; 3636 3637 private ScrollabilityCache mScrollCache; 3638 3639 private int[] mDrawableState = null; 3640 3641 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3642 3643 /** 3644 * Animator that automatically runs based on state changes. 3645 */ 3646 private StateListAnimator mStateListAnimator; 3647 3648 /** 3649 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3650 * the user may specify which view to go to next. 3651 */ 3652 private int mNextFocusLeftId = View.NO_ID; 3653 3654 /** 3655 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3656 * the user may specify which view to go to next. 3657 */ 3658 private int mNextFocusRightId = View.NO_ID; 3659 3660 /** 3661 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3662 * the user may specify which view to go to next. 3663 */ 3664 private int mNextFocusUpId = View.NO_ID; 3665 3666 /** 3667 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3668 * the user may specify which view to go to next. 3669 */ 3670 private int mNextFocusDownId = View.NO_ID; 3671 3672 /** 3673 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3674 * the user may specify which view to go to next. 3675 */ 3676 int mNextFocusForwardId = View.NO_ID; 3677 3678 private CheckForLongPress mPendingCheckForLongPress; 3679 private CheckForTap mPendingCheckForTap = null; 3680 private PerformClick mPerformClick; 3681 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3682 3683 private UnsetPressedState mUnsetPressedState; 3684 3685 /** 3686 * Whether the long press's action has been invoked. The tap's action is invoked on the 3687 * up event while a long press is invoked as soon as the long press duration is reached, so 3688 * a long press could be performed before the tap is checked, in which case the tap's action 3689 * should not be invoked. 3690 */ 3691 private boolean mHasPerformedLongPress; 3692 3693 /** 3694 * Whether a context click button is currently pressed down. This is true when the stylus is 3695 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3696 * pressed. This is false once the button is released or if the stylus has been lifted. 3697 */ 3698 private boolean mInContextButtonPress; 3699 3700 /** 3701 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3702 * true after a stylus button press has occured, when the next up event should not be recognized 3703 * as a tap. 3704 */ 3705 private boolean mIgnoreNextUpEvent; 3706 3707 /** 3708 * The minimum height of the view. We'll try our best to have the height 3709 * of this view to at least this amount. 3710 */ 3711 @ViewDebug.ExportedProperty(category = "measurement") 3712 private int mMinHeight; 3713 3714 /** 3715 * The minimum width of the view. We'll try our best to have the width 3716 * of this view to at least this amount. 3717 */ 3718 @ViewDebug.ExportedProperty(category = "measurement") 3719 private int mMinWidth; 3720 3721 /** 3722 * The delegate to handle touch events that are physically in this view 3723 * but should be handled by another view. 3724 */ 3725 private TouchDelegate mTouchDelegate = null; 3726 3727 /** 3728 * Solid color to use as a background when creating the drawing cache. Enables 3729 * the cache to use 16 bit bitmaps instead of 32 bit. 3730 */ 3731 private int mDrawingCacheBackgroundColor = 0; 3732 3733 /** 3734 * Special tree observer used when mAttachInfo is null. 3735 */ 3736 private ViewTreeObserver mFloatingTreeObserver; 3737 3738 /** 3739 * Cache the touch slop from the context that created the view. 3740 */ 3741 private int mTouchSlop; 3742 3743 /** 3744 * Object that handles automatic animation of view properties. 3745 */ 3746 private ViewPropertyAnimator mAnimator = null; 3747 3748 /** 3749 * List of registered FrameMetricsObservers. 3750 */ 3751 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3752 3753 /** 3754 * Flag indicating that a drag can cross window boundaries. When 3755 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3756 * with this flag set, all visible applications with targetSdkVersion >= 3757 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 3758 * in the drag operation and receive the dragged content. 3759 * 3760 * <p>If this is the only flag set, then the drag recipient will only have access to text data 3761 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3762 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 3763 */ 3764 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3765 3766 /** 3767 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3768 * request read access to the content URI(s) contained in the {@link ClipData} object. 3769 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3770 */ 3771 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3772 3773 /** 3774 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3775 * request write access to the content URI(s) contained in the {@link ClipData} object. 3776 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3777 */ 3778 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3779 3780 /** 3781 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3782 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3783 * reboots until explicitly revoked with 3784 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3785 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3786 */ 3787 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3788 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3789 3790 /** 3791 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3792 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3793 * match against the original granted URI. 3794 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3795 */ 3796 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3797 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3798 3799 /** 3800 * Flag indicating that the drag shadow will be opaque. When 3801 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3802 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3803 */ 3804 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3805 3806 /** 3807 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3808 */ 3809 private float mVerticalScrollFactor; 3810 3811 /** 3812 * Position of the vertical scroll bar. 3813 */ 3814 private int mVerticalScrollbarPosition; 3815 3816 /** 3817 * Position the scroll bar at the default position as determined by the system. 3818 */ 3819 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3820 3821 /** 3822 * Position the scroll bar along the left edge. 3823 */ 3824 public static final int SCROLLBAR_POSITION_LEFT = 1; 3825 3826 /** 3827 * Position the scroll bar along the right edge. 3828 */ 3829 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3830 3831 /** 3832 * Indicates that the view does not have a layer. 3833 * 3834 * @see #getLayerType() 3835 * @see #setLayerType(int, android.graphics.Paint) 3836 * @see #LAYER_TYPE_SOFTWARE 3837 * @see #LAYER_TYPE_HARDWARE 3838 */ 3839 public static final int LAYER_TYPE_NONE = 0; 3840 3841 /** 3842 * <p>Indicates that the view has a software layer. A software layer is backed 3843 * by a bitmap and causes the view to be rendered using Android's software 3844 * rendering pipeline, even if hardware acceleration is enabled.</p> 3845 * 3846 * <p>Software layers have various usages:</p> 3847 * <p>When the application is not using hardware acceleration, a software layer 3848 * is useful to apply a specific color filter and/or blending mode and/or 3849 * translucency to a view and all its children.</p> 3850 * <p>When the application is using hardware acceleration, a software layer 3851 * is useful to render drawing primitives not supported by the hardware 3852 * accelerated pipeline. It can also be used to cache a complex view tree 3853 * into a texture and reduce the complexity of drawing operations. For instance, 3854 * when animating a complex view tree with a translation, a software layer can 3855 * be used to render the view tree only once.</p> 3856 * <p>Software layers should be avoided when the affected view tree updates 3857 * often. Every update will require to re-render the software layer, which can 3858 * potentially be slow (particularly when hardware acceleration is turned on 3859 * since the layer will have to be uploaded into a hardware texture after every 3860 * update.)</p> 3861 * 3862 * @see #getLayerType() 3863 * @see #setLayerType(int, android.graphics.Paint) 3864 * @see #LAYER_TYPE_NONE 3865 * @see #LAYER_TYPE_HARDWARE 3866 */ 3867 public static final int LAYER_TYPE_SOFTWARE = 1; 3868 3869 /** 3870 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3871 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3872 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3873 * rendering pipeline, but only if hardware acceleration is turned on for the 3874 * view hierarchy. When hardware acceleration is turned off, hardware layers 3875 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3876 * 3877 * <p>A hardware layer is useful to apply a specific color filter and/or 3878 * blending mode and/or translucency to a view and all its children.</p> 3879 * <p>A hardware layer can be used to cache a complex view tree into a 3880 * texture and reduce the complexity of drawing operations. For instance, 3881 * when animating a complex view tree with a translation, a hardware layer can 3882 * be used to render the view tree only once.</p> 3883 * <p>A hardware layer can also be used to increase the rendering quality when 3884 * rotation transformations are applied on a view. It can also be used to 3885 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3886 * 3887 * @see #getLayerType() 3888 * @see #setLayerType(int, android.graphics.Paint) 3889 * @see #LAYER_TYPE_NONE 3890 * @see #LAYER_TYPE_SOFTWARE 3891 */ 3892 public static final int LAYER_TYPE_HARDWARE = 2; 3893 3894 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3895 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3896 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3897 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3898 }) 3899 int mLayerType = LAYER_TYPE_NONE; 3900 Paint mLayerPaint; 3901 3902 /** 3903 * Set to true when drawing cache is enabled and cannot be created. 3904 * 3905 * @hide 3906 */ 3907 public boolean mCachingFailed; 3908 private Bitmap mDrawingCache; 3909 private Bitmap mUnscaledDrawingCache; 3910 3911 /** 3912 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3913 * <p> 3914 * When non-null and valid, this is expected to contain an up-to-date copy 3915 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3916 * cleanup. 3917 */ 3918 final RenderNode mRenderNode; 3919 3920 /** 3921 * Set to true when the view is sending hover accessibility events because it 3922 * is the innermost hovered view. 3923 */ 3924 private boolean mSendingHoverAccessibilityEvents; 3925 3926 /** 3927 * Delegate for injecting accessibility functionality. 3928 */ 3929 AccessibilityDelegate mAccessibilityDelegate; 3930 3931 /** 3932 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3933 * and add/remove objects to/from the overlay directly through the Overlay methods. 3934 */ 3935 ViewOverlay mOverlay; 3936 3937 /** 3938 * The currently active parent view for receiving delegated nested scrolling events. 3939 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3940 * by {@link #stopNestedScroll()} at the same point where we clear 3941 * requestDisallowInterceptTouchEvent. 3942 */ 3943 private ViewParent mNestedScrollingParent; 3944 3945 /** 3946 * Consistency verifier for debugging purposes. 3947 * @hide 3948 */ 3949 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3950 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3951 new InputEventConsistencyVerifier(this, 0) : null; 3952 3953 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3954 3955 private int[] mTempNestedScrollConsumed; 3956 3957 /** 3958 * An overlay is going to draw this View instead of being drawn as part of this 3959 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3960 * when this view is invalidated. 3961 */ 3962 GhostView mGhostView; 3963 3964 /** 3965 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3966 * @hide 3967 */ 3968 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3969 public String[] mAttributes; 3970 3971 /** 3972 * Maps a Resource id to its name. 3973 */ 3974 private static SparseArray<String> mAttributeMap; 3975 3976 /** 3977 * Queue of pending runnables. Used to postpone calls to post() until this 3978 * view is attached and has a handler. 3979 */ 3980 private HandlerActionQueue mRunQueue; 3981 3982 /** 3983 * The pointer icon when the mouse hovers on this view. The default is null. 3984 */ 3985 private PointerIcon mPointerIcon; 3986 3987 /** 3988 * @hide 3989 */ 3990 String mStartActivityRequestWho; 3991 3992 @Nullable 3993 private RoundScrollbarRenderer mRoundScrollbarRenderer; 3994 3995 /** 3996 * Simple constructor to use when creating a view from code. 3997 * 3998 * @param context The Context the view is running in, through which it can 3999 * access the current theme, resources, etc. 4000 */ 4001 public View(Context context) { 4002 mContext = context; 4003 mResources = context != null ? context.getResources() : null; 4004 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 4005 // Set some flags defaults 4006 mPrivateFlags2 = 4007 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 4008 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 4009 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 4010 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4011 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4012 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4013 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4014 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4015 mUserPaddingStart = UNDEFINED_PADDING; 4016 mUserPaddingEnd = UNDEFINED_PADDING; 4017 mRenderNode = RenderNode.create(getClass().getName(), this); 4018 4019 if (!sCompatibilityDone && context != null) { 4020 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4021 4022 // Older apps may need this compatibility hack for measurement. 4023 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4024 4025 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4026 // of whether a layout was requested on that View. 4027 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4028 4029 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4030 4031 // In M and newer, our widgets can pass a "hint" value in the size 4032 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4033 // know what the expected parent size is going to be, so e.g. list items can size 4034 // themselves at 1/3 the size of their container. It breaks older apps though, 4035 // specifically apps that use some popular open source libraries. 4036 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4037 4038 // Old versions of the platform would give different results from 4039 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4040 // modes, so we always need to run an additional EXACTLY pass. 4041 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4042 4043 // Prior to N, layout params could change without requiring a 4044 // subsequent call to setLayoutParams() and they would usually 4045 // work. Partial layout breaks this assumption. 4046 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4047 4048 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4049 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4050 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4051 4052 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4053 // in apps so we target check it to avoid breaking existing apps. 4054 sPreserveMarginParamsInLayoutParamConversion = targetSdkVersion >= N; 4055 4056 sCascadedDragDrop = targetSdkVersion < N; 4057 4058 sCompatibilityDone = true; 4059 } 4060 } 4061 4062 /** 4063 * Constructor that is called when inflating a view from XML. This is called 4064 * when a view is being constructed from an XML file, supplying attributes 4065 * that were specified in the XML file. This version uses a default style of 4066 * 0, so the only attribute values applied are those in the Context's Theme 4067 * and the given AttributeSet. 4068 * 4069 * <p> 4070 * The method onFinishInflate() will be called after all children have been 4071 * added. 4072 * 4073 * @param context The Context the view is running in, through which it can 4074 * access the current theme, resources, etc. 4075 * @param attrs The attributes of the XML tag that is inflating the view. 4076 * @see #View(Context, AttributeSet, int) 4077 */ 4078 public View(Context context, @Nullable AttributeSet attrs) { 4079 this(context, attrs, 0); 4080 } 4081 4082 /** 4083 * Perform inflation from XML and apply a class-specific base style from a 4084 * theme attribute. This constructor of View allows subclasses to use their 4085 * own base style when they are inflating. For example, a Button class's 4086 * constructor would call this version of the super class constructor and 4087 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4088 * allows the theme's button style to modify all of the base view attributes 4089 * (in particular its background) as well as the Button class's attributes. 4090 * 4091 * @param context The Context the view is running in, through which it can 4092 * access the current theme, resources, etc. 4093 * @param attrs The attributes of the XML tag that is inflating the view. 4094 * @param defStyleAttr An attribute in the current theme that contains a 4095 * reference to a style resource that supplies default values for 4096 * the view. Can be 0 to not look for defaults. 4097 * @see #View(Context, AttributeSet) 4098 */ 4099 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4100 this(context, attrs, defStyleAttr, 0); 4101 } 4102 4103 /** 4104 * Perform inflation from XML and apply a class-specific base style from a 4105 * theme attribute or style resource. This constructor of View allows 4106 * subclasses to use their own base style when they are inflating. 4107 * <p> 4108 * When determining the final value of a particular attribute, there are 4109 * four inputs that come into play: 4110 * <ol> 4111 * <li>Any attribute values in the given AttributeSet. 4112 * <li>The style resource specified in the AttributeSet (named "style"). 4113 * <li>The default style specified by <var>defStyleAttr</var>. 4114 * <li>The default style specified by <var>defStyleRes</var>. 4115 * <li>The base values in this theme. 4116 * </ol> 4117 * <p> 4118 * Each of these inputs is considered in-order, with the first listed taking 4119 * precedence over the following ones. In other words, if in the 4120 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4121 * , then the button's text will <em>always</em> be black, regardless of 4122 * what is specified in any of the styles. 4123 * 4124 * @param context The Context the view is running in, through which it can 4125 * access the current theme, resources, etc. 4126 * @param attrs The attributes of the XML tag that is inflating the view. 4127 * @param defStyleAttr An attribute in the current theme that contains a 4128 * reference to a style resource that supplies default values for 4129 * the view. Can be 0 to not look for defaults. 4130 * @param defStyleRes A resource identifier of a style resource that 4131 * supplies default values for the view, used only if 4132 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4133 * to not look for defaults. 4134 * @see #View(Context, AttributeSet, int) 4135 */ 4136 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4137 this(context); 4138 4139 final TypedArray a = context.obtainStyledAttributes( 4140 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4141 4142 if (mDebugViewAttributes) { 4143 saveAttributeData(attrs, a); 4144 } 4145 4146 Drawable background = null; 4147 4148 int leftPadding = -1; 4149 int topPadding = -1; 4150 int rightPadding = -1; 4151 int bottomPadding = -1; 4152 int startPadding = UNDEFINED_PADDING; 4153 int endPadding = UNDEFINED_PADDING; 4154 4155 int padding = -1; 4156 4157 int viewFlagValues = 0; 4158 int viewFlagMasks = 0; 4159 4160 boolean setScrollContainer = false; 4161 4162 int x = 0; 4163 int y = 0; 4164 4165 float tx = 0; 4166 float ty = 0; 4167 float tz = 0; 4168 float elevation = 0; 4169 float rotation = 0; 4170 float rotationX = 0; 4171 float rotationY = 0; 4172 float sx = 1f; 4173 float sy = 1f; 4174 boolean transformSet = false; 4175 4176 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4177 int overScrollMode = mOverScrollMode; 4178 boolean initializeScrollbars = false; 4179 boolean initializeScrollIndicators = false; 4180 4181 boolean startPaddingDefined = false; 4182 boolean endPaddingDefined = false; 4183 boolean leftPaddingDefined = false; 4184 boolean rightPaddingDefined = false; 4185 4186 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4187 4188 final int N = a.getIndexCount(); 4189 for (int i = 0; i < N; i++) { 4190 int attr = a.getIndex(i); 4191 switch (attr) { 4192 case com.android.internal.R.styleable.View_background: 4193 background = a.getDrawable(attr); 4194 break; 4195 case com.android.internal.R.styleable.View_padding: 4196 padding = a.getDimensionPixelSize(attr, -1); 4197 mUserPaddingLeftInitial = padding; 4198 mUserPaddingRightInitial = padding; 4199 leftPaddingDefined = true; 4200 rightPaddingDefined = true; 4201 break; 4202 case com.android.internal.R.styleable.View_paddingLeft: 4203 leftPadding = a.getDimensionPixelSize(attr, -1); 4204 mUserPaddingLeftInitial = leftPadding; 4205 leftPaddingDefined = true; 4206 break; 4207 case com.android.internal.R.styleable.View_paddingTop: 4208 topPadding = a.getDimensionPixelSize(attr, -1); 4209 break; 4210 case com.android.internal.R.styleable.View_paddingRight: 4211 rightPadding = a.getDimensionPixelSize(attr, -1); 4212 mUserPaddingRightInitial = rightPadding; 4213 rightPaddingDefined = true; 4214 break; 4215 case com.android.internal.R.styleable.View_paddingBottom: 4216 bottomPadding = a.getDimensionPixelSize(attr, -1); 4217 break; 4218 case com.android.internal.R.styleable.View_paddingStart: 4219 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4220 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4221 break; 4222 case com.android.internal.R.styleable.View_paddingEnd: 4223 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4224 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4225 break; 4226 case com.android.internal.R.styleable.View_scrollX: 4227 x = a.getDimensionPixelOffset(attr, 0); 4228 break; 4229 case com.android.internal.R.styleable.View_scrollY: 4230 y = a.getDimensionPixelOffset(attr, 0); 4231 break; 4232 case com.android.internal.R.styleable.View_alpha: 4233 setAlpha(a.getFloat(attr, 1f)); 4234 break; 4235 case com.android.internal.R.styleable.View_transformPivotX: 4236 setPivotX(a.getDimension(attr, 0)); 4237 break; 4238 case com.android.internal.R.styleable.View_transformPivotY: 4239 setPivotY(a.getDimension(attr, 0)); 4240 break; 4241 case com.android.internal.R.styleable.View_translationX: 4242 tx = a.getDimension(attr, 0); 4243 transformSet = true; 4244 break; 4245 case com.android.internal.R.styleable.View_translationY: 4246 ty = a.getDimension(attr, 0); 4247 transformSet = true; 4248 break; 4249 case com.android.internal.R.styleable.View_translationZ: 4250 tz = a.getDimension(attr, 0); 4251 transformSet = true; 4252 break; 4253 case com.android.internal.R.styleable.View_elevation: 4254 elevation = a.getDimension(attr, 0); 4255 transformSet = true; 4256 break; 4257 case com.android.internal.R.styleable.View_rotation: 4258 rotation = a.getFloat(attr, 0); 4259 transformSet = true; 4260 break; 4261 case com.android.internal.R.styleable.View_rotationX: 4262 rotationX = a.getFloat(attr, 0); 4263 transformSet = true; 4264 break; 4265 case com.android.internal.R.styleable.View_rotationY: 4266 rotationY = a.getFloat(attr, 0); 4267 transformSet = true; 4268 break; 4269 case com.android.internal.R.styleable.View_scaleX: 4270 sx = a.getFloat(attr, 1f); 4271 transformSet = true; 4272 break; 4273 case com.android.internal.R.styleable.View_scaleY: 4274 sy = a.getFloat(attr, 1f); 4275 transformSet = true; 4276 break; 4277 case com.android.internal.R.styleable.View_id: 4278 mID = a.getResourceId(attr, NO_ID); 4279 break; 4280 case com.android.internal.R.styleable.View_tag: 4281 mTag = a.getText(attr); 4282 break; 4283 case com.android.internal.R.styleable.View_fitsSystemWindows: 4284 if (a.getBoolean(attr, false)) { 4285 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4286 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4287 } 4288 break; 4289 case com.android.internal.R.styleable.View_focusable: 4290 if (a.getBoolean(attr, false)) { 4291 viewFlagValues |= FOCUSABLE; 4292 viewFlagMasks |= FOCUSABLE_MASK; 4293 } 4294 break; 4295 case com.android.internal.R.styleable.View_focusableInTouchMode: 4296 if (a.getBoolean(attr, false)) { 4297 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4298 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4299 } 4300 break; 4301 case com.android.internal.R.styleable.View_clickable: 4302 if (a.getBoolean(attr, false)) { 4303 viewFlagValues |= CLICKABLE; 4304 viewFlagMasks |= CLICKABLE; 4305 } 4306 break; 4307 case com.android.internal.R.styleable.View_longClickable: 4308 if (a.getBoolean(attr, false)) { 4309 viewFlagValues |= LONG_CLICKABLE; 4310 viewFlagMasks |= LONG_CLICKABLE; 4311 } 4312 break; 4313 case com.android.internal.R.styleable.View_contextClickable: 4314 if (a.getBoolean(attr, false)) { 4315 viewFlagValues |= CONTEXT_CLICKABLE; 4316 viewFlagMasks |= CONTEXT_CLICKABLE; 4317 } 4318 break; 4319 case com.android.internal.R.styleable.View_saveEnabled: 4320 if (!a.getBoolean(attr, true)) { 4321 viewFlagValues |= SAVE_DISABLED; 4322 viewFlagMasks |= SAVE_DISABLED_MASK; 4323 } 4324 break; 4325 case com.android.internal.R.styleable.View_duplicateParentState: 4326 if (a.getBoolean(attr, false)) { 4327 viewFlagValues |= DUPLICATE_PARENT_STATE; 4328 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4329 } 4330 break; 4331 case com.android.internal.R.styleable.View_visibility: 4332 final int visibility = a.getInt(attr, 0); 4333 if (visibility != 0) { 4334 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4335 viewFlagMasks |= VISIBILITY_MASK; 4336 } 4337 break; 4338 case com.android.internal.R.styleable.View_layoutDirection: 4339 // Clear any layout direction flags (included resolved bits) already set 4340 mPrivateFlags2 &= 4341 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4342 // Set the layout direction flags depending on the value of the attribute 4343 final int layoutDirection = a.getInt(attr, -1); 4344 final int value = (layoutDirection != -1) ? 4345 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4346 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4347 break; 4348 case com.android.internal.R.styleable.View_drawingCacheQuality: 4349 final int cacheQuality = a.getInt(attr, 0); 4350 if (cacheQuality != 0) { 4351 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4352 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4353 } 4354 break; 4355 case com.android.internal.R.styleable.View_contentDescription: 4356 setContentDescription(a.getString(attr)); 4357 break; 4358 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4359 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4360 break; 4361 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4362 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4363 break; 4364 case com.android.internal.R.styleable.View_labelFor: 4365 setLabelFor(a.getResourceId(attr, NO_ID)); 4366 break; 4367 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4368 if (!a.getBoolean(attr, true)) { 4369 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4370 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4371 } 4372 break; 4373 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4374 if (!a.getBoolean(attr, true)) { 4375 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4376 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4377 } 4378 break; 4379 case R.styleable.View_scrollbars: 4380 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4381 if (scrollbars != SCROLLBARS_NONE) { 4382 viewFlagValues |= scrollbars; 4383 viewFlagMasks |= SCROLLBARS_MASK; 4384 initializeScrollbars = true; 4385 } 4386 break; 4387 //noinspection deprecation 4388 case R.styleable.View_fadingEdge: 4389 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4390 // Ignore the attribute starting with ICS 4391 break; 4392 } 4393 // With builds < ICS, fall through and apply fading edges 4394 case R.styleable.View_requiresFadingEdge: 4395 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4396 if (fadingEdge != FADING_EDGE_NONE) { 4397 viewFlagValues |= fadingEdge; 4398 viewFlagMasks |= FADING_EDGE_MASK; 4399 initializeFadingEdgeInternal(a); 4400 } 4401 break; 4402 case R.styleable.View_scrollbarStyle: 4403 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4404 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4405 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4406 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4407 } 4408 break; 4409 case R.styleable.View_isScrollContainer: 4410 setScrollContainer = true; 4411 if (a.getBoolean(attr, false)) { 4412 setScrollContainer(true); 4413 } 4414 break; 4415 case com.android.internal.R.styleable.View_keepScreenOn: 4416 if (a.getBoolean(attr, false)) { 4417 viewFlagValues |= KEEP_SCREEN_ON; 4418 viewFlagMasks |= KEEP_SCREEN_ON; 4419 } 4420 break; 4421 case R.styleable.View_filterTouchesWhenObscured: 4422 if (a.getBoolean(attr, false)) { 4423 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4424 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4425 } 4426 break; 4427 case R.styleable.View_nextFocusLeft: 4428 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4429 break; 4430 case R.styleable.View_nextFocusRight: 4431 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4432 break; 4433 case R.styleable.View_nextFocusUp: 4434 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4435 break; 4436 case R.styleable.View_nextFocusDown: 4437 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4438 break; 4439 case R.styleable.View_nextFocusForward: 4440 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4441 break; 4442 case R.styleable.View_minWidth: 4443 mMinWidth = a.getDimensionPixelSize(attr, 0); 4444 break; 4445 case R.styleable.View_minHeight: 4446 mMinHeight = a.getDimensionPixelSize(attr, 0); 4447 break; 4448 case R.styleable.View_onClick: 4449 if (context.isRestricted()) { 4450 throw new IllegalStateException("The android:onClick attribute cannot " 4451 + "be used within a restricted context"); 4452 } 4453 4454 final String handlerName = a.getString(attr); 4455 if (handlerName != null) { 4456 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4457 } 4458 break; 4459 case R.styleable.View_overScrollMode: 4460 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4461 break; 4462 case R.styleable.View_verticalScrollbarPosition: 4463 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4464 break; 4465 case R.styleable.View_layerType: 4466 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4467 break; 4468 case R.styleable.View_textDirection: 4469 // Clear any text direction flag already set 4470 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4471 // Set the text direction flags depending on the value of the attribute 4472 final int textDirection = a.getInt(attr, -1); 4473 if (textDirection != -1) { 4474 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4475 } 4476 break; 4477 case R.styleable.View_textAlignment: 4478 // Clear any text alignment flag already set 4479 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4480 // Set the text alignment flag depending on the value of the attribute 4481 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4482 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4483 break; 4484 case R.styleable.View_importantForAccessibility: 4485 setImportantForAccessibility(a.getInt(attr, 4486 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4487 break; 4488 case R.styleable.View_accessibilityLiveRegion: 4489 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4490 break; 4491 case R.styleable.View_transitionName: 4492 setTransitionName(a.getString(attr)); 4493 break; 4494 case R.styleable.View_nestedScrollingEnabled: 4495 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4496 break; 4497 case R.styleable.View_stateListAnimator: 4498 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4499 a.getResourceId(attr, 0))); 4500 break; 4501 case R.styleable.View_backgroundTint: 4502 // This will get applied later during setBackground(). 4503 if (mBackgroundTint == null) { 4504 mBackgroundTint = new TintInfo(); 4505 } 4506 mBackgroundTint.mTintList = a.getColorStateList( 4507 R.styleable.View_backgroundTint); 4508 mBackgroundTint.mHasTintList = true; 4509 break; 4510 case R.styleable.View_backgroundTintMode: 4511 // This will get applied later during setBackground(). 4512 if (mBackgroundTint == null) { 4513 mBackgroundTint = new TintInfo(); 4514 } 4515 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4516 R.styleable.View_backgroundTintMode, -1), null); 4517 mBackgroundTint.mHasTintMode = true; 4518 break; 4519 case R.styleable.View_outlineProvider: 4520 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4521 PROVIDER_BACKGROUND)); 4522 break; 4523 case R.styleable.View_foreground: 4524 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4525 setForeground(a.getDrawable(attr)); 4526 } 4527 break; 4528 case R.styleable.View_foregroundGravity: 4529 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4530 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4531 } 4532 break; 4533 case R.styleable.View_foregroundTintMode: 4534 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4535 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4536 } 4537 break; 4538 case R.styleable.View_foregroundTint: 4539 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4540 setForegroundTintList(a.getColorStateList(attr)); 4541 } 4542 break; 4543 case R.styleable.View_foregroundInsidePadding: 4544 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4545 if (mForegroundInfo == null) { 4546 mForegroundInfo = new ForegroundInfo(); 4547 } 4548 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4549 mForegroundInfo.mInsidePadding); 4550 } 4551 break; 4552 case R.styleable.View_scrollIndicators: 4553 final int scrollIndicators = 4554 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4555 & SCROLL_INDICATORS_PFLAG3_MASK; 4556 if (scrollIndicators != 0) { 4557 mPrivateFlags3 |= scrollIndicators; 4558 initializeScrollIndicators = true; 4559 } 4560 break; 4561 case R.styleable.View_pointerIcon: 4562 final int resourceId = a.getResourceId(attr, 0); 4563 if (resourceId != 0) { 4564 setPointerIcon(PointerIcon.load( 4565 context.getResources(), resourceId)); 4566 } else { 4567 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 4568 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 4569 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 4570 } 4571 } 4572 break; 4573 case R.styleable.View_forceHasOverlappingRendering: 4574 if (a.peekValue(attr) != null) { 4575 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4576 } 4577 break; 4578 4579 } 4580 } 4581 4582 setOverScrollMode(overScrollMode); 4583 4584 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4585 // the resolved layout direction). Those cached values will be used later during padding 4586 // resolution. 4587 mUserPaddingStart = startPadding; 4588 mUserPaddingEnd = endPadding; 4589 4590 if (background != null) { 4591 setBackground(background); 4592 } 4593 4594 // setBackground above will record that padding is currently provided by the background. 4595 // If we have padding specified via xml, record that here instead and use it. 4596 mLeftPaddingDefined = leftPaddingDefined; 4597 mRightPaddingDefined = rightPaddingDefined; 4598 4599 if (padding >= 0) { 4600 leftPadding = padding; 4601 topPadding = padding; 4602 rightPadding = padding; 4603 bottomPadding = padding; 4604 mUserPaddingLeftInitial = padding; 4605 mUserPaddingRightInitial = padding; 4606 } 4607 4608 if (isRtlCompatibilityMode()) { 4609 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4610 // left / right padding are used if defined (meaning here nothing to do). If they are not 4611 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4612 // start / end and resolve them as left / right (layout direction is not taken into account). 4613 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4614 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4615 // defined. 4616 if (!mLeftPaddingDefined && startPaddingDefined) { 4617 leftPadding = startPadding; 4618 } 4619 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4620 if (!mRightPaddingDefined && endPaddingDefined) { 4621 rightPadding = endPadding; 4622 } 4623 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4624 } else { 4625 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4626 // values defined. Otherwise, left /right values are used. 4627 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4628 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4629 // defined. 4630 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4631 4632 if (mLeftPaddingDefined && !hasRelativePadding) { 4633 mUserPaddingLeftInitial = leftPadding; 4634 } 4635 if (mRightPaddingDefined && !hasRelativePadding) { 4636 mUserPaddingRightInitial = rightPadding; 4637 } 4638 } 4639 4640 internalSetPadding( 4641 mUserPaddingLeftInitial, 4642 topPadding >= 0 ? topPadding : mPaddingTop, 4643 mUserPaddingRightInitial, 4644 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4645 4646 if (viewFlagMasks != 0) { 4647 setFlags(viewFlagValues, viewFlagMasks); 4648 } 4649 4650 if (initializeScrollbars) { 4651 initializeScrollbarsInternal(a); 4652 } 4653 4654 if (initializeScrollIndicators) { 4655 initializeScrollIndicatorsInternal(); 4656 } 4657 4658 a.recycle(); 4659 4660 // Needs to be called after mViewFlags is set 4661 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4662 recomputePadding(); 4663 } 4664 4665 if (x != 0 || y != 0) { 4666 scrollTo(x, y); 4667 } 4668 4669 if (transformSet) { 4670 setTranslationX(tx); 4671 setTranslationY(ty); 4672 setTranslationZ(tz); 4673 setElevation(elevation); 4674 setRotation(rotation); 4675 setRotationX(rotationX); 4676 setRotationY(rotationY); 4677 setScaleX(sx); 4678 setScaleY(sy); 4679 } 4680 4681 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4682 setScrollContainer(true); 4683 } 4684 4685 computeOpaqueFlags(); 4686 } 4687 4688 /** 4689 * An implementation of OnClickListener that attempts to lazily load a 4690 * named click handling method from a parent or ancestor context. 4691 */ 4692 private static class DeclaredOnClickListener implements OnClickListener { 4693 private final View mHostView; 4694 private final String mMethodName; 4695 4696 private Method mResolvedMethod; 4697 private Context mResolvedContext; 4698 4699 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4700 mHostView = hostView; 4701 mMethodName = methodName; 4702 } 4703 4704 @Override 4705 public void onClick(@NonNull View v) { 4706 if (mResolvedMethod == null) { 4707 resolveMethod(mHostView.getContext(), mMethodName); 4708 } 4709 4710 try { 4711 mResolvedMethod.invoke(mResolvedContext, v); 4712 } catch (IllegalAccessException e) { 4713 throw new IllegalStateException( 4714 "Could not execute non-public method for android:onClick", e); 4715 } catch (InvocationTargetException e) { 4716 throw new IllegalStateException( 4717 "Could not execute method for android:onClick", e); 4718 } 4719 } 4720 4721 @NonNull 4722 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4723 while (context != null) { 4724 try { 4725 if (!context.isRestricted()) { 4726 final Method method = context.getClass().getMethod(mMethodName, View.class); 4727 if (method != null) { 4728 mResolvedMethod = method; 4729 mResolvedContext = context; 4730 return; 4731 } 4732 } 4733 } catch (NoSuchMethodException e) { 4734 // Failed to find method, keep searching up the hierarchy. 4735 } 4736 4737 if (context instanceof ContextWrapper) { 4738 context = ((ContextWrapper) context).getBaseContext(); 4739 } else { 4740 // Can't search up the hierarchy, null out and fail. 4741 context = null; 4742 } 4743 } 4744 4745 final int id = mHostView.getId(); 4746 final String idText = id == NO_ID ? "" : " with id '" 4747 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4748 throw new IllegalStateException("Could not find method " + mMethodName 4749 + "(View) in a parent or ancestor Context for android:onClick " 4750 + "attribute defined on view " + mHostView.getClass() + idText); 4751 } 4752 } 4753 4754 /** 4755 * Non-public constructor for use in testing 4756 */ 4757 View() { 4758 mResources = null; 4759 mRenderNode = RenderNode.create(getClass().getName(), this); 4760 } 4761 4762 final boolean debugDraw() { 4763 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout; 4764 } 4765 4766 private static SparseArray<String> getAttributeMap() { 4767 if (mAttributeMap == null) { 4768 mAttributeMap = new SparseArray<>(); 4769 } 4770 return mAttributeMap; 4771 } 4772 4773 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4774 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4775 final int indexCount = t.getIndexCount(); 4776 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4777 4778 int i = 0; 4779 4780 // Store raw XML attributes. 4781 for (int j = 0; j < attrsCount; ++j) { 4782 attributes[i] = attrs.getAttributeName(j); 4783 attributes[i + 1] = attrs.getAttributeValue(j); 4784 i += 2; 4785 } 4786 4787 // Store resolved styleable attributes. 4788 final Resources res = t.getResources(); 4789 final SparseArray<String> attributeMap = getAttributeMap(); 4790 for (int j = 0; j < indexCount; ++j) { 4791 final int index = t.getIndex(j); 4792 if (!t.hasValueOrEmpty(index)) { 4793 // Value is undefined. Skip it. 4794 continue; 4795 } 4796 4797 final int resourceId = t.getResourceId(index, 0); 4798 if (resourceId == 0) { 4799 // Value is not a reference. Skip it. 4800 continue; 4801 } 4802 4803 String resourceName = attributeMap.get(resourceId); 4804 if (resourceName == null) { 4805 try { 4806 resourceName = res.getResourceName(resourceId); 4807 } catch (Resources.NotFoundException e) { 4808 resourceName = "0x" + Integer.toHexString(resourceId); 4809 } 4810 attributeMap.put(resourceId, resourceName); 4811 } 4812 4813 attributes[i] = resourceName; 4814 attributes[i + 1] = t.getString(index); 4815 i += 2; 4816 } 4817 4818 // Trim to fit contents. 4819 final String[] trimmed = new String[i]; 4820 System.arraycopy(attributes, 0, trimmed, 0, i); 4821 mAttributes = trimmed; 4822 } 4823 4824 public String toString() { 4825 StringBuilder out = new StringBuilder(128); 4826 out.append(getClass().getName()); 4827 out.append('{'); 4828 out.append(Integer.toHexString(System.identityHashCode(this))); 4829 out.append(' '); 4830 switch (mViewFlags&VISIBILITY_MASK) { 4831 case VISIBLE: out.append('V'); break; 4832 case INVISIBLE: out.append('I'); break; 4833 case GONE: out.append('G'); break; 4834 default: out.append('.'); break; 4835 } 4836 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4837 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4838 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4839 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4840 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4841 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4842 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4843 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4844 out.append(' '); 4845 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4846 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4847 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4848 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4849 out.append('p'); 4850 } else { 4851 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4852 } 4853 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4854 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4855 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4856 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4857 out.append(' '); 4858 out.append(mLeft); 4859 out.append(','); 4860 out.append(mTop); 4861 out.append('-'); 4862 out.append(mRight); 4863 out.append(','); 4864 out.append(mBottom); 4865 final int id = getId(); 4866 if (id != NO_ID) { 4867 out.append(" #"); 4868 out.append(Integer.toHexString(id)); 4869 final Resources r = mResources; 4870 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4871 try { 4872 String pkgname; 4873 switch (id&0xff000000) { 4874 case 0x7f000000: 4875 pkgname="app"; 4876 break; 4877 case 0x01000000: 4878 pkgname="android"; 4879 break; 4880 default: 4881 pkgname = r.getResourcePackageName(id); 4882 break; 4883 } 4884 String typename = r.getResourceTypeName(id); 4885 String entryname = r.getResourceEntryName(id); 4886 out.append(" "); 4887 out.append(pkgname); 4888 out.append(":"); 4889 out.append(typename); 4890 out.append("/"); 4891 out.append(entryname); 4892 } catch (Resources.NotFoundException e) { 4893 } 4894 } 4895 } 4896 out.append("}"); 4897 return out.toString(); 4898 } 4899 4900 /** 4901 * <p> 4902 * Initializes the fading edges from a given set of styled attributes. This 4903 * method should be called by subclasses that need fading edges and when an 4904 * instance of these subclasses is created programmatically rather than 4905 * being inflated from XML. This method is automatically called when the XML 4906 * is inflated. 4907 * </p> 4908 * 4909 * @param a the styled attributes set to initialize the fading edges from 4910 * 4911 * @removed 4912 */ 4913 protected void initializeFadingEdge(TypedArray a) { 4914 // This method probably shouldn't have been included in the SDK to begin with. 4915 // It relies on 'a' having been initialized using an attribute filter array that is 4916 // not publicly available to the SDK. The old method has been renamed 4917 // to initializeFadingEdgeInternal and hidden for framework use only; 4918 // this one initializes using defaults to make it safe to call for apps. 4919 4920 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4921 4922 initializeFadingEdgeInternal(arr); 4923 4924 arr.recycle(); 4925 } 4926 4927 /** 4928 * <p> 4929 * Initializes the fading edges from a given set of styled attributes. This 4930 * method should be called by subclasses that need fading edges and when an 4931 * instance of these subclasses is created programmatically rather than 4932 * being inflated from XML. This method is automatically called when the XML 4933 * is inflated. 4934 * </p> 4935 * 4936 * @param a the styled attributes set to initialize the fading edges from 4937 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4938 */ 4939 protected void initializeFadingEdgeInternal(TypedArray a) { 4940 initScrollCache(); 4941 4942 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4943 R.styleable.View_fadingEdgeLength, 4944 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4945 } 4946 4947 /** 4948 * Returns the size of the vertical faded edges used to indicate that more 4949 * content in this view is visible. 4950 * 4951 * @return The size in pixels of the vertical faded edge or 0 if vertical 4952 * faded edges are not enabled for this view. 4953 * @attr ref android.R.styleable#View_fadingEdgeLength 4954 */ 4955 public int getVerticalFadingEdgeLength() { 4956 if (isVerticalFadingEdgeEnabled()) { 4957 ScrollabilityCache cache = mScrollCache; 4958 if (cache != null) { 4959 return cache.fadingEdgeLength; 4960 } 4961 } 4962 return 0; 4963 } 4964 4965 /** 4966 * Set the size of the faded edge used to indicate that more content in this 4967 * view is available. Will not change whether the fading edge is enabled; use 4968 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4969 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4970 * for the vertical or horizontal fading edges. 4971 * 4972 * @param length The size in pixels of the faded edge used to indicate that more 4973 * content in this view is visible. 4974 */ 4975 public void setFadingEdgeLength(int length) { 4976 initScrollCache(); 4977 mScrollCache.fadingEdgeLength = length; 4978 } 4979 4980 /** 4981 * Returns the size of the horizontal faded edges used to indicate that more 4982 * content in this view is visible. 4983 * 4984 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4985 * faded edges are not enabled for this view. 4986 * @attr ref android.R.styleable#View_fadingEdgeLength 4987 */ 4988 public int getHorizontalFadingEdgeLength() { 4989 if (isHorizontalFadingEdgeEnabled()) { 4990 ScrollabilityCache cache = mScrollCache; 4991 if (cache != null) { 4992 return cache.fadingEdgeLength; 4993 } 4994 } 4995 return 0; 4996 } 4997 4998 /** 4999 * Returns the width of the vertical scrollbar. 5000 * 5001 * @return The width in pixels of the vertical scrollbar or 0 if there 5002 * is no vertical scrollbar. 5003 */ 5004 public int getVerticalScrollbarWidth() { 5005 ScrollabilityCache cache = mScrollCache; 5006 if (cache != null) { 5007 ScrollBarDrawable scrollBar = cache.scrollBar; 5008 if (scrollBar != null) { 5009 int size = scrollBar.getSize(true); 5010 if (size <= 0) { 5011 size = cache.scrollBarSize; 5012 } 5013 return size; 5014 } 5015 return 0; 5016 } 5017 return 0; 5018 } 5019 5020 /** 5021 * Returns the height of the horizontal scrollbar. 5022 * 5023 * @return The height in pixels of the horizontal scrollbar or 0 if 5024 * there is no horizontal scrollbar. 5025 */ 5026 protected int getHorizontalScrollbarHeight() { 5027 ScrollabilityCache cache = mScrollCache; 5028 if (cache != null) { 5029 ScrollBarDrawable scrollBar = cache.scrollBar; 5030 if (scrollBar != null) { 5031 int size = scrollBar.getSize(false); 5032 if (size <= 0) { 5033 size = cache.scrollBarSize; 5034 } 5035 return size; 5036 } 5037 return 0; 5038 } 5039 return 0; 5040 } 5041 5042 /** 5043 * <p> 5044 * Initializes the scrollbars from a given set of styled attributes. This 5045 * method should be called by subclasses that need scrollbars and when an 5046 * instance of these subclasses is created programmatically rather than 5047 * being inflated from XML. This method is automatically called when the XML 5048 * is inflated. 5049 * </p> 5050 * 5051 * @param a the styled attributes set to initialize the scrollbars from 5052 * 5053 * @removed 5054 */ 5055 protected void initializeScrollbars(TypedArray a) { 5056 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5057 // using the View filter array which is not available to the SDK. As such, internal 5058 // framework usage now uses initializeScrollbarsInternal and we grab a default 5059 // TypedArray with the right filter instead here. 5060 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5061 5062 initializeScrollbarsInternal(arr); 5063 5064 // We ignored the method parameter. Recycle the one we actually did use. 5065 arr.recycle(); 5066 } 5067 5068 /** 5069 * <p> 5070 * Initializes the scrollbars from a given set of styled attributes. This 5071 * method should be called by subclasses that need scrollbars and when an 5072 * instance of these subclasses is created programmatically rather than 5073 * being inflated from XML. This method is automatically called when the XML 5074 * is inflated. 5075 * </p> 5076 * 5077 * @param a the styled attributes set to initialize the scrollbars from 5078 * @hide 5079 */ 5080 protected void initializeScrollbarsInternal(TypedArray a) { 5081 initScrollCache(); 5082 5083 final ScrollabilityCache scrollabilityCache = mScrollCache; 5084 5085 if (scrollabilityCache.scrollBar == null) { 5086 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5087 scrollabilityCache.scrollBar.setState(getDrawableState()); 5088 scrollabilityCache.scrollBar.setCallback(this); 5089 } 5090 5091 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5092 5093 if (!fadeScrollbars) { 5094 scrollabilityCache.state = ScrollabilityCache.ON; 5095 } 5096 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5097 5098 5099 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5100 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5101 .getScrollBarFadeDuration()); 5102 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5103 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5104 ViewConfiguration.getScrollDefaultDelay()); 5105 5106 5107 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5108 com.android.internal.R.styleable.View_scrollbarSize, 5109 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5110 5111 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5112 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5113 5114 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5115 if (thumb != null) { 5116 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5117 } 5118 5119 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5120 false); 5121 if (alwaysDraw) { 5122 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5123 } 5124 5125 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5126 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5127 5128 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5129 if (thumb != null) { 5130 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5131 } 5132 5133 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5134 false); 5135 if (alwaysDraw) { 5136 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5137 } 5138 5139 // Apply layout direction to the new Drawables if needed 5140 final int layoutDirection = getLayoutDirection(); 5141 if (track != null) { 5142 track.setLayoutDirection(layoutDirection); 5143 } 5144 if (thumb != null) { 5145 thumb.setLayoutDirection(layoutDirection); 5146 } 5147 5148 // Re-apply user/background padding so that scrollbar(s) get added 5149 resolvePadding(); 5150 } 5151 5152 private void initializeScrollIndicatorsInternal() { 5153 // Some day maybe we'll break this into top/left/start/etc. and let the 5154 // client control it. Until then, you can have any scroll indicator you 5155 // want as long as it's a 1dp foreground-colored rectangle. 5156 if (mScrollIndicatorDrawable == null) { 5157 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5158 } 5159 } 5160 5161 /** 5162 * <p> 5163 * Initalizes the scrollability cache if necessary. 5164 * </p> 5165 */ 5166 private void initScrollCache() { 5167 if (mScrollCache == null) { 5168 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5169 } 5170 } 5171 5172 private ScrollabilityCache getScrollCache() { 5173 initScrollCache(); 5174 return mScrollCache; 5175 } 5176 5177 /** 5178 * Set the position of the vertical scroll bar. Should be one of 5179 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5180 * {@link #SCROLLBAR_POSITION_RIGHT}. 5181 * 5182 * @param position Where the vertical scroll bar should be positioned. 5183 */ 5184 public void setVerticalScrollbarPosition(int position) { 5185 if (mVerticalScrollbarPosition != position) { 5186 mVerticalScrollbarPosition = position; 5187 computeOpaqueFlags(); 5188 resolvePadding(); 5189 } 5190 } 5191 5192 /** 5193 * @return The position where the vertical scroll bar will show, if applicable. 5194 * @see #setVerticalScrollbarPosition(int) 5195 */ 5196 public int getVerticalScrollbarPosition() { 5197 return mVerticalScrollbarPosition; 5198 } 5199 5200 boolean isOnScrollbar(float x, float y) { 5201 if (mScrollCache == null) { 5202 return false; 5203 } 5204 x += getScrollX(); 5205 y += getScrollY(); 5206 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5207 final Rect bounds = mScrollCache.mScrollBarBounds; 5208 getVerticalScrollBarBounds(bounds); 5209 if (bounds.contains((int)x, (int)y)) { 5210 return true; 5211 } 5212 } 5213 if (isHorizontalScrollBarEnabled()) { 5214 final Rect bounds = mScrollCache.mScrollBarBounds; 5215 getHorizontalScrollBarBounds(bounds); 5216 if (bounds.contains((int)x, (int)y)) { 5217 return true; 5218 } 5219 } 5220 return false; 5221 } 5222 5223 boolean isOnScrollbarThumb(float x, float y) { 5224 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5225 } 5226 5227 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5228 if (mScrollCache == null) { 5229 return false; 5230 } 5231 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5232 x += getScrollX(); 5233 y += getScrollY(); 5234 final Rect bounds = mScrollCache.mScrollBarBounds; 5235 getVerticalScrollBarBounds(bounds); 5236 final int range = computeVerticalScrollRange(); 5237 final int offset = computeVerticalScrollOffset(); 5238 final int extent = computeVerticalScrollExtent(); 5239 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5240 extent, range); 5241 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5242 extent, range, offset); 5243 final int thumbTop = bounds.top + thumbOffset; 5244 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5245 && y <= thumbTop + thumbLength) { 5246 return true; 5247 } 5248 } 5249 return false; 5250 } 5251 5252 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5253 if (mScrollCache == null) { 5254 return false; 5255 } 5256 if (isHorizontalScrollBarEnabled()) { 5257 x += getScrollX(); 5258 y += getScrollY(); 5259 final Rect bounds = mScrollCache.mScrollBarBounds; 5260 getHorizontalScrollBarBounds(bounds); 5261 final int range = computeHorizontalScrollRange(); 5262 final int offset = computeHorizontalScrollOffset(); 5263 final int extent = computeHorizontalScrollExtent(); 5264 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5265 extent, range); 5266 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5267 extent, range, offset); 5268 final int thumbLeft = bounds.left + thumbOffset; 5269 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5270 && y <= bounds.bottom) { 5271 return true; 5272 } 5273 } 5274 return false; 5275 } 5276 5277 boolean isDraggingScrollBar() { 5278 return mScrollCache != null 5279 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5280 } 5281 5282 /** 5283 * Sets the state of all scroll indicators. 5284 * <p> 5285 * See {@link #setScrollIndicators(int, int)} for usage information. 5286 * 5287 * @param indicators a bitmask of indicators that should be enabled, or 5288 * {@code 0} to disable all indicators 5289 * @see #setScrollIndicators(int, int) 5290 * @see #getScrollIndicators() 5291 * @attr ref android.R.styleable#View_scrollIndicators 5292 */ 5293 public void setScrollIndicators(@ScrollIndicators int indicators) { 5294 setScrollIndicators(indicators, 5295 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5296 } 5297 5298 /** 5299 * Sets the state of the scroll indicators specified by the mask. To change 5300 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5301 * <p> 5302 * When a scroll indicator is enabled, it will be displayed if the view 5303 * can scroll in the direction of the indicator. 5304 * <p> 5305 * Multiple indicator types may be enabled or disabled by passing the 5306 * logical OR of the desired types. If multiple types are specified, they 5307 * will all be set to the same enabled state. 5308 * <p> 5309 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5310 * 5311 * @param indicators the indicator direction, or the logical OR of multiple 5312 * indicator directions. One or more of: 5313 * <ul> 5314 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5315 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5316 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5317 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5318 * <li>{@link #SCROLL_INDICATOR_START}</li> 5319 * <li>{@link #SCROLL_INDICATOR_END}</li> 5320 * </ul> 5321 * @see #setScrollIndicators(int) 5322 * @see #getScrollIndicators() 5323 * @attr ref android.R.styleable#View_scrollIndicators 5324 */ 5325 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5326 // Shift and sanitize mask. 5327 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5328 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5329 5330 // Shift and mask indicators. 5331 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5332 indicators &= mask; 5333 5334 // Merge with non-masked flags. 5335 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5336 5337 if (mPrivateFlags3 != updatedFlags) { 5338 mPrivateFlags3 = updatedFlags; 5339 5340 if (indicators != 0) { 5341 initializeScrollIndicatorsInternal(); 5342 } 5343 invalidate(); 5344 } 5345 } 5346 5347 /** 5348 * Returns a bitmask representing the enabled scroll indicators. 5349 * <p> 5350 * For example, if the top and left scroll indicators are enabled and all 5351 * other indicators are disabled, the return value will be 5352 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5353 * <p> 5354 * To check whether the bottom scroll indicator is enabled, use the value 5355 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5356 * 5357 * @return a bitmask representing the enabled scroll indicators 5358 */ 5359 @ScrollIndicators 5360 public int getScrollIndicators() { 5361 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5362 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5363 } 5364 5365 ListenerInfo getListenerInfo() { 5366 if (mListenerInfo != null) { 5367 return mListenerInfo; 5368 } 5369 mListenerInfo = new ListenerInfo(); 5370 return mListenerInfo; 5371 } 5372 5373 /** 5374 * Register a callback to be invoked when the scroll X or Y positions of 5375 * this view change. 5376 * <p> 5377 * <b>Note:</b> Some views handle scrolling independently from View and may 5378 * have their own separate listeners for scroll-type events. For example, 5379 * {@link android.widget.ListView ListView} allows clients to register an 5380 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5381 * to listen for changes in list scroll position. 5382 * 5383 * @param l The listener to notify when the scroll X or Y position changes. 5384 * @see android.view.View#getScrollX() 5385 * @see android.view.View#getScrollY() 5386 */ 5387 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5388 getListenerInfo().mOnScrollChangeListener = l; 5389 } 5390 5391 /** 5392 * Register a callback to be invoked when focus of this view changed. 5393 * 5394 * @param l The callback that will run. 5395 */ 5396 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5397 getListenerInfo().mOnFocusChangeListener = l; 5398 } 5399 5400 /** 5401 * Add a listener that will be called when the bounds of the view change due to 5402 * layout processing. 5403 * 5404 * @param listener The listener that will be called when layout bounds change. 5405 */ 5406 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5407 ListenerInfo li = getListenerInfo(); 5408 if (li.mOnLayoutChangeListeners == null) { 5409 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5410 } 5411 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5412 li.mOnLayoutChangeListeners.add(listener); 5413 } 5414 } 5415 5416 /** 5417 * Remove a listener for layout changes. 5418 * 5419 * @param listener The listener for layout bounds change. 5420 */ 5421 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5422 ListenerInfo li = mListenerInfo; 5423 if (li == null || li.mOnLayoutChangeListeners == null) { 5424 return; 5425 } 5426 li.mOnLayoutChangeListeners.remove(listener); 5427 } 5428 5429 /** 5430 * Add a listener for attach state changes. 5431 * 5432 * This listener will be called whenever this view is attached or detached 5433 * from a window. Remove the listener using 5434 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5435 * 5436 * @param listener Listener to attach 5437 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5438 */ 5439 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5440 ListenerInfo li = getListenerInfo(); 5441 if (li.mOnAttachStateChangeListeners == null) { 5442 li.mOnAttachStateChangeListeners 5443 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5444 } 5445 li.mOnAttachStateChangeListeners.add(listener); 5446 } 5447 5448 /** 5449 * Remove a listener for attach state changes. The listener will receive no further 5450 * notification of window attach/detach events. 5451 * 5452 * @param listener Listener to remove 5453 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5454 */ 5455 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5456 ListenerInfo li = mListenerInfo; 5457 if (li == null || li.mOnAttachStateChangeListeners == null) { 5458 return; 5459 } 5460 li.mOnAttachStateChangeListeners.remove(listener); 5461 } 5462 5463 /** 5464 * Returns the focus-change callback registered for this view. 5465 * 5466 * @return The callback, or null if one is not registered. 5467 */ 5468 public OnFocusChangeListener getOnFocusChangeListener() { 5469 ListenerInfo li = mListenerInfo; 5470 return li != null ? li.mOnFocusChangeListener : null; 5471 } 5472 5473 /** 5474 * Register a callback to be invoked when this view is clicked. If this view is not 5475 * clickable, it becomes clickable. 5476 * 5477 * @param l The callback that will run 5478 * 5479 * @see #setClickable(boolean) 5480 */ 5481 public void setOnClickListener(@Nullable OnClickListener l) { 5482 if (!isClickable()) { 5483 setClickable(true); 5484 } 5485 getListenerInfo().mOnClickListener = l; 5486 } 5487 5488 /** 5489 * Return whether this view has an attached OnClickListener. Returns 5490 * true if there is a listener, false if there is none. 5491 */ 5492 public boolean hasOnClickListeners() { 5493 ListenerInfo li = mListenerInfo; 5494 return (li != null && li.mOnClickListener != null); 5495 } 5496 5497 /** 5498 * Register a callback to be invoked when this view is clicked and held. If this view is not 5499 * long clickable, it becomes long clickable. 5500 * 5501 * @param l The callback that will run 5502 * 5503 * @see #setLongClickable(boolean) 5504 */ 5505 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5506 if (!isLongClickable()) { 5507 setLongClickable(true); 5508 } 5509 getListenerInfo().mOnLongClickListener = l; 5510 } 5511 5512 /** 5513 * Register a callback to be invoked when this view is context clicked. If the view is not 5514 * context clickable, it becomes context clickable. 5515 * 5516 * @param l The callback that will run 5517 * @see #setContextClickable(boolean) 5518 */ 5519 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5520 if (!isContextClickable()) { 5521 setContextClickable(true); 5522 } 5523 getListenerInfo().mOnContextClickListener = l; 5524 } 5525 5526 /** 5527 * Register a callback to be invoked when the context menu for this view is 5528 * being built. If this view is not long clickable, it becomes long clickable. 5529 * 5530 * @param l The callback that will run 5531 * 5532 */ 5533 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5534 if (!isLongClickable()) { 5535 setLongClickable(true); 5536 } 5537 getListenerInfo().mOnCreateContextMenuListener = l; 5538 } 5539 5540 /** 5541 * Set an observer to collect stats for each frame rendered for this view. 5542 * 5543 * @hide 5544 */ 5545 public void addFrameMetricsListener(Window window, 5546 Window.OnFrameMetricsAvailableListener listener, 5547 Handler handler) { 5548 if (mAttachInfo != null) { 5549 if (mAttachInfo.mThreadedRenderer != null) { 5550 if (mFrameMetricsObservers == null) { 5551 mFrameMetricsObservers = new ArrayList<>(); 5552 } 5553 5554 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5555 handler.getLooper(), listener); 5556 mFrameMetricsObservers.add(fmo); 5557 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 5558 } else { 5559 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5560 } 5561 } else { 5562 if (mFrameMetricsObservers == null) { 5563 mFrameMetricsObservers = new ArrayList<>(); 5564 } 5565 5566 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5567 handler.getLooper(), listener); 5568 mFrameMetricsObservers.add(fmo); 5569 } 5570 } 5571 5572 /** 5573 * Remove observer configured to collect frame stats for this view. 5574 * 5575 * @hide 5576 */ 5577 public void removeFrameMetricsListener( 5578 Window.OnFrameMetricsAvailableListener listener) { 5579 ThreadedRenderer renderer = getThreadedRenderer(); 5580 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5581 if (fmo == null) { 5582 throw new IllegalArgumentException( 5583 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 5584 } 5585 5586 if (mFrameMetricsObservers != null) { 5587 mFrameMetricsObservers.remove(fmo); 5588 if (renderer != null) { 5589 renderer.removeFrameMetricsObserver(fmo); 5590 } 5591 } 5592 } 5593 5594 private void registerPendingFrameMetricsObservers() { 5595 if (mFrameMetricsObservers != null) { 5596 ThreadedRenderer renderer = getThreadedRenderer(); 5597 if (renderer != null) { 5598 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5599 renderer.addFrameMetricsObserver(fmo); 5600 } 5601 } else { 5602 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5603 } 5604 } 5605 } 5606 5607 private FrameMetricsObserver findFrameMetricsObserver( 5608 Window.OnFrameMetricsAvailableListener listener) { 5609 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5610 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5611 if (observer.mListener == listener) { 5612 return observer; 5613 } 5614 } 5615 5616 return null; 5617 } 5618 5619 /** 5620 * Call this view's OnClickListener, if it is defined. Performs all normal 5621 * actions associated with clicking: reporting accessibility event, playing 5622 * a sound, etc. 5623 * 5624 * @return True there was an assigned OnClickListener that was called, false 5625 * otherwise is returned. 5626 */ 5627 public boolean performClick() { 5628 final boolean result; 5629 final ListenerInfo li = mListenerInfo; 5630 if (li != null && li.mOnClickListener != null) { 5631 playSoundEffect(SoundEffectConstants.CLICK); 5632 li.mOnClickListener.onClick(this); 5633 result = true; 5634 } else { 5635 result = false; 5636 } 5637 5638 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5639 return result; 5640 } 5641 5642 /** 5643 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5644 * this only calls the listener, and does not do any associated clicking 5645 * actions like reporting an accessibility event. 5646 * 5647 * @return True there was an assigned OnClickListener that was called, false 5648 * otherwise is returned. 5649 */ 5650 public boolean callOnClick() { 5651 ListenerInfo li = mListenerInfo; 5652 if (li != null && li.mOnClickListener != null) { 5653 li.mOnClickListener.onClick(this); 5654 return true; 5655 } 5656 return false; 5657 } 5658 5659 /** 5660 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5661 * context menu if the OnLongClickListener did not consume the event. 5662 * 5663 * @return {@code true} if one of the above receivers consumed the event, 5664 * {@code false} otherwise 5665 */ 5666 public boolean performLongClick() { 5667 return performLongClickInternal(mLongClickX, mLongClickY); 5668 } 5669 5670 /** 5671 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5672 * context menu if the OnLongClickListener did not consume the event, 5673 * anchoring it to an (x,y) coordinate. 5674 * 5675 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5676 * to disable anchoring 5677 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5678 * to disable anchoring 5679 * @return {@code true} if one of the above receivers consumed the event, 5680 * {@code false} otherwise 5681 */ 5682 public boolean performLongClick(float x, float y) { 5683 mLongClickX = x; 5684 mLongClickY = y; 5685 final boolean handled = performLongClick(); 5686 mLongClickX = Float.NaN; 5687 mLongClickY = Float.NaN; 5688 return handled; 5689 } 5690 5691 /** 5692 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5693 * context menu if the OnLongClickListener did not consume the event, 5694 * optionally anchoring it to an (x,y) coordinate. 5695 * 5696 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5697 * to disable anchoring 5698 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5699 * to disable anchoring 5700 * @return {@code true} if one of the above receivers consumed the event, 5701 * {@code false} otherwise 5702 */ 5703 private boolean performLongClickInternal(float x, float y) { 5704 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5705 5706 boolean handled = false; 5707 final ListenerInfo li = mListenerInfo; 5708 if (li != null && li.mOnLongClickListener != null) { 5709 handled = li.mOnLongClickListener.onLongClick(View.this); 5710 } 5711 if (!handled) { 5712 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5713 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5714 } 5715 if (handled) { 5716 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5717 } 5718 return handled; 5719 } 5720 5721 /** 5722 * Call this view's OnContextClickListener, if it is defined. 5723 * 5724 * @param x the x coordinate of the context click 5725 * @param y the y coordinate of the context click 5726 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5727 * otherwise. 5728 */ 5729 public boolean performContextClick(float x, float y) { 5730 return performContextClick(); 5731 } 5732 5733 /** 5734 * Call this view's OnContextClickListener, if it is defined. 5735 * 5736 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5737 * otherwise. 5738 */ 5739 public boolean performContextClick() { 5740 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5741 5742 boolean handled = false; 5743 ListenerInfo li = mListenerInfo; 5744 if (li != null && li.mOnContextClickListener != null) { 5745 handled = li.mOnContextClickListener.onContextClick(View.this); 5746 } 5747 if (handled) { 5748 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5749 } 5750 return handled; 5751 } 5752 5753 /** 5754 * Performs button-related actions during a touch down event. 5755 * 5756 * @param event The event. 5757 * @return True if the down was consumed. 5758 * 5759 * @hide 5760 */ 5761 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5762 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5763 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5764 showContextMenu(event.getX(), event.getY()); 5765 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5766 return true; 5767 } 5768 return false; 5769 } 5770 5771 /** 5772 * Shows the context menu for this view. 5773 * 5774 * @return {@code true} if the context menu was shown, {@code false} 5775 * otherwise 5776 * @see #showContextMenu(float, float) 5777 */ 5778 public boolean showContextMenu() { 5779 return getParent().showContextMenuForChild(this); 5780 } 5781 5782 /** 5783 * Shows the context menu for this view anchored to the specified 5784 * view-relative coordinate. 5785 * 5786 * @param x the X coordinate in pixels relative to the view to which the 5787 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5788 * @param y the Y coordinate in pixels relative to the view to which the 5789 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5790 * @return {@code true} if the context menu was shown, {@code false} 5791 * otherwise 5792 */ 5793 public boolean showContextMenu(float x, float y) { 5794 return getParent().showContextMenuForChild(this, x, y); 5795 } 5796 5797 /** 5798 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5799 * 5800 * @param callback Callback that will control the lifecycle of the action mode 5801 * @return The new action mode if it is started, null otherwise 5802 * 5803 * @see ActionMode 5804 * @see #startActionMode(android.view.ActionMode.Callback, int) 5805 */ 5806 public ActionMode startActionMode(ActionMode.Callback callback) { 5807 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5808 } 5809 5810 /** 5811 * Start an action mode with the given type. 5812 * 5813 * @param callback Callback that will control the lifecycle of the action mode 5814 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5815 * @return The new action mode if it is started, null otherwise 5816 * 5817 * @see ActionMode 5818 */ 5819 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5820 ViewParent parent = getParent(); 5821 if (parent == null) return null; 5822 try { 5823 return parent.startActionModeForChild(this, callback, type); 5824 } catch (AbstractMethodError ame) { 5825 // Older implementations of custom views might not implement this. 5826 return parent.startActionModeForChild(this, callback); 5827 } 5828 } 5829 5830 /** 5831 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5832 * Context, creating a unique View identifier to retrieve the result. 5833 * 5834 * @param intent The Intent to be started. 5835 * @param requestCode The request code to use. 5836 * @hide 5837 */ 5838 public void startActivityForResult(Intent intent, int requestCode) { 5839 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5840 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5841 } 5842 5843 /** 5844 * If this View corresponds to the calling who, dispatches the activity result. 5845 * @param who The identifier for the targeted View to receive the result. 5846 * @param requestCode The integer request code originally supplied to 5847 * startActivityForResult(), allowing you to identify who this 5848 * result came from. 5849 * @param resultCode The integer result code returned by the child activity 5850 * through its setResult(). 5851 * @param data An Intent, which can return result data to the caller 5852 * (various data can be attached to Intent "extras"). 5853 * @return {@code true} if the activity result was dispatched. 5854 * @hide 5855 */ 5856 public boolean dispatchActivityResult( 5857 String who, int requestCode, int resultCode, Intent data) { 5858 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5859 onActivityResult(requestCode, resultCode, data); 5860 mStartActivityRequestWho = null; 5861 return true; 5862 } 5863 return false; 5864 } 5865 5866 /** 5867 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5868 * 5869 * @param requestCode The integer request code originally supplied to 5870 * startActivityForResult(), allowing you to identify who this 5871 * result came from. 5872 * @param resultCode The integer result code returned by the child activity 5873 * through its setResult(). 5874 * @param data An Intent, which can return result data to the caller 5875 * (various data can be attached to Intent "extras"). 5876 * @hide 5877 */ 5878 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5879 // Do nothing. 5880 } 5881 5882 /** 5883 * Register a callback to be invoked when a hardware key is pressed in this view. 5884 * Key presses in software input methods will generally not trigger the methods of 5885 * this listener. 5886 * @param l the key listener to attach to this view 5887 */ 5888 public void setOnKeyListener(OnKeyListener l) { 5889 getListenerInfo().mOnKeyListener = l; 5890 } 5891 5892 /** 5893 * Register a callback to be invoked when a touch event is sent to this view. 5894 * @param l the touch listener to attach to this view 5895 */ 5896 public void setOnTouchListener(OnTouchListener l) { 5897 getListenerInfo().mOnTouchListener = l; 5898 } 5899 5900 /** 5901 * Register a callback to be invoked when a generic motion event is sent to this view. 5902 * @param l the generic motion listener to attach to this view 5903 */ 5904 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5905 getListenerInfo().mOnGenericMotionListener = l; 5906 } 5907 5908 /** 5909 * Register a callback to be invoked when a hover event is sent to this view. 5910 * @param l the hover listener to attach to this view 5911 */ 5912 public void setOnHoverListener(OnHoverListener l) { 5913 getListenerInfo().mOnHoverListener = l; 5914 } 5915 5916 /** 5917 * Register a drag event listener callback object for this View. The parameter is 5918 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5919 * View, the system calls the 5920 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5921 * @param l An implementation of {@link android.view.View.OnDragListener}. 5922 */ 5923 public void setOnDragListener(OnDragListener l) { 5924 getListenerInfo().mOnDragListener = l; 5925 } 5926 5927 /** 5928 * Give this view focus. This will cause 5929 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5930 * 5931 * Note: this does not check whether this {@link View} should get focus, it just 5932 * gives it focus no matter what. It should only be called internally by framework 5933 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5934 * 5935 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5936 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5937 * focus moved when requestFocus() is called. It may not always 5938 * apply, in which case use the default View.FOCUS_DOWN. 5939 * @param previouslyFocusedRect The rectangle of the view that had focus 5940 * prior in this View's coordinate system. 5941 */ 5942 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5943 if (DBG) { 5944 System.out.println(this + " requestFocus()"); 5945 } 5946 5947 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5948 mPrivateFlags |= PFLAG_FOCUSED; 5949 5950 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5951 5952 if (mParent != null) { 5953 mParent.requestChildFocus(this, this); 5954 } 5955 5956 if (mAttachInfo != null) { 5957 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5958 } 5959 5960 onFocusChanged(true, direction, previouslyFocusedRect); 5961 refreshDrawableState(); 5962 } 5963 } 5964 5965 /** 5966 * Sets this view's preference for reveal behavior when it gains focus. 5967 * 5968 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 5969 * this view would prefer to be brought fully into view when it gains focus. 5970 * For example, a text field that a user is meant to type into. Other views such 5971 * as scrolling containers may prefer to opt-out of this behavior.</p> 5972 * 5973 * <p>The default value for views is true, though subclasses may change this 5974 * based on their preferred behavior.</p> 5975 * 5976 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 5977 * 5978 * @see #getRevealOnFocusHint() 5979 */ 5980 public final void setRevealOnFocusHint(boolean revealOnFocus) { 5981 if (revealOnFocus) { 5982 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 5983 } else { 5984 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 5985 } 5986 } 5987 5988 /** 5989 * Returns this view's preference for reveal behavior when it gains focus. 5990 * 5991 * <p>When this method returns true for a child view requesting focus, ancestor 5992 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 5993 * should make a best effort to make the newly focused child fully visible to the user. 5994 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 5995 * other properties affecting visibility to the user as part of the focus change.</p> 5996 * 5997 * @return true if this view would prefer to become fully visible when it gains focus, 5998 * false if it would prefer not to disrupt scroll positioning 5999 * 6000 * @see #setRevealOnFocusHint(boolean) 6001 */ 6002 public final boolean getRevealOnFocusHint() { 6003 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 6004 } 6005 6006 /** 6007 * Populates <code>outRect</code> with the hotspot bounds. By default, 6008 * the hotspot bounds are identical to the screen bounds. 6009 * 6010 * @param outRect rect to populate with hotspot bounds 6011 * @hide Only for internal use by views and widgets. 6012 */ 6013 public void getHotspotBounds(Rect outRect) { 6014 final Drawable background = getBackground(); 6015 if (background != null) { 6016 background.getHotspotBounds(outRect); 6017 } else { 6018 getBoundsOnScreen(outRect); 6019 } 6020 } 6021 6022 /** 6023 * Request that a rectangle of this view be visible on the screen, 6024 * scrolling if necessary just enough. 6025 * 6026 * <p>A View should call this if it maintains some notion of which part 6027 * of its content is interesting. For example, a text editing view 6028 * should call this when its cursor moves. 6029 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6030 * It should not be affected by which part of the View is currently visible or its scroll 6031 * position. 6032 * 6033 * @param rectangle The rectangle in the View's content coordinate space 6034 * @return Whether any parent scrolled. 6035 */ 6036 public boolean requestRectangleOnScreen(Rect rectangle) { 6037 return requestRectangleOnScreen(rectangle, false); 6038 } 6039 6040 /** 6041 * Request that a rectangle of this view be visible on the screen, 6042 * scrolling if necessary just enough. 6043 * 6044 * <p>A View should call this if it maintains some notion of which part 6045 * of its content is interesting. For example, a text editing view 6046 * should call this when its cursor moves. 6047 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6048 * It should not be affected by which part of the View is currently visible or its scroll 6049 * position. 6050 * <p>When <code>immediate</code> is set to true, scrolling will not be 6051 * animated. 6052 * 6053 * @param rectangle The rectangle in the View's content coordinate space 6054 * @param immediate True to forbid animated scrolling, false otherwise 6055 * @return Whether any parent scrolled. 6056 */ 6057 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 6058 if (mParent == null) { 6059 return false; 6060 } 6061 6062 View child = this; 6063 6064 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6065 position.set(rectangle); 6066 6067 ViewParent parent = mParent; 6068 boolean scrolled = false; 6069 while (parent != null) { 6070 rectangle.set((int) position.left, (int) position.top, 6071 (int) position.right, (int) position.bottom); 6072 6073 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6074 6075 if (!(parent instanceof View)) { 6076 break; 6077 } 6078 6079 // move it from child's content coordinate space to parent's content coordinate space 6080 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6081 6082 child = (View) parent; 6083 parent = child.getParent(); 6084 } 6085 6086 return scrolled; 6087 } 6088 6089 /** 6090 * Called when this view wants to give up focus. If focus is cleared 6091 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6092 * <p> 6093 * <strong>Note:</strong> When a View clears focus the framework is trying 6094 * to give focus to the first focusable View from the top. Hence, if this 6095 * View is the first from the top that can take focus, then all callbacks 6096 * related to clearing focus will be invoked after which the framework will 6097 * give focus to this view. 6098 * </p> 6099 */ 6100 public void clearFocus() { 6101 if (DBG) { 6102 System.out.println(this + " clearFocus()"); 6103 } 6104 6105 clearFocusInternal(null, true, true); 6106 } 6107 6108 /** 6109 * Clears focus from the view, optionally propagating the change up through 6110 * the parent hierarchy and requesting that the root view place new focus. 6111 * 6112 * @param propagate whether to propagate the change up through the parent 6113 * hierarchy 6114 * @param refocus when propagate is true, specifies whether to request the 6115 * root view place new focus 6116 */ 6117 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6118 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6119 mPrivateFlags &= ~PFLAG_FOCUSED; 6120 6121 if (propagate && mParent != null) { 6122 mParent.clearChildFocus(this); 6123 } 6124 6125 onFocusChanged(false, 0, null); 6126 refreshDrawableState(); 6127 6128 if (propagate && (!refocus || !rootViewRequestFocus())) { 6129 notifyGlobalFocusCleared(this); 6130 } 6131 } 6132 } 6133 6134 void notifyGlobalFocusCleared(View oldFocus) { 6135 if (oldFocus != null && mAttachInfo != null) { 6136 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6137 } 6138 } 6139 6140 boolean rootViewRequestFocus() { 6141 final View root = getRootView(); 6142 return root != null && root.requestFocus(); 6143 } 6144 6145 /** 6146 * Called internally by the view system when a new view is getting focus. 6147 * This is what clears the old focus. 6148 * <p> 6149 * <b>NOTE:</b> The parent view's focused child must be updated manually 6150 * after calling this method. Otherwise, the view hierarchy may be left in 6151 * an inconstent state. 6152 */ 6153 void unFocus(View focused) { 6154 if (DBG) { 6155 System.out.println(this + " unFocus()"); 6156 } 6157 6158 clearFocusInternal(focused, false, false); 6159 } 6160 6161 /** 6162 * Returns true if this view has focus itself, or is the ancestor of the 6163 * view that has focus. 6164 * 6165 * @return True if this view has or contains focus, false otherwise. 6166 */ 6167 @ViewDebug.ExportedProperty(category = "focus") 6168 public boolean hasFocus() { 6169 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6170 } 6171 6172 /** 6173 * Returns true if this view is focusable or if it contains a reachable View 6174 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6175 * is a View whose parents do not block descendants focus. 6176 * 6177 * Only {@link #VISIBLE} views are considered focusable. 6178 * 6179 * @return True if the view is focusable or if the view contains a focusable 6180 * View, false otherwise. 6181 * 6182 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6183 * @see ViewGroup#getTouchscreenBlocksFocus() 6184 */ 6185 public boolean hasFocusable() { 6186 if (!isFocusableInTouchMode()) { 6187 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6188 final ViewGroup g = (ViewGroup) p; 6189 if (g.shouldBlockFocusForTouchscreen()) { 6190 return false; 6191 } 6192 } 6193 } 6194 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6195 } 6196 6197 /** 6198 * Called by the view system when the focus state of this view changes. 6199 * When the focus change event is caused by directional navigation, direction 6200 * and previouslyFocusedRect provide insight into where the focus is coming from. 6201 * When overriding, be sure to call up through to the super class so that 6202 * the standard focus handling will occur. 6203 * 6204 * @param gainFocus True if the View has focus; false otherwise. 6205 * @param direction The direction focus has moved when requestFocus() 6206 * is called to give this view focus. Values are 6207 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6208 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6209 * It may not always apply, in which case use the default. 6210 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6211 * system, of the previously focused view. If applicable, this will be 6212 * passed in as finer grained information about where the focus is coming 6213 * from (in addition to direction). Will be <code>null</code> otherwise. 6214 */ 6215 @CallSuper 6216 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6217 @Nullable Rect previouslyFocusedRect) { 6218 if (gainFocus) { 6219 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6220 } else { 6221 notifyViewAccessibilityStateChangedIfNeeded( 6222 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6223 } 6224 6225 InputMethodManager imm = InputMethodManager.peekInstance(); 6226 if (!gainFocus) { 6227 if (isPressed()) { 6228 setPressed(false); 6229 } 6230 if (imm != null && mAttachInfo != null 6231 && mAttachInfo.mHasWindowFocus) { 6232 imm.focusOut(this); 6233 } 6234 onFocusLost(); 6235 } else if (imm != null && mAttachInfo != null 6236 && mAttachInfo.mHasWindowFocus) { 6237 imm.focusIn(this); 6238 } 6239 6240 invalidate(true); 6241 ListenerInfo li = mListenerInfo; 6242 if (li != null && li.mOnFocusChangeListener != null) { 6243 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6244 } 6245 6246 if (mAttachInfo != null) { 6247 mAttachInfo.mKeyDispatchState.reset(this); 6248 } 6249 } 6250 6251 /** 6252 * Sends an accessibility event of the given type. If accessibility is 6253 * not enabled this method has no effect. The default implementation calls 6254 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6255 * to populate information about the event source (this View), then calls 6256 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6257 * populate the text content of the event source including its descendants, 6258 * and last calls 6259 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6260 * on its parent to request sending of the event to interested parties. 6261 * <p> 6262 * If an {@link AccessibilityDelegate} has been specified via calling 6263 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6264 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6265 * responsible for handling this call. 6266 * </p> 6267 * 6268 * @param eventType The type of the event to send, as defined by several types from 6269 * {@link android.view.accessibility.AccessibilityEvent}, such as 6270 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6271 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6272 * 6273 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6274 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6275 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6276 * @see AccessibilityDelegate 6277 */ 6278 public void sendAccessibilityEvent(int eventType) { 6279 if (mAccessibilityDelegate != null) { 6280 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6281 } else { 6282 sendAccessibilityEventInternal(eventType); 6283 } 6284 } 6285 6286 /** 6287 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6288 * {@link AccessibilityEvent} to make an announcement which is related to some 6289 * sort of a context change for which none of the events representing UI transitions 6290 * is a good fit. For example, announcing a new page in a book. If accessibility 6291 * is not enabled this method does nothing. 6292 * 6293 * @param text The announcement text. 6294 */ 6295 public void announceForAccessibility(CharSequence text) { 6296 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6297 AccessibilityEvent event = AccessibilityEvent.obtain( 6298 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6299 onInitializeAccessibilityEvent(event); 6300 event.getText().add(text); 6301 event.setContentDescription(null); 6302 mParent.requestSendAccessibilityEvent(this, event); 6303 } 6304 } 6305 6306 /** 6307 * @see #sendAccessibilityEvent(int) 6308 * 6309 * Note: Called from the default {@link AccessibilityDelegate}. 6310 * 6311 * @hide 6312 */ 6313 public void sendAccessibilityEventInternal(int eventType) { 6314 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6315 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6316 } 6317 } 6318 6319 /** 6320 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6321 * takes as an argument an empty {@link AccessibilityEvent} and does not 6322 * perform a check whether accessibility is enabled. 6323 * <p> 6324 * If an {@link AccessibilityDelegate} has been specified via calling 6325 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6326 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6327 * is responsible for handling this call. 6328 * </p> 6329 * 6330 * @param event The event to send. 6331 * 6332 * @see #sendAccessibilityEvent(int) 6333 */ 6334 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6335 if (mAccessibilityDelegate != null) { 6336 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6337 } else { 6338 sendAccessibilityEventUncheckedInternal(event); 6339 } 6340 } 6341 6342 /** 6343 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6344 * 6345 * Note: Called from the default {@link AccessibilityDelegate}. 6346 * 6347 * @hide 6348 */ 6349 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6350 if (!isShown()) { 6351 return; 6352 } 6353 onInitializeAccessibilityEvent(event); 6354 // Only a subset of accessibility events populates text content. 6355 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6356 dispatchPopulateAccessibilityEvent(event); 6357 } 6358 // In the beginning we called #isShown(), so we know that getParent() is not null. 6359 getParent().requestSendAccessibilityEvent(this, event); 6360 } 6361 6362 /** 6363 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6364 * to its children for adding their text content to the event. Note that the 6365 * event text is populated in a separate dispatch path since we add to the 6366 * event not only the text of the source but also the text of all its descendants. 6367 * A typical implementation will call 6368 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6369 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6370 * on each child. Override this method if custom population of the event text 6371 * content is required. 6372 * <p> 6373 * If an {@link AccessibilityDelegate} has been specified via calling 6374 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6375 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6376 * is responsible for handling this call. 6377 * </p> 6378 * <p> 6379 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6380 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6381 * </p> 6382 * 6383 * @param event The event. 6384 * 6385 * @return True if the event population was completed. 6386 */ 6387 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6388 if (mAccessibilityDelegate != null) { 6389 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6390 } else { 6391 return dispatchPopulateAccessibilityEventInternal(event); 6392 } 6393 } 6394 6395 /** 6396 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6397 * 6398 * Note: Called from the default {@link AccessibilityDelegate}. 6399 * 6400 * @hide 6401 */ 6402 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6403 onPopulateAccessibilityEvent(event); 6404 return false; 6405 } 6406 6407 /** 6408 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6409 * giving a chance to this View to populate the accessibility event with its 6410 * text content. While this method is free to modify event 6411 * attributes other than text content, doing so should normally be performed in 6412 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6413 * <p> 6414 * Example: Adding formatted date string to an accessibility event in addition 6415 * to the text added by the super implementation: 6416 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6417 * super.onPopulateAccessibilityEvent(event); 6418 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6419 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6420 * mCurrentDate.getTimeInMillis(), flags); 6421 * event.getText().add(selectedDateUtterance); 6422 * }</pre> 6423 * <p> 6424 * If an {@link AccessibilityDelegate} has been specified via calling 6425 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6426 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6427 * is responsible for handling this call. 6428 * </p> 6429 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6430 * information to the event, in case the default implementation has basic information to add. 6431 * </p> 6432 * 6433 * @param event The accessibility event which to populate. 6434 * 6435 * @see #sendAccessibilityEvent(int) 6436 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6437 */ 6438 @CallSuper 6439 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6440 if (mAccessibilityDelegate != null) { 6441 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6442 } else { 6443 onPopulateAccessibilityEventInternal(event); 6444 } 6445 } 6446 6447 /** 6448 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6449 * 6450 * Note: Called from the default {@link AccessibilityDelegate}. 6451 * 6452 * @hide 6453 */ 6454 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6455 } 6456 6457 /** 6458 * Initializes an {@link AccessibilityEvent} with information about 6459 * this View which is the event source. In other words, the source of 6460 * an accessibility event is the view whose state change triggered firing 6461 * the event. 6462 * <p> 6463 * Example: Setting the password property of an event in addition 6464 * to properties set by the super implementation: 6465 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6466 * super.onInitializeAccessibilityEvent(event); 6467 * event.setPassword(true); 6468 * }</pre> 6469 * <p> 6470 * If an {@link AccessibilityDelegate} has been specified via calling 6471 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6472 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6473 * is responsible for handling this call. 6474 * </p> 6475 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6476 * information to the event, in case the default implementation has basic information to add. 6477 * </p> 6478 * @param event The event to initialize. 6479 * 6480 * @see #sendAccessibilityEvent(int) 6481 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6482 */ 6483 @CallSuper 6484 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6485 if (mAccessibilityDelegate != null) { 6486 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6487 } else { 6488 onInitializeAccessibilityEventInternal(event); 6489 } 6490 } 6491 6492 /** 6493 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6494 * 6495 * Note: Called from the default {@link AccessibilityDelegate}. 6496 * 6497 * @hide 6498 */ 6499 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6500 event.setSource(this); 6501 event.setClassName(getAccessibilityClassName()); 6502 event.setPackageName(getContext().getPackageName()); 6503 event.setEnabled(isEnabled()); 6504 event.setContentDescription(mContentDescription); 6505 6506 switch (event.getEventType()) { 6507 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6508 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6509 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6510 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6511 event.setItemCount(focusablesTempList.size()); 6512 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6513 if (mAttachInfo != null) { 6514 focusablesTempList.clear(); 6515 } 6516 } break; 6517 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6518 CharSequence text = getIterableTextForAccessibility(); 6519 if (text != null && text.length() > 0) { 6520 event.setFromIndex(getAccessibilitySelectionStart()); 6521 event.setToIndex(getAccessibilitySelectionEnd()); 6522 event.setItemCount(text.length()); 6523 } 6524 } break; 6525 } 6526 } 6527 6528 /** 6529 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6530 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6531 * This method is responsible for obtaining an accessibility node info from a 6532 * pool of reusable instances and calling 6533 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6534 * initialize the former. 6535 * <p> 6536 * Note: The client is responsible for recycling the obtained instance by calling 6537 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6538 * </p> 6539 * 6540 * @return A populated {@link AccessibilityNodeInfo}. 6541 * 6542 * @see AccessibilityNodeInfo 6543 */ 6544 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6545 if (mAccessibilityDelegate != null) { 6546 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6547 } else { 6548 return createAccessibilityNodeInfoInternal(); 6549 } 6550 } 6551 6552 /** 6553 * @see #createAccessibilityNodeInfo() 6554 * 6555 * @hide 6556 */ 6557 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6558 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6559 if (provider != null) { 6560 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6561 } else { 6562 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6563 onInitializeAccessibilityNodeInfo(info); 6564 return info; 6565 } 6566 } 6567 6568 /** 6569 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6570 * The base implementation sets: 6571 * <ul> 6572 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6573 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6574 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6575 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6576 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6577 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6578 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6579 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6580 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6581 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6582 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6583 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6584 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6585 * </ul> 6586 * <p> 6587 * Subclasses should override this method, call the super implementation, 6588 * and set additional attributes. 6589 * </p> 6590 * <p> 6591 * If an {@link AccessibilityDelegate} has been specified via calling 6592 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6593 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6594 * is responsible for handling this call. 6595 * </p> 6596 * 6597 * @param info The instance to initialize. 6598 */ 6599 @CallSuper 6600 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6601 if (mAccessibilityDelegate != null) { 6602 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6603 } else { 6604 onInitializeAccessibilityNodeInfoInternal(info); 6605 } 6606 } 6607 6608 /** 6609 * Gets the location of this view in screen coordinates. 6610 * 6611 * @param outRect The output location 6612 * @hide 6613 */ 6614 public void getBoundsOnScreen(Rect outRect) { 6615 getBoundsOnScreen(outRect, false); 6616 } 6617 6618 /** 6619 * Gets the location of this view in screen coordinates. 6620 * 6621 * @param outRect The output location 6622 * @param clipToParent Whether to clip child bounds to the parent ones. 6623 * @hide 6624 */ 6625 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6626 if (mAttachInfo == null) { 6627 return; 6628 } 6629 6630 RectF position = mAttachInfo.mTmpTransformRect; 6631 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6632 6633 if (!hasIdentityMatrix()) { 6634 getMatrix().mapRect(position); 6635 } 6636 6637 position.offset(mLeft, mTop); 6638 6639 ViewParent parent = mParent; 6640 while (parent instanceof View) { 6641 View parentView = (View) parent; 6642 6643 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6644 6645 if (clipToParent) { 6646 position.left = Math.max(position.left, 0); 6647 position.top = Math.max(position.top, 0); 6648 position.right = Math.min(position.right, parentView.getWidth()); 6649 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6650 } 6651 6652 if (!parentView.hasIdentityMatrix()) { 6653 parentView.getMatrix().mapRect(position); 6654 } 6655 6656 position.offset(parentView.mLeft, parentView.mTop); 6657 6658 parent = parentView.mParent; 6659 } 6660 6661 if (parent instanceof ViewRootImpl) { 6662 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6663 position.offset(0, -viewRootImpl.mCurScrollY); 6664 } 6665 6666 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6667 6668 outRect.set(Math.round(position.left), Math.round(position.top), 6669 Math.round(position.right), Math.round(position.bottom)); 6670 } 6671 6672 /** 6673 * Return the class name of this object to be used for accessibility purposes. 6674 * Subclasses should only override this if they are implementing something that 6675 * should be seen as a completely new class of view when used by accessibility, 6676 * unrelated to the class it is deriving from. This is used to fill in 6677 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6678 */ 6679 public CharSequence getAccessibilityClassName() { 6680 return View.class.getName(); 6681 } 6682 6683 /** 6684 * Called when assist structure is being retrieved from a view as part of 6685 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6686 * @param structure Fill in with structured view data. The default implementation 6687 * fills in all data that can be inferred from the view itself. 6688 */ 6689 public void onProvideStructure(ViewStructure structure) { 6690 final int id = mID; 6691 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6692 && (id&0x0000ffff) != 0) { 6693 String pkg, type, entry; 6694 try { 6695 final Resources res = getResources(); 6696 entry = res.getResourceEntryName(id); 6697 type = res.getResourceTypeName(id); 6698 pkg = res.getResourcePackageName(id); 6699 } catch (Resources.NotFoundException e) { 6700 entry = type = pkg = null; 6701 } 6702 structure.setId(id, pkg, type, entry); 6703 } else { 6704 structure.setId(id, null, null, null); 6705 } 6706 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6707 if (!hasIdentityMatrix()) { 6708 structure.setTransformation(getMatrix()); 6709 } 6710 structure.setElevation(getZ()); 6711 structure.setVisibility(getVisibility()); 6712 structure.setEnabled(isEnabled()); 6713 if (isClickable()) { 6714 structure.setClickable(true); 6715 } 6716 if (isFocusable()) { 6717 structure.setFocusable(true); 6718 } 6719 if (isFocused()) { 6720 structure.setFocused(true); 6721 } 6722 if (isAccessibilityFocused()) { 6723 structure.setAccessibilityFocused(true); 6724 } 6725 if (isSelected()) { 6726 structure.setSelected(true); 6727 } 6728 if (isActivated()) { 6729 structure.setActivated(true); 6730 } 6731 if (isLongClickable()) { 6732 structure.setLongClickable(true); 6733 } 6734 if (this instanceof Checkable) { 6735 structure.setCheckable(true); 6736 if (((Checkable)this).isChecked()) { 6737 structure.setChecked(true); 6738 } 6739 } 6740 if (isContextClickable()) { 6741 structure.setContextClickable(true); 6742 } 6743 structure.setClassName(getAccessibilityClassName().toString()); 6744 structure.setContentDescription(getContentDescription()); 6745 } 6746 6747 /** 6748 * Called when assist structure is being retrieved from a view as part of 6749 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6750 * generate additional virtual structure under this view. The defaullt implementation 6751 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6752 * view's virtual accessibility nodes, if any. You can override this for a more 6753 * optimal implementation providing this data. 6754 */ 6755 public void onProvideVirtualStructure(ViewStructure structure) { 6756 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6757 if (provider != null) { 6758 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6759 structure.setChildCount(1); 6760 ViewStructure root = structure.newChild(0); 6761 populateVirtualStructure(root, provider, info); 6762 info.recycle(); 6763 } 6764 } 6765 6766 private void populateVirtualStructure(ViewStructure structure, 6767 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6768 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6769 null, null, null); 6770 Rect rect = structure.getTempRect(); 6771 info.getBoundsInParent(rect); 6772 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6773 structure.setVisibility(VISIBLE); 6774 structure.setEnabled(info.isEnabled()); 6775 if (info.isClickable()) { 6776 structure.setClickable(true); 6777 } 6778 if (info.isFocusable()) { 6779 structure.setFocusable(true); 6780 } 6781 if (info.isFocused()) { 6782 structure.setFocused(true); 6783 } 6784 if (info.isAccessibilityFocused()) { 6785 structure.setAccessibilityFocused(true); 6786 } 6787 if (info.isSelected()) { 6788 structure.setSelected(true); 6789 } 6790 if (info.isLongClickable()) { 6791 structure.setLongClickable(true); 6792 } 6793 if (info.isCheckable()) { 6794 structure.setCheckable(true); 6795 if (info.isChecked()) { 6796 structure.setChecked(true); 6797 } 6798 } 6799 if (info.isContextClickable()) { 6800 structure.setContextClickable(true); 6801 } 6802 CharSequence cname = info.getClassName(); 6803 structure.setClassName(cname != null ? cname.toString() : null); 6804 structure.setContentDescription(info.getContentDescription()); 6805 if (info.getText() != null || info.getError() != null) { 6806 structure.setText(info.getText(), info.getTextSelectionStart(), 6807 info.getTextSelectionEnd()); 6808 } 6809 final int NCHILDREN = info.getChildCount(); 6810 if (NCHILDREN > 0) { 6811 structure.setChildCount(NCHILDREN); 6812 for (int i=0; i<NCHILDREN; i++) { 6813 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6814 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6815 ViewStructure child = structure.newChild(i); 6816 populateVirtualStructure(child, provider, cinfo); 6817 cinfo.recycle(); 6818 } 6819 } 6820 } 6821 6822 /** 6823 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6824 * implementation calls {@link #onProvideStructure} and 6825 * {@link #onProvideVirtualStructure}. 6826 */ 6827 public void dispatchProvideStructure(ViewStructure structure) { 6828 if (!isAssistBlocked()) { 6829 onProvideStructure(structure); 6830 onProvideVirtualStructure(structure); 6831 } else { 6832 structure.setClassName(getAccessibilityClassName().toString()); 6833 structure.setAssistBlocked(true); 6834 } 6835 } 6836 6837 /** 6838 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6839 * 6840 * Note: Called from the default {@link AccessibilityDelegate}. 6841 * 6842 * @hide 6843 */ 6844 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6845 if (mAttachInfo == null) { 6846 return; 6847 } 6848 6849 Rect bounds = mAttachInfo.mTmpInvalRect; 6850 6851 getDrawingRect(bounds); 6852 info.setBoundsInParent(bounds); 6853 6854 getBoundsOnScreen(bounds, true); 6855 info.setBoundsInScreen(bounds); 6856 6857 ViewParent parent = getParentForAccessibility(); 6858 if (parent instanceof View) { 6859 info.setParent((View) parent); 6860 } 6861 6862 if (mID != View.NO_ID) { 6863 View rootView = getRootView(); 6864 if (rootView == null) { 6865 rootView = this; 6866 } 6867 6868 View label = rootView.findLabelForView(this, mID); 6869 if (label != null) { 6870 info.setLabeledBy(label); 6871 } 6872 6873 if ((mAttachInfo.mAccessibilityFetchFlags 6874 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6875 && Resources.resourceHasPackage(mID)) { 6876 try { 6877 String viewId = getResources().getResourceName(mID); 6878 info.setViewIdResourceName(viewId); 6879 } catch (Resources.NotFoundException nfe) { 6880 /* ignore */ 6881 } 6882 } 6883 } 6884 6885 if (mLabelForId != View.NO_ID) { 6886 View rootView = getRootView(); 6887 if (rootView == null) { 6888 rootView = this; 6889 } 6890 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6891 if (labeled != null) { 6892 info.setLabelFor(labeled); 6893 } 6894 } 6895 6896 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6897 View rootView = getRootView(); 6898 if (rootView == null) { 6899 rootView = this; 6900 } 6901 View next = rootView.findViewInsideOutShouldExist(this, 6902 mAccessibilityTraversalBeforeId); 6903 if (next != null && next.includeForAccessibility()) { 6904 info.setTraversalBefore(next); 6905 } 6906 } 6907 6908 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6909 View rootView = getRootView(); 6910 if (rootView == null) { 6911 rootView = this; 6912 } 6913 View next = rootView.findViewInsideOutShouldExist(this, 6914 mAccessibilityTraversalAfterId); 6915 if (next != null && next.includeForAccessibility()) { 6916 info.setTraversalAfter(next); 6917 } 6918 } 6919 6920 info.setVisibleToUser(isVisibleToUser()); 6921 6922 info.setImportantForAccessibility(isImportantForAccessibility()); 6923 info.setPackageName(mContext.getPackageName()); 6924 info.setClassName(getAccessibilityClassName()); 6925 info.setContentDescription(getContentDescription()); 6926 6927 info.setEnabled(isEnabled()); 6928 info.setClickable(isClickable()); 6929 info.setFocusable(isFocusable()); 6930 info.setFocused(isFocused()); 6931 info.setAccessibilityFocused(isAccessibilityFocused()); 6932 info.setSelected(isSelected()); 6933 info.setLongClickable(isLongClickable()); 6934 info.setContextClickable(isContextClickable()); 6935 info.setLiveRegion(getAccessibilityLiveRegion()); 6936 6937 // TODO: These make sense only if we are in an AdapterView but all 6938 // views can be selected. Maybe from accessibility perspective 6939 // we should report as selectable view in an AdapterView. 6940 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6941 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6942 6943 if (isFocusable()) { 6944 if (isFocused()) { 6945 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6946 } else { 6947 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6948 } 6949 } 6950 6951 if (!isAccessibilityFocused()) { 6952 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6953 } else { 6954 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6955 } 6956 6957 if (isClickable() && isEnabled()) { 6958 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6959 } 6960 6961 if (isLongClickable() && isEnabled()) { 6962 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6963 } 6964 6965 if (isContextClickable() && isEnabled()) { 6966 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6967 } 6968 6969 CharSequence text = getIterableTextForAccessibility(); 6970 if (text != null && text.length() > 0) { 6971 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6972 6973 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6974 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6975 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6976 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6977 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6978 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6979 } 6980 6981 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6982 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6983 } 6984 6985 /** 6986 * Determine the order in which this view will be drawn relative to its siblings for a11y 6987 * 6988 * @param info The info whose drawing order should be populated 6989 */ 6990 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6991 /* 6992 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6993 * drawing order may not be well-defined, and some Views with custom drawing order may 6994 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6995 */ 6996 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6997 info.setDrawingOrder(0); 6998 return; 6999 } 7000 int drawingOrderInParent = 1; 7001 // Iterate up the hierarchy if parents are not important for a11y 7002 View viewAtDrawingLevel = this; 7003 final ViewParent parent = getParentForAccessibility(); 7004 while (viewAtDrawingLevel != parent) { 7005 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 7006 if (!(currentParent instanceof ViewGroup)) { 7007 // Should only happen for the Decor 7008 drawingOrderInParent = 0; 7009 break; 7010 } else { 7011 final ViewGroup parentGroup = (ViewGroup) currentParent; 7012 final int childCount = parentGroup.getChildCount(); 7013 if (childCount > 1) { 7014 List<View> preorderedList = parentGroup.buildOrderedChildList(); 7015 if (preorderedList != null) { 7016 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 7017 for (int i = 0; i < childDrawIndex; i++) { 7018 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 7019 } 7020 } else { 7021 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 7022 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 7023 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 7024 .getChildDrawingOrder(childCount, childIndex) : childIndex; 7025 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 7026 if (childDrawIndex != 0) { 7027 for (int i = 0; i < numChildrenToIterate; i++) { 7028 final int otherDrawIndex = (customOrder ? 7029 parentGroup.getChildDrawingOrder(childCount, i) : i); 7030 if (otherDrawIndex < childDrawIndex) { 7031 drawingOrderInParent += 7032 numViewsForAccessibility(parentGroup.getChildAt(i)); 7033 } 7034 } 7035 } 7036 } 7037 } 7038 } 7039 viewAtDrawingLevel = (View) currentParent; 7040 } 7041 info.setDrawingOrder(drawingOrderInParent); 7042 } 7043 7044 private static int numViewsForAccessibility(View view) { 7045 if (view != null) { 7046 if (view.includeForAccessibility()) { 7047 return 1; 7048 } else if (view instanceof ViewGroup) { 7049 return ((ViewGroup) view).getNumChildrenForAccessibility(); 7050 } 7051 } 7052 return 0; 7053 } 7054 7055 private View findLabelForView(View view, int labeledId) { 7056 if (mMatchLabelForPredicate == null) { 7057 mMatchLabelForPredicate = new MatchLabelForPredicate(); 7058 } 7059 mMatchLabelForPredicate.mLabeledId = labeledId; 7060 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 7061 } 7062 7063 /** 7064 * Computes whether this view is visible to the user. Such a view is 7065 * attached, visible, all its predecessors are visible, it is not clipped 7066 * entirely by its predecessors, and has an alpha greater than zero. 7067 * 7068 * @return Whether the view is visible on the screen. 7069 * 7070 * @hide 7071 */ 7072 protected boolean isVisibleToUser() { 7073 return isVisibleToUser(null); 7074 } 7075 7076 /** 7077 * Computes whether the given portion of this view is visible to the user. 7078 * Such a view is attached, visible, all its predecessors are visible, 7079 * has an alpha greater than zero, and the specified portion is not 7080 * clipped entirely by its predecessors. 7081 * 7082 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7083 * <code>null</code>, and the entire view will be tested in this case. 7084 * When <code>true</code> is returned by the function, the actual visible 7085 * region will be stored in this parameter; that is, if boundInView is fully 7086 * contained within the view, no modification will be made, otherwise regions 7087 * outside of the visible area of the view will be clipped. 7088 * 7089 * @return Whether the specified portion of the view is visible on the screen. 7090 * 7091 * @hide 7092 */ 7093 protected boolean isVisibleToUser(Rect boundInView) { 7094 if (mAttachInfo != null) { 7095 // Attached to invisible window means this view is not visible. 7096 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7097 return false; 7098 } 7099 // An invisible predecessor or one with alpha zero means 7100 // that this view is not visible to the user. 7101 Object current = this; 7102 while (current instanceof View) { 7103 View view = (View) current; 7104 // We have attach info so this view is attached and there is no 7105 // need to check whether we reach to ViewRootImpl on the way up. 7106 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7107 view.getVisibility() != VISIBLE) { 7108 return false; 7109 } 7110 current = view.mParent; 7111 } 7112 // Check if the view is entirely covered by its predecessors. 7113 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7114 Point offset = mAttachInfo.mPoint; 7115 if (!getGlobalVisibleRect(visibleRect, offset)) { 7116 return false; 7117 } 7118 // Check if the visible portion intersects the rectangle of interest. 7119 if (boundInView != null) { 7120 visibleRect.offset(-offset.x, -offset.y); 7121 return boundInView.intersect(visibleRect); 7122 } 7123 return true; 7124 } 7125 return false; 7126 } 7127 7128 /** 7129 * Returns the delegate for implementing accessibility support via 7130 * composition. For more details see {@link AccessibilityDelegate}. 7131 * 7132 * @return The delegate, or null if none set. 7133 * 7134 * @hide 7135 */ 7136 public AccessibilityDelegate getAccessibilityDelegate() { 7137 return mAccessibilityDelegate; 7138 } 7139 7140 /** 7141 * Sets a delegate for implementing accessibility support via composition 7142 * (as opposed to inheritance). For more details, see 7143 * {@link AccessibilityDelegate}. 7144 * <p> 7145 * <strong>Note:</strong> On platform versions prior to 7146 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7147 * views in the {@code android.widget.*} package are called <i>before</i> 7148 * host methods. This prevents certain properties such as class name from 7149 * being modified by overriding 7150 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7151 * as any changes will be overwritten by the host class. 7152 * <p> 7153 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7154 * methods are called <i>after</i> host methods, which all properties to be 7155 * modified without being overwritten by the host class. 7156 * 7157 * @param delegate the object to which accessibility method calls should be 7158 * delegated 7159 * @see AccessibilityDelegate 7160 */ 7161 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7162 mAccessibilityDelegate = delegate; 7163 } 7164 7165 /** 7166 * Gets the provider for managing a virtual view hierarchy rooted at this View 7167 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7168 * that explore the window content. 7169 * <p> 7170 * If this method returns an instance, this instance is responsible for managing 7171 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7172 * View including the one representing the View itself. Similarly the returned 7173 * instance is responsible for performing accessibility actions on any virtual 7174 * view or the root view itself. 7175 * </p> 7176 * <p> 7177 * If an {@link AccessibilityDelegate} has been specified via calling 7178 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7179 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7180 * is responsible for handling this call. 7181 * </p> 7182 * 7183 * @return The provider. 7184 * 7185 * @see AccessibilityNodeProvider 7186 */ 7187 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7188 if (mAccessibilityDelegate != null) { 7189 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7190 } else { 7191 return null; 7192 } 7193 } 7194 7195 /** 7196 * Gets the unique identifier of this view on the screen for accessibility purposes. 7197 * 7198 * @return The view accessibility id. 7199 * 7200 * @hide 7201 */ 7202 public int getAccessibilityViewId() { 7203 if (mAccessibilityViewId == NO_ID) { 7204 mAccessibilityViewId = sNextAccessibilityViewId++; 7205 } 7206 return mAccessibilityViewId; 7207 } 7208 7209 /** 7210 * Gets the unique identifier of the window in which this View reseides. 7211 * 7212 * @return The window accessibility id. 7213 * 7214 * @hide 7215 */ 7216 public int getAccessibilityWindowId() { 7217 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7218 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7219 } 7220 7221 /** 7222 * Returns the {@link View}'s content description. 7223 * <p> 7224 * <strong>Note:</strong> Do not override this method, as it will have no 7225 * effect on the content description presented to accessibility services. 7226 * You must call {@link #setContentDescription(CharSequence)} to modify the 7227 * content description. 7228 * 7229 * @return the content description 7230 * @see #setContentDescription(CharSequence) 7231 * @attr ref android.R.styleable#View_contentDescription 7232 */ 7233 @ViewDebug.ExportedProperty(category = "accessibility") 7234 public CharSequence getContentDescription() { 7235 return mContentDescription; 7236 } 7237 7238 /** 7239 * Sets the {@link View}'s content description. 7240 * <p> 7241 * A content description briefly describes the view and is primarily used 7242 * for accessibility support to determine how a view should be presented to 7243 * the user. In the case of a view with no textual representation, such as 7244 * {@link android.widget.ImageButton}, a useful content description 7245 * explains what the view does. For example, an image button with a phone 7246 * icon that is used to place a call may use "Call" as its content 7247 * description. An image of a floppy disk that is used to save a file may 7248 * use "Save". 7249 * 7250 * @param contentDescription The content description. 7251 * @see #getContentDescription() 7252 * @attr ref android.R.styleable#View_contentDescription 7253 */ 7254 @RemotableViewMethod 7255 public void setContentDescription(CharSequence contentDescription) { 7256 if (mContentDescription == null) { 7257 if (contentDescription == null) { 7258 return; 7259 } 7260 } else if (mContentDescription.equals(contentDescription)) { 7261 return; 7262 } 7263 mContentDescription = contentDescription; 7264 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7265 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7266 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7267 notifySubtreeAccessibilityStateChangedIfNeeded(); 7268 } else { 7269 notifyViewAccessibilityStateChangedIfNeeded( 7270 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7271 } 7272 } 7273 7274 /** 7275 * Sets the id of a view before which this one is visited in accessibility traversal. 7276 * A screen-reader must visit the content of this view before the content of the one 7277 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7278 * will traverse the entire content of B before traversing the entire content of A, 7279 * regardles of what traversal strategy it is using. 7280 * <p> 7281 * Views that do not have specified before/after relationships are traversed in order 7282 * determined by the screen-reader. 7283 * </p> 7284 * <p> 7285 * Setting that this view is before a view that is not important for accessibility 7286 * or if this view is not important for accessibility will have no effect as the 7287 * screen-reader is not aware of unimportant views. 7288 * </p> 7289 * 7290 * @param beforeId The id of a view this one precedes in accessibility traversal. 7291 * 7292 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7293 * 7294 * @see #setImportantForAccessibility(int) 7295 */ 7296 @RemotableViewMethod 7297 public void setAccessibilityTraversalBefore(int beforeId) { 7298 if (mAccessibilityTraversalBeforeId == beforeId) { 7299 return; 7300 } 7301 mAccessibilityTraversalBeforeId = beforeId; 7302 notifyViewAccessibilityStateChangedIfNeeded( 7303 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7304 } 7305 7306 /** 7307 * Gets the id of a view before which this one is visited in accessibility traversal. 7308 * 7309 * @return The id of a view this one precedes in accessibility traversal if 7310 * specified, otherwise {@link #NO_ID}. 7311 * 7312 * @see #setAccessibilityTraversalBefore(int) 7313 */ 7314 public int getAccessibilityTraversalBefore() { 7315 return mAccessibilityTraversalBeforeId; 7316 } 7317 7318 /** 7319 * Sets the id of a view after which this one is visited in accessibility traversal. 7320 * A screen-reader must visit the content of the other view before the content of this 7321 * one. For example, if view B is set to be after view A, then a screen-reader 7322 * will traverse the entire content of A before traversing the entire content of B, 7323 * regardles of what traversal strategy it is using. 7324 * <p> 7325 * Views that do not have specified before/after relationships are traversed in order 7326 * determined by the screen-reader. 7327 * </p> 7328 * <p> 7329 * Setting that this view is after a view that is not important for accessibility 7330 * or if this view is not important for accessibility will have no effect as the 7331 * screen-reader is not aware of unimportant views. 7332 * </p> 7333 * 7334 * @param afterId The id of a view this one succedees in accessibility traversal. 7335 * 7336 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7337 * 7338 * @see #setImportantForAccessibility(int) 7339 */ 7340 @RemotableViewMethod 7341 public void setAccessibilityTraversalAfter(int afterId) { 7342 if (mAccessibilityTraversalAfterId == afterId) { 7343 return; 7344 } 7345 mAccessibilityTraversalAfterId = afterId; 7346 notifyViewAccessibilityStateChangedIfNeeded( 7347 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7348 } 7349 7350 /** 7351 * Gets the id of a view after which this one is visited in accessibility traversal. 7352 * 7353 * @return The id of a view this one succeedes in accessibility traversal if 7354 * specified, otherwise {@link #NO_ID}. 7355 * 7356 * @see #setAccessibilityTraversalAfter(int) 7357 */ 7358 public int getAccessibilityTraversalAfter() { 7359 return mAccessibilityTraversalAfterId; 7360 } 7361 7362 /** 7363 * Gets the id of a view for which this view serves as a label for 7364 * accessibility purposes. 7365 * 7366 * @return The labeled view id. 7367 */ 7368 @ViewDebug.ExportedProperty(category = "accessibility") 7369 public int getLabelFor() { 7370 return mLabelForId; 7371 } 7372 7373 /** 7374 * Sets the id of a view for which this view serves as a label for 7375 * accessibility purposes. 7376 * 7377 * @param id The labeled view id. 7378 */ 7379 @RemotableViewMethod 7380 public void setLabelFor(@IdRes int id) { 7381 if (mLabelForId == id) { 7382 return; 7383 } 7384 mLabelForId = id; 7385 if (mLabelForId != View.NO_ID 7386 && mID == View.NO_ID) { 7387 mID = generateViewId(); 7388 } 7389 notifyViewAccessibilityStateChangedIfNeeded( 7390 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7391 } 7392 7393 /** 7394 * Invoked whenever this view loses focus, either by losing window focus or by losing 7395 * focus within its window. This method can be used to clear any state tied to the 7396 * focus. For instance, if a button is held pressed with the trackball and the window 7397 * loses focus, this method can be used to cancel the press. 7398 * 7399 * Subclasses of View overriding this method should always call super.onFocusLost(). 7400 * 7401 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7402 * @see #onWindowFocusChanged(boolean) 7403 * 7404 * @hide pending API council approval 7405 */ 7406 @CallSuper 7407 protected void onFocusLost() { 7408 resetPressedState(); 7409 } 7410 7411 private void resetPressedState() { 7412 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7413 return; 7414 } 7415 7416 if (isPressed()) { 7417 setPressed(false); 7418 7419 if (!mHasPerformedLongPress) { 7420 removeLongPressCallback(); 7421 } 7422 } 7423 } 7424 7425 /** 7426 * Returns true if this view has focus 7427 * 7428 * @return True if this view has focus, false otherwise. 7429 */ 7430 @ViewDebug.ExportedProperty(category = "focus") 7431 public boolean isFocused() { 7432 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7433 } 7434 7435 /** 7436 * Find the view in the hierarchy rooted at this view that currently has 7437 * focus. 7438 * 7439 * @return The view that currently has focus, or null if no focused view can 7440 * be found. 7441 */ 7442 public View findFocus() { 7443 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7444 } 7445 7446 /** 7447 * Indicates whether this view is one of the set of scrollable containers in 7448 * its window. 7449 * 7450 * @return whether this view is one of the set of scrollable containers in 7451 * its window 7452 * 7453 * @attr ref android.R.styleable#View_isScrollContainer 7454 */ 7455 public boolean isScrollContainer() { 7456 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7457 } 7458 7459 /** 7460 * Change whether this view is one of the set of scrollable containers in 7461 * its window. This will be used to determine whether the window can 7462 * resize or must pan when a soft input area is open -- scrollable 7463 * containers allow the window to use resize mode since the container 7464 * will appropriately shrink. 7465 * 7466 * @attr ref android.R.styleable#View_isScrollContainer 7467 */ 7468 public void setScrollContainer(boolean isScrollContainer) { 7469 if (isScrollContainer) { 7470 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7471 mAttachInfo.mScrollContainers.add(this); 7472 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7473 } 7474 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7475 } else { 7476 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7477 mAttachInfo.mScrollContainers.remove(this); 7478 } 7479 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7480 } 7481 } 7482 7483 /** 7484 * Returns the quality of the drawing cache. 7485 * 7486 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7487 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7488 * 7489 * @see #setDrawingCacheQuality(int) 7490 * @see #setDrawingCacheEnabled(boolean) 7491 * @see #isDrawingCacheEnabled() 7492 * 7493 * @attr ref android.R.styleable#View_drawingCacheQuality 7494 */ 7495 @DrawingCacheQuality 7496 public int getDrawingCacheQuality() { 7497 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7498 } 7499 7500 /** 7501 * Set the drawing cache quality of this view. This value is used only when the 7502 * drawing cache is enabled 7503 * 7504 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7505 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7506 * 7507 * @see #getDrawingCacheQuality() 7508 * @see #setDrawingCacheEnabled(boolean) 7509 * @see #isDrawingCacheEnabled() 7510 * 7511 * @attr ref android.R.styleable#View_drawingCacheQuality 7512 */ 7513 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7514 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7515 } 7516 7517 /** 7518 * Returns whether the screen should remain on, corresponding to the current 7519 * value of {@link #KEEP_SCREEN_ON}. 7520 * 7521 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7522 * 7523 * @see #setKeepScreenOn(boolean) 7524 * 7525 * @attr ref android.R.styleable#View_keepScreenOn 7526 */ 7527 public boolean getKeepScreenOn() { 7528 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7529 } 7530 7531 /** 7532 * Controls whether the screen should remain on, modifying the 7533 * value of {@link #KEEP_SCREEN_ON}. 7534 * 7535 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7536 * 7537 * @see #getKeepScreenOn() 7538 * 7539 * @attr ref android.R.styleable#View_keepScreenOn 7540 */ 7541 public void setKeepScreenOn(boolean keepScreenOn) { 7542 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7543 } 7544 7545 /** 7546 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7547 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7548 * 7549 * @attr ref android.R.styleable#View_nextFocusLeft 7550 */ 7551 public int getNextFocusLeftId() { 7552 return mNextFocusLeftId; 7553 } 7554 7555 /** 7556 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7557 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7558 * decide automatically. 7559 * 7560 * @attr ref android.R.styleable#View_nextFocusLeft 7561 */ 7562 public void setNextFocusLeftId(int nextFocusLeftId) { 7563 mNextFocusLeftId = nextFocusLeftId; 7564 } 7565 7566 /** 7567 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7568 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7569 * 7570 * @attr ref android.R.styleable#View_nextFocusRight 7571 */ 7572 public int getNextFocusRightId() { 7573 return mNextFocusRightId; 7574 } 7575 7576 /** 7577 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7578 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7579 * decide automatically. 7580 * 7581 * @attr ref android.R.styleable#View_nextFocusRight 7582 */ 7583 public void setNextFocusRightId(int nextFocusRightId) { 7584 mNextFocusRightId = nextFocusRightId; 7585 } 7586 7587 /** 7588 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7589 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7590 * 7591 * @attr ref android.R.styleable#View_nextFocusUp 7592 */ 7593 public int getNextFocusUpId() { 7594 return mNextFocusUpId; 7595 } 7596 7597 /** 7598 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7599 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7600 * decide automatically. 7601 * 7602 * @attr ref android.R.styleable#View_nextFocusUp 7603 */ 7604 public void setNextFocusUpId(int nextFocusUpId) { 7605 mNextFocusUpId = nextFocusUpId; 7606 } 7607 7608 /** 7609 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7610 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7611 * 7612 * @attr ref android.R.styleable#View_nextFocusDown 7613 */ 7614 public int getNextFocusDownId() { 7615 return mNextFocusDownId; 7616 } 7617 7618 /** 7619 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7620 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7621 * decide automatically. 7622 * 7623 * @attr ref android.R.styleable#View_nextFocusDown 7624 */ 7625 public void setNextFocusDownId(int nextFocusDownId) { 7626 mNextFocusDownId = nextFocusDownId; 7627 } 7628 7629 /** 7630 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7631 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7632 * 7633 * @attr ref android.R.styleable#View_nextFocusForward 7634 */ 7635 public int getNextFocusForwardId() { 7636 return mNextFocusForwardId; 7637 } 7638 7639 /** 7640 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7641 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7642 * decide automatically. 7643 * 7644 * @attr ref android.R.styleable#View_nextFocusForward 7645 */ 7646 public void setNextFocusForwardId(int nextFocusForwardId) { 7647 mNextFocusForwardId = nextFocusForwardId; 7648 } 7649 7650 /** 7651 * Returns the visibility of this view and all of its ancestors 7652 * 7653 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7654 */ 7655 public boolean isShown() { 7656 View current = this; 7657 //noinspection ConstantConditions 7658 do { 7659 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7660 return false; 7661 } 7662 ViewParent parent = current.mParent; 7663 if (parent == null) { 7664 return false; // We are not attached to the view root 7665 } 7666 if (!(parent instanceof View)) { 7667 return true; 7668 } 7669 current = (View) parent; 7670 } while (current != null); 7671 7672 return false; 7673 } 7674 7675 /** 7676 * Called by the view hierarchy when the content insets for a window have 7677 * changed, to allow it to adjust its content to fit within those windows. 7678 * The content insets tell you the space that the status bar, input method, 7679 * and other system windows infringe on the application's window. 7680 * 7681 * <p>You do not normally need to deal with this function, since the default 7682 * window decoration given to applications takes care of applying it to the 7683 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7684 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7685 * and your content can be placed under those system elements. You can then 7686 * use this method within your view hierarchy if you have parts of your UI 7687 * which you would like to ensure are not being covered. 7688 * 7689 * <p>The default implementation of this method simply applies the content 7690 * insets to the view's padding, consuming that content (modifying the 7691 * insets to be 0), and returning true. This behavior is off by default, but can 7692 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7693 * 7694 * <p>This function's traversal down the hierarchy is depth-first. The same content 7695 * insets object is propagated down the hierarchy, so any changes made to it will 7696 * be seen by all following views (including potentially ones above in 7697 * the hierarchy since this is a depth-first traversal). The first view 7698 * that returns true will abort the entire traversal. 7699 * 7700 * <p>The default implementation works well for a situation where it is 7701 * used with a container that covers the entire window, allowing it to 7702 * apply the appropriate insets to its content on all edges. If you need 7703 * a more complicated layout (such as two different views fitting system 7704 * windows, one on the top of the window, and one on the bottom), 7705 * you can override the method and handle the insets however you would like. 7706 * Note that the insets provided by the framework are always relative to the 7707 * far edges of the window, not accounting for the location of the called view 7708 * within that window. (In fact when this method is called you do not yet know 7709 * where the layout will place the view, as it is done before layout happens.) 7710 * 7711 * <p>Note: unlike many View methods, there is no dispatch phase to this 7712 * call. If you are overriding it in a ViewGroup and want to allow the 7713 * call to continue to your children, you must be sure to call the super 7714 * implementation. 7715 * 7716 * <p>Here is a sample layout that makes use of fitting system windows 7717 * to have controls for a video view placed inside of the window decorations 7718 * that it hides and shows. This can be used with code like the second 7719 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7720 * 7721 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7722 * 7723 * @param insets Current content insets of the window. Prior to 7724 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7725 * the insets or else you and Android will be unhappy. 7726 * 7727 * @return {@code true} if this view applied the insets and it should not 7728 * continue propagating further down the hierarchy, {@code false} otherwise. 7729 * @see #getFitsSystemWindows() 7730 * @see #setFitsSystemWindows(boolean) 7731 * @see #setSystemUiVisibility(int) 7732 * 7733 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7734 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7735 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7736 * to implement handling their own insets. 7737 */ 7738 @Deprecated 7739 protected boolean fitSystemWindows(Rect insets) { 7740 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7741 if (insets == null) { 7742 // Null insets by definition have already been consumed. 7743 // This call cannot apply insets since there are none to apply, 7744 // so return false. 7745 return false; 7746 } 7747 // If we're not in the process of dispatching the newer apply insets call, 7748 // that means we're not in the compatibility path. Dispatch into the newer 7749 // apply insets path and take things from there. 7750 try { 7751 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7752 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7753 } finally { 7754 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7755 } 7756 } else { 7757 // We're being called from the newer apply insets path. 7758 // Perform the standard fallback behavior. 7759 return fitSystemWindowsInt(insets); 7760 } 7761 } 7762 7763 private boolean fitSystemWindowsInt(Rect insets) { 7764 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7765 mUserPaddingStart = UNDEFINED_PADDING; 7766 mUserPaddingEnd = UNDEFINED_PADDING; 7767 Rect localInsets = sThreadLocal.get(); 7768 if (localInsets == null) { 7769 localInsets = new Rect(); 7770 sThreadLocal.set(localInsets); 7771 } 7772 boolean res = computeFitSystemWindows(insets, localInsets); 7773 mUserPaddingLeftInitial = localInsets.left; 7774 mUserPaddingRightInitial = localInsets.right; 7775 internalSetPadding(localInsets.left, localInsets.top, 7776 localInsets.right, localInsets.bottom); 7777 return res; 7778 } 7779 return false; 7780 } 7781 7782 /** 7783 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7784 * 7785 * <p>This method should be overridden by views that wish to apply a policy different from or 7786 * in addition to the default behavior. Clients that wish to force a view subtree 7787 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7788 * 7789 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7790 * it will be called during dispatch instead of this method. The listener may optionally 7791 * call this method from its own implementation if it wishes to apply the view's default 7792 * insets policy in addition to its own.</p> 7793 * 7794 * <p>Implementations of this method should either return the insets parameter unchanged 7795 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7796 * that this view applied itself. This allows new inset types added in future platform 7797 * versions to pass through existing implementations unchanged without being erroneously 7798 * consumed.</p> 7799 * 7800 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7801 * property is set then the view will consume the system window insets and apply them 7802 * as padding for the view.</p> 7803 * 7804 * @param insets Insets to apply 7805 * @return The supplied insets with any applied insets consumed 7806 */ 7807 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7808 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7809 // We weren't called from within a direct call to fitSystemWindows, 7810 // call into it as a fallback in case we're in a class that overrides it 7811 // and has logic to perform. 7812 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7813 return insets.consumeSystemWindowInsets(); 7814 } 7815 } else { 7816 // We were called from within a direct call to fitSystemWindows. 7817 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7818 return insets.consumeSystemWindowInsets(); 7819 } 7820 } 7821 return insets; 7822 } 7823 7824 /** 7825 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7826 * window insets to this view. The listener's 7827 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7828 * method will be called instead of the view's 7829 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7830 * 7831 * @param listener Listener to set 7832 * 7833 * @see #onApplyWindowInsets(WindowInsets) 7834 */ 7835 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7836 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7837 } 7838 7839 /** 7840 * Request to apply the given window insets to this view or another view in its subtree. 7841 * 7842 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7843 * obscured by window decorations or overlays. This can include the status and navigation bars, 7844 * action bars, input methods and more. New inset categories may be added in the future. 7845 * The method returns the insets provided minus any that were applied by this view or its 7846 * children.</p> 7847 * 7848 * <p>Clients wishing to provide custom behavior should override the 7849 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7850 * {@link OnApplyWindowInsetsListener} via the 7851 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7852 * method.</p> 7853 * 7854 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7855 * </p> 7856 * 7857 * @param insets Insets to apply 7858 * @return The provided insets minus the insets that were consumed 7859 */ 7860 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7861 try { 7862 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7863 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7864 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7865 } else { 7866 return onApplyWindowInsets(insets); 7867 } 7868 } finally { 7869 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7870 } 7871 } 7872 7873 /** 7874 * Compute the view's coordinate within the surface. 7875 * 7876 * <p>Computes the coordinates of this view in its surface. The argument 7877 * must be an array of two integers. After the method returns, the array 7878 * contains the x and y location in that order.</p> 7879 * @hide 7880 * @param location an array of two integers in which to hold the coordinates 7881 */ 7882 public void getLocationInSurface(@Size(2) int[] location) { 7883 getLocationInWindow(location); 7884 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7885 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7886 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7887 } 7888 } 7889 7890 /** 7891 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7892 * only available if the view is attached. 7893 * 7894 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7895 */ 7896 public WindowInsets getRootWindowInsets() { 7897 if (mAttachInfo != null) { 7898 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7899 } 7900 return null; 7901 } 7902 7903 /** 7904 * @hide Compute the insets that should be consumed by this view and the ones 7905 * that should propagate to those under it. 7906 */ 7907 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7908 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7909 || mAttachInfo == null 7910 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7911 && !mAttachInfo.mOverscanRequested)) { 7912 outLocalInsets.set(inoutInsets); 7913 inoutInsets.set(0, 0, 0, 0); 7914 return true; 7915 } else { 7916 // The application wants to take care of fitting system window for 7917 // the content... however we still need to take care of any overscan here. 7918 final Rect overscan = mAttachInfo.mOverscanInsets; 7919 outLocalInsets.set(overscan); 7920 inoutInsets.left -= overscan.left; 7921 inoutInsets.top -= overscan.top; 7922 inoutInsets.right -= overscan.right; 7923 inoutInsets.bottom -= overscan.bottom; 7924 return false; 7925 } 7926 } 7927 7928 /** 7929 * Compute insets that should be consumed by this view and the ones that should propagate 7930 * to those under it. 7931 * 7932 * @param in Insets currently being processed by this View, likely received as a parameter 7933 * to {@link #onApplyWindowInsets(WindowInsets)}. 7934 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7935 * by this view 7936 * @return Insets that should be passed along to views under this one 7937 */ 7938 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7939 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7940 || mAttachInfo == null 7941 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7942 outLocalInsets.set(in.getSystemWindowInsets()); 7943 return in.consumeSystemWindowInsets(); 7944 } else { 7945 outLocalInsets.set(0, 0, 0, 0); 7946 return in; 7947 } 7948 } 7949 7950 /** 7951 * Sets whether or not this view should account for system screen decorations 7952 * such as the status bar and inset its content; that is, controlling whether 7953 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7954 * executed. See that method for more details. 7955 * 7956 * <p>Note that if you are providing your own implementation of 7957 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7958 * flag to true -- your implementation will be overriding the default 7959 * implementation that checks this flag. 7960 * 7961 * @param fitSystemWindows If true, then the default implementation of 7962 * {@link #fitSystemWindows(Rect)} will be executed. 7963 * 7964 * @attr ref android.R.styleable#View_fitsSystemWindows 7965 * @see #getFitsSystemWindows() 7966 * @see #fitSystemWindows(Rect) 7967 * @see #setSystemUiVisibility(int) 7968 */ 7969 public void setFitsSystemWindows(boolean fitSystemWindows) { 7970 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7971 } 7972 7973 /** 7974 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7975 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7976 * will be executed. 7977 * 7978 * @return {@code true} if the default implementation of 7979 * {@link #fitSystemWindows(Rect)} will be executed. 7980 * 7981 * @attr ref android.R.styleable#View_fitsSystemWindows 7982 * @see #setFitsSystemWindows(boolean) 7983 * @see #fitSystemWindows(Rect) 7984 * @see #setSystemUiVisibility(int) 7985 */ 7986 @ViewDebug.ExportedProperty 7987 public boolean getFitsSystemWindows() { 7988 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7989 } 7990 7991 /** @hide */ 7992 public boolean fitsSystemWindows() { 7993 return getFitsSystemWindows(); 7994 } 7995 7996 /** 7997 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7998 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7999 */ 8000 @Deprecated 8001 public void requestFitSystemWindows() { 8002 if (mParent != null) { 8003 mParent.requestFitSystemWindows(); 8004 } 8005 } 8006 8007 /** 8008 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 8009 */ 8010 public void requestApplyInsets() { 8011 requestFitSystemWindows(); 8012 } 8013 8014 /** 8015 * For use by PhoneWindow to make its own system window fitting optional. 8016 * @hide 8017 */ 8018 public void makeOptionalFitsSystemWindows() { 8019 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 8020 } 8021 8022 /** 8023 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 8024 * treat them as such. 8025 * @hide 8026 */ 8027 public void getOutsets(Rect outOutsetRect) { 8028 if (mAttachInfo != null) { 8029 outOutsetRect.set(mAttachInfo.mOutsets); 8030 } else { 8031 outOutsetRect.setEmpty(); 8032 } 8033 } 8034 8035 /** 8036 * Returns the visibility status for this view. 8037 * 8038 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8039 * @attr ref android.R.styleable#View_visibility 8040 */ 8041 @ViewDebug.ExportedProperty(mapping = { 8042 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 8043 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 8044 @ViewDebug.IntToString(from = GONE, to = "GONE") 8045 }) 8046 @Visibility 8047 public int getVisibility() { 8048 return mViewFlags & VISIBILITY_MASK; 8049 } 8050 8051 /** 8052 * Set the visibility state of this view. 8053 * 8054 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8055 * @attr ref android.R.styleable#View_visibility 8056 */ 8057 @RemotableViewMethod 8058 public void setVisibility(@Visibility int visibility) { 8059 setFlags(visibility, VISIBILITY_MASK); 8060 } 8061 8062 /** 8063 * Returns the enabled status for this view. The interpretation of the 8064 * enabled state varies by subclass. 8065 * 8066 * @return True if this view is enabled, false otherwise. 8067 */ 8068 @ViewDebug.ExportedProperty 8069 public boolean isEnabled() { 8070 return (mViewFlags & ENABLED_MASK) == ENABLED; 8071 } 8072 8073 /** 8074 * Set the enabled state of this view. The interpretation of the enabled 8075 * state varies by subclass. 8076 * 8077 * @param enabled True if this view is enabled, false otherwise. 8078 */ 8079 @RemotableViewMethod 8080 public void setEnabled(boolean enabled) { 8081 if (enabled == isEnabled()) return; 8082 8083 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8084 8085 /* 8086 * The View most likely has to change its appearance, so refresh 8087 * the drawable state. 8088 */ 8089 refreshDrawableState(); 8090 8091 // Invalidate too, since the default behavior for views is to be 8092 // be drawn at 50% alpha rather than to change the drawable. 8093 invalidate(true); 8094 8095 if (!enabled) { 8096 cancelPendingInputEvents(); 8097 } 8098 } 8099 8100 /** 8101 * Set whether this view can receive the focus. 8102 * 8103 * Setting this to false will also ensure that this view is not focusable 8104 * in touch mode. 8105 * 8106 * @param focusable If true, this view can receive the focus. 8107 * 8108 * @see #setFocusableInTouchMode(boolean) 8109 * @attr ref android.R.styleable#View_focusable 8110 */ 8111 public void setFocusable(boolean focusable) { 8112 if (!focusable) { 8113 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8114 } 8115 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8116 } 8117 8118 /** 8119 * Set whether this view can receive focus while in touch mode. 8120 * 8121 * Setting this to true will also ensure that this view is focusable. 8122 * 8123 * @param focusableInTouchMode If true, this view can receive the focus while 8124 * in touch mode. 8125 * 8126 * @see #setFocusable(boolean) 8127 * @attr ref android.R.styleable#View_focusableInTouchMode 8128 */ 8129 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8130 // Focusable in touch mode should always be set before the focusable flag 8131 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8132 // which, in touch mode, will not successfully request focus on this view 8133 // because the focusable in touch mode flag is not set 8134 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8135 if (focusableInTouchMode) { 8136 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8137 } 8138 } 8139 8140 /** 8141 * Set whether this view should have sound effects enabled for events such as 8142 * clicking and touching. 8143 * 8144 * <p>You may wish to disable sound effects for a view if you already play sounds, 8145 * for instance, a dial key that plays dtmf tones. 8146 * 8147 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8148 * @see #isSoundEffectsEnabled() 8149 * @see #playSoundEffect(int) 8150 * @attr ref android.R.styleable#View_soundEffectsEnabled 8151 */ 8152 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8153 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8154 } 8155 8156 /** 8157 * @return whether this view should have sound effects enabled for events such as 8158 * clicking and touching. 8159 * 8160 * @see #setSoundEffectsEnabled(boolean) 8161 * @see #playSoundEffect(int) 8162 * @attr ref android.R.styleable#View_soundEffectsEnabled 8163 */ 8164 @ViewDebug.ExportedProperty 8165 public boolean isSoundEffectsEnabled() { 8166 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8167 } 8168 8169 /** 8170 * Set whether this view should have haptic feedback for events such as 8171 * long presses. 8172 * 8173 * <p>You may wish to disable haptic feedback if your view already controls 8174 * its own haptic feedback. 8175 * 8176 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8177 * @see #isHapticFeedbackEnabled() 8178 * @see #performHapticFeedback(int) 8179 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8180 */ 8181 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8182 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8183 } 8184 8185 /** 8186 * @return whether this view should have haptic feedback enabled for events 8187 * long presses. 8188 * 8189 * @see #setHapticFeedbackEnabled(boolean) 8190 * @see #performHapticFeedback(int) 8191 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8192 */ 8193 @ViewDebug.ExportedProperty 8194 public boolean isHapticFeedbackEnabled() { 8195 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8196 } 8197 8198 /** 8199 * Returns the layout direction for this view. 8200 * 8201 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8202 * {@link #LAYOUT_DIRECTION_RTL}, 8203 * {@link #LAYOUT_DIRECTION_INHERIT} or 8204 * {@link #LAYOUT_DIRECTION_LOCALE}. 8205 * 8206 * @attr ref android.R.styleable#View_layoutDirection 8207 * 8208 * @hide 8209 */ 8210 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8211 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8212 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8213 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8214 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8215 }) 8216 @LayoutDir 8217 public int getRawLayoutDirection() { 8218 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8219 } 8220 8221 /** 8222 * Set the layout direction for this view. This will propagate a reset of layout direction 8223 * resolution to the view's children and resolve layout direction for this view. 8224 * 8225 * @param layoutDirection the layout direction to set. Should be one of: 8226 * 8227 * {@link #LAYOUT_DIRECTION_LTR}, 8228 * {@link #LAYOUT_DIRECTION_RTL}, 8229 * {@link #LAYOUT_DIRECTION_INHERIT}, 8230 * {@link #LAYOUT_DIRECTION_LOCALE}. 8231 * 8232 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8233 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8234 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8235 * 8236 * @attr ref android.R.styleable#View_layoutDirection 8237 */ 8238 @RemotableViewMethod 8239 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8240 if (getRawLayoutDirection() != layoutDirection) { 8241 // Reset the current layout direction and the resolved one 8242 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8243 resetRtlProperties(); 8244 // Set the new layout direction (filtered) 8245 mPrivateFlags2 |= 8246 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8247 // We need to resolve all RTL properties as they all depend on layout direction 8248 resolveRtlPropertiesIfNeeded(); 8249 requestLayout(); 8250 invalidate(true); 8251 } 8252 } 8253 8254 /** 8255 * Returns the resolved layout direction for this view. 8256 * 8257 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8258 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8259 * 8260 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8261 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8262 * 8263 * @attr ref android.R.styleable#View_layoutDirection 8264 */ 8265 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8266 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8267 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8268 }) 8269 @ResolvedLayoutDir 8270 public int getLayoutDirection() { 8271 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8272 if (targetSdkVersion < JELLY_BEAN_MR1) { 8273 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8274 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8275 } 8276 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8277 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8278 } 8279 8280 /** 8281 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8282 * layout attribute and/or the inherited value from the parent 8283 * 8284 * @return true if the layout is right-to-left. 8285 * 8286 * @hide 8287 */ 8288 @ViewDebug.ExportedProperty(category = "layout") 8289 public boolean isLayoutRtl() { 8290 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8291 } 8292 8293 /** 8294 * Indicates whether the view is currently tracking transient state that the 8295 * app should not need to concern itself with saving and restoring, but that 8296 * the framework should take special note to preserve when possible. 8297 * 8298 * <p>A view with transient state cannot be trivially rebound from an external 8299 * data source, such as an adapter binding item views in a list. This may be 8300 * because the view is performing an animation, tracking user selection 8301 * of content, or similar.</p> 8302 * 8303 * @return true if the view has transient state 8304 */ 8305 @ViewDebug.ExportedProperty(category = "layout") 8306 public boolean hasTransientState() { 8307 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8308 } 8309 8310 /** 8311 * Set whether this view is currently tracking transient state that the 8312 * framework should attempt to preserve when possible. This flag is reference counted, 8313 * so every call to setHasTransientState(true) should be paired with a later call 8314 * to setHasTransientState(false). 8315 * 8316 * <p>A view with transient state cannot be trivially rebound from an external 8317 * data source, such as an adapter binding item views in a list. This may be 8318 * because the view is performing an animation, tracking user selection 8319 * of content, or similar.</p> 8320 * 8321 * @param hasTransientState true if this view has transient state 8322 */ 8323 public void setHasTransientState(boolean hasTransientState) { 8324 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8325 mTransientStateCount - 1; 8326 if (mTransientStateCount < 0) { 8327 mTransientStateCount = 0; 8328 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8329 "unmatched pair of setHasTransientState calls"); 8330 } else if ((hasTransientState && mTransientStateCount == 1) || 8331 (!hasTransientState && mTransientStateCount == 0)) { 8332 // update flag if we've just incremented up from 0 or decremented down to 0 8333 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8334 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8335 if (mParent != null) { 8336 try { 8337 mParent.childHasTransientStateChanged(this, hasTransientState); 8338 } catch (AbstractMethodError e) { 8339 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8340 " does not fully implement ViewParent", e); 8341 } 8342 } 8343 } 8344 } 8345 8346 /** 8347 * Returns true if this view is currently attached to a window. 8348 */ 8349 public boolean isAttachedToWindow() { 8350 return mAttachInfo != null; 8351 } 8352 8353 /** 8354 * Returns true if this view has been through at least one layout since it 8355 * was last attached to or detached from a window. 8356 */ 8357 public boolean isLaidOut() { 8358 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8359 } 8360 8361 /** 8362 * If this view doesn't do any drawing on its own, set this flag to 8363 * allow further optimizations. By default, this flag is not set on 8364 * View, but could be set on some View subclasses such as ViewGroup. 8365 * 8366 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8367 * you should clear this flag. 8368 * 8369 * @param willNotDraw whether or not this View draw on its own 8370 */ 8371 public void setWillNotDraw(boolean willNotDraw) { 8372 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8373 } 8374 8375 /** 8376 * Returns whether or not this View draws on its own. 8377 * 8378 * @return true if this view has nothing to draw, false otherwise 8379 */ 8380 @ViewDebug.ExportedProperty(category = "drawing") 8381 public boolean willNotDraw() { 8382 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8383 } 8384 8385 /** 8386 * When a View's drawing cache is enabled, drawing is redirected to an 8387 * offscreen bitmap. Some views, like an ImageView, must be able to 8388 * bypass this mechanism if they already draw a single bitmap, to avoid 8389 * unnecessary usage of the memory. 8390 * 8391 * @param willNotCacheDrawing true if this view does not cache its 8392 * drawing, false otherwise 8393 */ 8394 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8395 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8396 } 8397 8398 /** 8399 * Returns whether or not this View can cache its drawing or not. 8400 * 8401 * @return true if this view does not cache its drawing, false otherwise 8402 */ 8403 @ViewDebug.ExportedProperty(category = "drawing") 8404 public boolean willNotCacheDrawing() { 8405 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8406 } 8407 8408 /** 8409 * Indicates whether this view reacts to click events or not. 8410 * 8411 * @return true if the view is clickable, false otherwise 8412 * 8413 * @see #setClickable(boolean) 8414 * @attr ref android.R.styleable#View_clickable 8415 */ 8416 @ViewDebug.ExportedProperty 8417 public boolean isClickable() { 8418 return (mViewFlags & CLICKABLE) == CLICKABLE; 8419 } 8420 8421 /** 8422 * Enables or disables click events for this view. When a view 8423 * is clickable it will change its state to "pressed" on every click. 8424 * Subclasses should set the view clickable to visually react to 8425 * user's clicks. 8426 * 8427 * @param clickable true to make the view clickable, false otherwise 8428 * 8429 * @see #isClickable() 8430 * @attr ref android.R.styleable#View_clickable 8431 */ 8432 public void setClickable(boolean clickable) { 8433 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8434 } 8435 8436 /** 8437 * Indicates whether this view reacts to long click events or not. 8438 * 8439 * @return true if the view is long clickable, false otherwise 8440 * 8441 * @see #setLongClickable(boolean) 8442 * @attr ref android.R.styleable#View_longClickable 8443 */ 8444 public boolean isLongClickable() { 8445 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8446 } 8447 8448 /** 8449 * Enables or disables long click events for this view. When a view is long 8450 * clickable it reacts to the user holding down the button for a longer 8451 * duration than a tap. This event can either launch the listener or a 8452 * context menu. 8453 * 8454 * @param longClickable true to make the view long clickable, false otherwise 8455 * @see #isLongClickable() 8456 * @attr ref android.R.styleable#View_longClickable 8457 */ 8458 public void setLongClickable(boolean longClickable) { 8459 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8460 } 8461 8462 /** 8463 * Indicates whether this view reacts to context clicks or not. 8464 * 8465 * @return true if the view is context clickable, false otherwise 8466 * @see #setContextClickable(boolean) 8467 * @attr ref android.R.styleable#View_contextClickable 8468 */ 8469 public boolean isContextClickable() { 8470 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8471 } 8472 8473 /** 8474 * Enables or disables context clicking for this view. This event can launch the listener. 8475 * 8476 * @param contextClickable true to make the view react to a context click, false otherwise 8477 * @see #isContextClickable() 8478 * @attr ref android.R.styleable#View_contextClickable 8479 */ 8480 public void setContextClickable(boolean contextClickable) { 8481 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8482 } 8483 8484 /** 8485 * Sets the pressed state for this view and provides a touch coordinate for 8486 * animation hinting. 8487 * 8488 * @param pressed Pass true to set the View's internal state to "pressed", 8489 * or false to reverts the View's internal state from a 8490 * previously set "pressed" state. 8491 * @param x The x coordinate of the touch that caused the press 8492 * @param y The y coordinate of the touch that caused the press 8493 */ 8494 private void setPressed(boolean pressed, float x, float y) { 8495 if (pressed) { 8496 drawableHotspotChanged(x, y); 8497 } 8498 8499 setPressed(pressed); 8500 } 8501 8502 /** 8503 * Sets the pressed state for this view. 8504 * 8505 * @see #isClickable() 8506 * @see #setClickable(boolean) 8507 * 8508 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8509 * the View's internal state from a previously set "pressed" state. 8510 */ 8511 public void setPressed(boolean pressed) { 8512 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8513 8514 if (pressed) { 8515 mPrivateFlags |= PFLAG_PRESSED; 8516 } else { 8517 mPrivateFlags &= ~PFLAG_PRESSED; 8518 } 8519 8520 if (needsRefresh) { 8521 refreshDrawableState(); 8522 } 8523 dispatchSetPressed(pressed); 8524 } 8525 8526 /** 8527 * Dispatch setPressed to all of this View's children. 8528 * 8529 * @see #setPressed(boolean) 8530 * 8531 * @param pressed The new pressed state 8532 */ 8533 protected void dispatchSetPressed(boolean pressed) { 8534 } 8535 8536 /** 8537 * Indicates whether the view is currently in pressed state. Unless 8538 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8539 * the pressed state. 8540 * 8541 * @see #setPressed(boolean) 8542 * @see #isClickable() 8543 * @see #setClickable(boolean) 8544 * 8545 * @return true if the view is currently pressed, false otherwise 8546 */ 8547 @ViewDebug.ExportedProperty 8548 public boolean isPressed() { 8549 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8550 } 8551 8552 /** 8553 * @hide 8554 * Indicates whether this view will participate in data collection through 8555 * {@link ViewStructure}. If true, it will not provide any data 8556 * for itself or its children. If false, the normal data collection will be allowed. 8557 * 8558 * @return Returns false if assist data collection is not blocked, else true. 8559 * 8560 * @see #setAssistBlocked(boolean) 8561 * @attr ref android.R.styleable#View_assistBlocked 8562 */ 8563 public boolean isAssistBlocked() { 8564 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8565 } 8566 8567 /** 8568 * @hide 8569 * Controls whether assist data collection from this view and its children is enabled 8570 * (that is, whether {@link #onProvideStructure} and 8571 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8572 * allowing normal assist collection. Setting this to false will disable assist collection. 8573 * 8574 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8575 * (the default) to allow it. 8576 * 8577 * @see #isAssistBlocked() 8578 * @see #onProvideStructure 8579 * @see #onProvideVirtualStructure 8580 * @attr ref android.R.styleable#View_assistBlocked 8581 */ 8582 public void setAssistBlocked(boolean enabled) { 8583 if (enabled) { 8584 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8585 } else { 8586 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8587 } 8588 } 8589 8590 /** 8591 * Indicates whether this view will save its state (that is, 8592 * whether its {@link #onSaveInstanceState} method will be called). 8593 * 8594 * @return Returns true if the view state saving is enabled, else false. 8595 * 8596 * @see #setSaveEnabled(boolean) 8597 * @attr ref android.R.styleable#View_saveEnabled 8598 */ 8599 public boolean isSaveEnabled() { 8600 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8601 } 8602 8603 /** 8604 * Controls whether the saving of this view's state is 8605 * enabled (that is, whether its {@link #onSaveInstanceState} method 8606 * will be called). Note that even if freezing is enabled, the 8607 * view still must have an id assigned to it (via {@link #setId(int)}) 8608 * for its state to be saved. This flag can only disable the 8609 * saving of this view; any child views may still have their state saved. 8610 * 8611 * @param enabled Set to false to <em>disable</em> state saving, or true 8612 * (the default) to allow it. 8613 * 8614 * @see #isSaveEnabled() 8615 * @see #setId(int) 8616 * @see #onSaveInstanceState() 8617 * @attr ref android.R.styleable#View_saveEnabled 8618 */ 8619 public void setSaveEnabled(boolean enabled) { 8620 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8621 } 8622 8623 /** 8624 * Gets whether the framework should discard touches when the view's 8625 * window is obscured by another visible window. 8626 * Refer to the {@link View} security documentation for more details. 8627 * 8628 * @return True if touch filtering is enabled. 8629 * 8630 * @see #setFilterTouchesWhenObscured(boolean) 8631 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8632 */ 8633 @ViewDebug.ExportedProperty 8634 public boolean getFilterTouchesWhenObscured() { 8635 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8636 } 8637 8638 /** 8639 * Sets whether the framework should discard touches when the view's 8640 * window is obscured by another visible window. 8641 * Refer to the {@link View} security documentation for more details. 8642 * 8643 * @param enabled True if touch filtering should be enabled. 8644 * 8645 * @see #getFilterTouchesWhenObscured 8646 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8647 */ 8648 public void setFilterTouchesWhenObscured(boolean enabled) { 8649 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8650 FILTER_TOUCHES_WHEN_OBSCURED); 8651 } 8652 8653 /** 8654 * Indicates whether the entire hierarchy under this view will save its 8655 * state when a state saving traversal occurs from its parent. The default 8656 * is true; if false, these views will not be saved unless 8657 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8658 * 8659 * @return Returns true if the view state saving from parent is enabled, else false. 8660 * 8661 * @see #setSaveFromParentEnabled(boolean) 8662 */ 8663 public boolean isSaveFromParentEnabled() { 8664 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8665 } 8666 8667 /** 8668 * Controls whether the entire hierarchy under this view will save its 8669 * state when a state saving traversal occurs from its parent. The default 8670 * is true; if false, these views will not be saved unless 8671 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8672 * 8673 * @param enabled Set to false to <em>disable</em> state saving, or true 8674 * (the default) to allow it. 8675 * 8676 * @see #isSaveFromParentEnabled() 8677 * @see #setId(int) 8678 * @see #onSaveInstanceState() 8679 */ 8680 public void setSaveFromParentEnabled(boolean enabled) { 8681 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8682 } 8683 8684 8685 /** 8686 * Returns whether this View is able to take focus. 8687 * 8688 * @return True if this view can take focus, or false otherwise. 8689 * @attr ref android.R.styleable#View_focusable 8690 */ 8691 @ViewDebug.ExportedProperty(category = "focus") 8692 public final boolean isFocusable() { 8693 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8694 } 8695 8696 /** 8697 * When a view is focusable, it may not want to take focus when in touch mode. 8698 * For example, a button would like focus when the user is navigating via a D-pad 8699 * so that the user can click on it, but once the user starts touching the screen, 8700 * the button shouldn't take focus 8701 * @return Whether the view is focusable in touch mode. 8702 * @attr ref android.R.styleable#View_focusableInTouchMode 8703 */ 8704 @ViewDebug.ExportedProperty 8705 public final boolean isFocusableInTouchMode() { 8706 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8707 } 8708 8709 /** 8710 * Find the nearest view in the specified direction that can take focus. 8711 * This does not actually give focus to that view. 8712 * 8713 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8714 * 8715 * @return The nearest focusable in the specified direction, or null if none 8716 * can be found. 8717 */ 8718 public View focusSearch(@FocusRealDirection int direction) { 8719 if (mParent != null) { 8720 return mParent.focusSearch(this, direction); 8721 } else { 8722 return null; 8723 } 8724 } 8725 8726 /** 8727 * This method is the last chance for the focused view and its ancestors to 8728 * respond to an arrow key. This is called when the focused view did not 8729 * consume the key internally, nor could the view system find a new view in 8730 * the requested direction to give focus to. 8731 * 8732 * @param focused The currently focused view. 8733 * @param direction The direction focus wants to move. One of FOCUS_UP, 8734 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8735 * @return True if the this view consumed this unhandled move. 8736 */ 8737 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8738 return false; 8739 } 8740 8741 /** 8742 * If a user manually specified the next view id for a particular direction, 8743 * use the root to look up the view. 8744 * @param root The root view of the hierarchy containing this view. 8745 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8746 * or FOCUS_BACKWARD. 8747 * @return The user specified next view, or null if there is none. 8748 */ 8749 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8750 switch (direction) { 8751 case FOCUS_LEFT: 8752 if (mNextFocusLeftId == View.NO_ID) return null; 8753 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8754 case FOCUS_RIGHT: 8755 if (mNextFocusRightId == View.NO_ID) return null; 8756 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8757 case FOCUS_UP: 8758 if (mNextFocusUpId == View.NO_ID) return null; 8759 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8760 case FOCUS_DOWN: 8761 if (mNextFocusDownId == View.NO_ID) return null; 8762 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8763 case FOCUS_FORWARD: 8764 if (mNextFocusForwardId == View.NO_ID) return null; 8765 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8766 case FOCUS_BACKWARD: { 8767 if (mID == View.NO_ID) return null; 8768 final int id = mID; 8769 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8770 @Override 8771 public boolean apply(View t) { 8772 return t.mNextFocusForwardId == id; 8773 } 8774 }); 8775 } 8776 } 8777 return null; 8778 } 8779 8780 private View findViewInsideOutShouldExist(View root, int id) { 8781 if (mMatchIdPredicate == null) { 8782 mMatchIdPredicate = new MatchIdPredicate(); 8783 } 8784 mMatchIdPredicate.mId = id; 8785 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8786 if (result == null) { 8787 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8788 } 8789 return result; 8790 } 8791 8792 /** 8793 * Find and return all focusable views that are descendants of this view, 8794 * possibly including this view if it is focusable itself. 8795 * 8796 * @param direction The direction of the focus 8797 * @return A list of focusable views 8798 */ 8799 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8800 ArrayList<View> result = new ArrayList<View>(24); 8801 addFocusables(result, direction); 8802 return result; 8803 } 8804 8805 /** 8806 * Add any focusable views that are descendants of this view (possibly 8807 * including this view if it is focusable itself) to views. If we are in touch mode, 8808 * only add views that are also focusable in touch mode. 8809 * 8810 * @param views Focusable views found so far 8811 * @param direction The direction of the focus 8812 */ 8813 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8814 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 8815 } 8816 8817 /** 8818 * Adds any focusable views that are descendants of this view (possibly 8819 * including this view if it is focusable itself) to views. This method 8820 * adds all focusable views regardless if we are in touch mode or 8821 * only views focusable in touch mode if we are in touch mode or 8822 * only views that can take accessibility focus if accessibility is enabled 8823 * depending on the focusable mode parameter. 8824 * 8825 * @param views Focusable views found so far or null if all we are interested is 8826 * the number of focusables. 8827 * @param direction The direction of the focus. 8828 * @param focusableMode The type of focusables to be added. 8829 * 8830 * @see #FOCUSABLES_ALL 8831 * @see #FOCUSABLES_TOUCH_MODE 8832 */ 8833 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8834 @FocusableMode int focusableMode) { 8835 if (views == null) { 8836 return; 8837 } 8838 if (!isFocusable()) { 8839 return; 8840 } 8841 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8842 && !isFocusableInTouchMode()) { 8843 return; 8844 } 8845 views.add(this); 8846 } 8847 8848 /** 8849 * Finds the Views that contain given text. The containment is case insensitive. 8850 * The search is performed by either the text that the View renders or the content 8851 * description that describes the view for accessibility purposes and the view does 8852 * not render or both. Clients can specify how the search is to be performed via 8853 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8854 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8855 * 8856 * @param outViews The output list of matching Views. 8857 * @param searched The text to match against. 8858 * 8859 * @see #FIND_VIEWS_WITH_TEXT 8860 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8861 * @see #setContentDescription(CharSequence) 8862 */ 8863 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8864 @FindViewFlags int flags) { 8865 if (getAccessibilityNodeProvider() != null) { 8866 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8867 outViews.add(this); 8868 } 8869 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8870 && (searched != null && searched.length() > 0) 8871 && (mContentDescription != null && mContentDescription.length() > 0)) { 8872 String searchedLowerCase = searched.toString().toLowerCase(); 8873 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8874 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8875 outViews.add(this); 8876 } 8877 } 8878 } 8879 8880 /** 8881 * Find and return all touchable views that are descendants of this view, 8882 * possibly including this view if it is touchable itself. 8883 * 8884 * @return A list of touchable views 8885 */ 8886 public ArrayList<View> getTouchables() { 8887 ArrayList<View> result = new ArrayList<View>(); 8888 addTouchables(result); 8889 return result; 8890 } 8891 8892 /** 8893 * Add any touchable views that are descendants of this view (possibly 8894 * including this view if it is touchable itself) to views. 8895 * 8896 * @param views Touchable views found so far 8897 */ 8898 public void addTouchables(ArrayList<View> views) { 8899 final int viewFlags = mViewFlags; 8900 8901 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8902 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8903 && (viewFlags & ENABLED_MASK) == ENABLED) { 8904 views.add(this); 8905 } 8906 } 8907 8908 /** 8909 * Returns whether this View is accessibility focused. 8910 * 8911 * @return True if this View is accessibility focused. 8912 */ 8913 public boolean isAccessibilityFocused() { 8914 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8915 } 8916 8917 /** 8918 * Call this to try to give accessibility focus to this view. 8919 * 8920 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8921 * returns false or the view is no visible or the view already has accessibility 8922 * focus. 8923 * 8924 * See also {@link #focusSearch(int)}, which is what you call to say that you 8925 * have focus, and you want your parent to look for the next one. 8926 * 8927 * @return Whether this view actually took accessibility focus. 8928 * 8929 * @hide 8930 */ 8931 public boolean requestAccessibilityFocus() { 8932 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8933 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8934 return false; 8935 } 8936 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8937 return false; 8938 } 8939 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8940 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8941 ViewRootImpl viewRootImpl = getViewRootImpl(); 8942 if (viewRootImpl != null) { 8943 viewRootImpl.setAccessibilityFocus(this, null); 8944 } 8945 invalidate(); 8946 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8947 return true; 8948 } 8949 return false; 8950 } 8951 8952 /** 8953 * Call this to try to clear accessibility focus of this view. 8954 * 8955 * See also {@link #focusSearch(int)}, which is what you call to say that you 8956 * have focus, and you want your parent to look for the next one. 8957 * 8958 * @hide 8959 */ 8960 public void clearAccessibilityFocus() { 8961 clearAccessibilityFocusNoCallbacks(0); 8962 8963 // Clear the global reference of accessibility focus if this view or 8964 // any of its descendants had accessibility focus. This will NOT send 8965 // an event or update internal state if focus is cleared from a 8966 // descendant view, which may leave views in inconsistent states. 8967 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8968 if (viewRootImpl != null) { 8969 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8970 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8971 viewRootImpl.setAccessibilityFocus(null, null); 8972 } 8973 } 8974 } 8975 8976 private void sendAccessibilityHoverEvent(int eventType) { 8977 // Since we are not delivering to a client accessibility events from not 8978 // important views (unless the clinet request that) we need to fire the 8979 // event from the deepest view exposed to the client. As a consequence if 8980 // the user crosses a not exposed view the client will see enter and exit 8981 // of the exposed predecessor followed by and enter and exit of that same 8982 // predecessor when entering and exiting the not exposed descendant. This 8983 // is fine since the client has a clear idea which view is hovered at the 8984 // price of a couple more events being sent. This is a simple and 8985 // working solution. 8986 View source = this; 8987 while (true) { 8988 if (source.includeForAccessibility()) { 8989 source.sendAccessibilityEvent(eventType); 8990 return; 8991 } 8992 ViewParent parent = source.getParent(); 8993 if (parent instanceof View) { 8994 source = (View) parent; 8995 } else { 8996 return; 8997 } 8998 } 8999 } 9000 9001 /** 9002 * Clears accessibility focus without calling any callback methods 9003 * normally invoked in {@link #clearAccessibilityFocus()}. This method 9004 * is used separately from that one for clearing accessibility focus when 9005 * giving this focus to another view. 9006 * 9007 * @param action The action, if any, that led to focus being cleared. Set to 9008 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 9009 * the window. 9010 */ 9011 void clearAccessibilityFocusNoCallbacks(int action) { 9012 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 9013 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 9014 invalidate(); 9015 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9016 AccessibilityEvent event = AccessibilityEvent.obtain( 9017 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 9018 event.setAction(action); 9019 if (mAccessibilityDelegate != null) { 9020 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 9021 } else { 9022 sendAccessibilityEventUnchecked(event); 9023 } 9024 } 9025 } 9026 } 9027 9028 /** 9029 * Call this to try to give focus to a specific view or to one of its 9030 * descendants. 9031 * 9032 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9033 * false), or if it is focusable and it is not focusable in touch mode 9034 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9035 * 9036 * See also {@link #focusSearch(int)}, which is what you call to say that you 9037 * have focus, and you want your parent to look for the next one. 9038 * 9039 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 9040 * {@link #FOCUS_DOWN} and <code>null</code>. 9041 * 9042 * @return Whether this view or one of its descendants actually took focus. 9043 */ 9044 public final boolean requestFocus() { 9045 return requestFocus(View.FOCUS_DOWN); 9046 } 9047 9048 /** 9049 * Call this to try to give focus to a specific view or to one of its 9050 * descendants and give it a hint about what direction focus is heading. 9051 * 9052 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9053 * false), or if it is focusable and it is not focusable in touch mode 9054 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9055 * 9056 * See also {@link #focusSearch(int)}, which is what you call to say that you 9057 * have focus, and you want your parent to look for the next one. 9058 * 9059 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 9060 * <code>null</code> set for the previously focused rectangle. 9061 * 9062 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9063 * @return Whether this view or one of its descendants actually took focus. 9064 */ 9065 public final boolean requestFocus(int direction) { 9066 return requestFocus(direction, null); 9067 } 9068 9069 /** 9070 * Call this to try to give focus to a specific view or to one of its descendants 9071 * and give it hints about the direction and a specific rectangle that the focus 9072 * is coming from. The rectangle can help give larger views a finer grained hint 9073 * about where focus is coming from, and therefore, where to show selection, or 9074 * forward focus change internally. 9075 * 9076 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9077 * false), or if it is focusable and it is not focusable in touch mode 9078 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9079 * 9080 * A View will not take focus if it is not visible. 9081 * 9082 * A View will not take focus if one of its parents has 9083 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9084 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9085 * 9086 * See also {@link #focusSearch(int)}, which is what you call to say that you 9087 * have focus, and you want your parent to look for the next one. 9088 * 9089 * You may wish to override this method if your custom {@link View} has an internal 9090 * {@link View} that it wishes to forward the request to. 9091 * 9092 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9093 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9094 * to give a finer grained hint about where focus is coming from. May be null 9095 * if there is no hint. 9096 * @return Whether this view or one of its descendants actually took focus. 9097 */ 9098 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9099 return requestFocusNoSearch(direction, previouslyFocusedRect); 9100 } 9101 9102 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9103 // need to be focusable 9104 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9105 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9106 return false; 9107 } 9108 9109 // need to be focusable in touch mode if in touch mode 9110 if (isInTouchMode() && 9111 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9112 return false; 9113 } 9114 9115 // need to not have any parents blocking us 9116 if (hasAncestorThatBlocksDescendantFocus()) { 9117 return false; 9118 } 9119 9120 handleFocusGainInternal(direction, previouslyFocusedRect); 9121 return true; 9122 } 9123 9124 /** 9125 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9126 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9127 * touch mode to request focus when they are touched. 9128 * 9129 * @return Whether this view or one of its descendants actually took focus. 9130 * 9131 * @see #isInTouchMode() 9132 * 9133 */ 9134 public final boolean requestFocusFromTouch() { 9135 // Leave touch mode if we need to 9136 if (isInTouchMode()) { 9137 ViewRootImpl viewRoot = getViewRootImpl(); 9138 if (viewRoot != null) { 9139 viewRoot.ensureTouchMode(false); 9140 } 9141 } 9142 return requestFocus(View.FOCUS_DOWN); 9143 } 9144 9145 /** 9146 * @return Whether any ancestor of this view blocks descendant focus. 9147 */ 9148 private boolean hasAncestorThatBlocksDescendantFocus() { 9149 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9150 ViewParent ancestor = mParent; 9151 while (ancestor instanceof ViewGroup) { 9152 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9153 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9154 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9155 return true; 9156 } else { 9157 ancestor = vgAncestor.getParent(); 9158 } 9159 } 9160 return false; 9161 } 9162 9163 /** 9164 * Gets the mode for determining whether this View is important for accessibility. 9165 * A view is important for accessibility if it fires accessibility events and if it 9166 * is reported to accessibility services that query the screen. 9167 * 9168 * @return The mode for determining whether a view is important for accessibility, one 9169 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 9170 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 9171 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 9172 * 9173 * @attr ref android.R.styleable#View_importantForAccessibility 9174 * 9175 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9176 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9177 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9178 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9179 */ 9180 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9181 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9182 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9183 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9184 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9185 to = "noHideDescendants") 9186 }) 9187 public int getImportantForAccessibility() { 9188 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9189 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9190 } 9191 9192 /** 9193 * Sets the live region mode for this view. This indicates to accessibility 9194 * services whether they should automatically notify the user about changes 9195 * to the view's content description or text, or to the content descriptions 9196 * or text of the view's children (where applicable). 9197 * <p> 9198 * For example, in a login screen with a TextView that displays an "incorrect 9199 * password" notification, that view should be marked as a live region with 9200 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9201 * <p> 9202 * To disable change notifications for this view, use 9203 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9204 * mode for most views. 9205 * <p> 9206 * To indicate that the user should be notified of changes, use 9207 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9208 * <p> 9209 * If the view's changes should interrupt ongoing speech and notify the user 9210 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9211 * 9212 * @param mode The live region mode for this view, one of: 9213 * <ul> 9214 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9215 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9216 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9217 * </ul> 9218 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9219 */ 9220 public void setAccessibilityLiveRegion(int mode) { 9221 if (mode != getAccessibilityLiveRegion()) { 9222 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9223 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9224 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9225 notifyViewAccessibilityStateChangedIfNeeded( 9226 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9227 } 9228 } 9229 9230 /** 9231 * Gets the live region mode for this View. 9232 * 9233 * @return The live region mode for the view. 9234 * 9235 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9236 * 9237 * @see #setAccessibilityLiveRegion(int) 9238 */ 9239 public int getAccessibilityLiveRegion() { 9240 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9241 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9242 } 9243 9244 /** 9245 * Sets how to determine whether this view is important for accessibility 9246 * which is if it fires accessibility events and if it is reported to 9247 * accessibility services that query the screen. 9248 * 9249 * @param mode How to determine whether this view is important for accessibility. 9250 * 9251 * @attr ref android.R.styleable#View_importantForAccessibility 9252 * 9253 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9254 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9255 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9256 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9257 */ 9258 public void setImportantForAccessibility(int mode) { 9259 final int oldMode = getImportantForAccessibility(); 9260 if (mode != oldMode) { 9261 final boolean hideDescendants = 9262 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9263 9264 // If this node or its descendants are no longer important, try to 9265 // clear accessibility focus. 9266 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9267 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9268 if (focusHost != null) { 9269 focusHost.clearAccessibilityFocus(); 9270 } 9271 } 9272 9273 // If we're moving between AUTO and another state, we might not need 9274 // to send a subtree changed notification. We'll store the computed 9275 // importance, since we'll need to check it later to make sure. 9276 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9277 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9278 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9279 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9280 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9281 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9282 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9283 notifySubtreeAccessibilityStateChangedIfNeeded(); 9284 } else { 9285 notifyViewAccessibilityStateChangedIfNeeded( 9286 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9287 } 9288 } 9289 } 9290 9291 /** 9292 * Returns the view within this view's hierarchy that is hosting 9293 * accessibility focus. 9294 * 9295 * @param searchDescendants whether to search for focus in descendant views 9296 * @return the view hosting accessibility focus, or {@code null} 9297 */ 9298 private View findAccessibilityFocusHost(boolean searchDescendants) { 9299 if (isAccessibilityFocusedViewOrHost()) { 9300 return this; 9301 } 9302 9303 if (searchDescendants) { 9304 final ViewRootImpl viewRoot = getViewRootImpl(); 9305 if (viewRoot != null) { 9306 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9307 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9308 return focusHost; 9309 } 9310 } 9311 } 9312 9313 return null; 9314 } 9315 9316 /** 9317 * Computes whether this view should be exposed for accessibility. In 9318 * general, views that are interactive or provide information are exposed 9319 * while views that serve only as containers are hidden. 9320 * <p> 9321 * If an ancestor of this view has importance 9322 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9323 * returns <code>false</code>. 9324 * <p> 9325 * Otherwise, the value is computed according to the view's 9326 * {@link #getImportantForAccessibility()} value: 9327 * <ol> 9328 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9329 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9330 * </code> 9331 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9332 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9333 * view satisfies any of the following: 9334 * <ul> 9335 * <li>Is actionable, e.g. {@link #isClickable()}, 9336 * {@link #isLongClickable()}, or {@link #isFocusable()} 9337 * <li>Has an {@link AccessibilityDelegate} 9338 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9339 * {@link OnKeyListener}, etc. 9340 * <li>Is an accessibility live region, e.g. 9341 * {@link #getAccessibilityLiveRegion()} is not 9342 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9343 * </ul> 9344 * </ol> 9345 * 9346 * @return Whether the view is exposed for accessibility. 9347 * @see #setImportantForAccessibility(int) 9348 * @see #getImportantForAccessibility() 9349 */ 9350 public boolean isImportantForAccessibility() { 9351 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9352 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9353 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9354 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9355 return false; 9356 } 9357 9358 // Check parent mode to ensure we're not hidden. 9359 ViewParent parent = mParent; 9360 while (parent instanceof View) { 9361 if (((View) parent).getImportantForAccessibility() 9362 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9363 return false; 9364 } 9365 parent = parent.getParent(); 9366 } 9367 9368 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9369 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9370 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9371 } 9372 9373 /** 9374 * Gets the parent for accessibility purposes. Note that the parent for 9375 * accessibility is not necessary the immediate parent. It is the first 9376 * predecessor that is important for accessibility. 9377 * 9378 * @return The parent for accessibility purposes. 9379 */ 9380 public ViewParent getParentForAccessibility() { 9381 if (mParent instanceof View) { 9382 View parentView = (View) mParent; 9383 if (parentView.includeForAccessibility()) { 9384 return mParent; 9385 } else { 9386 return mParent.getParentForAccessibility(); 9387 } 9388 } 9389 return null; 9390 } 9391 9392 /** 9393 * Adds the children of this View relevant for accessibility to the given list 9394 * as output. Since some Views are not important for accessibility the added 9395 * child views are not necessarily direct children of this view, rather they are 9396 * the first level of descendants important for accessibility. 9397 * 9398 * @param outChildren The output list that will receive children for accessibility. 9399 */ 9400 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9401 9402 } 9403 9404 /** 9405 * Whether to regard this view for accessibility. A view is regarded for 9406 * accessibility if it is important for accessibility or the querying 9407 * accessibility service has explicitly requested that view not 9408 * important for accessibility are regarded. 9409 * 9410 * @return Whether to regard the view for accessibility. 9411 * 9412 * @hide 9413 */ 9414 public boolean includeForAccessibility() { 9415 if (mAttachInfo != null) { 9416 return (mAttachInfo.mAccessibilityFetchFlags 9417 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9418 || isImportantForAccessibility(); 9419 } 9420 return false; 9421 } 9422 9423 /** 9424 * Returns whether the View is considered actionable from 9425 * accessibility perspective. Such view are important for 9426 * accessibility. 9427 * 9428 * @return True if the view is actionable for accessibility. 9429 * 9430 * @hide 9431 */ 9432 public boolean isActionableForAccessibility() { 9433 return (isClickable() || isLongClickable() || isFocusable()); 9434 } 9435 9436 /** 9437 * Returns whether the View has registered callbacks which makes it 9438 * important for accessibility. 9439 * 9440 * @return True if the view is actionable for accessibility. 9441 */ 9442 private boolean hasListenersForAccessibility() { 9443 ListenerInfo info = getListenerInfo(); 9444 return mTouchDelegate != null || info.mOnKeyListener != null 9445 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9446 || info.mOnHoverListener != null || info.mOnDragListener != null; 9447 } 9448 9449 /** 9450 * Notifies that the accessibility state of this view changed. The change 9451 * is local to this view and does not represent structural changes such 9452 * as children and parent. For example, the view became focusable. The 9453 * notification is at at most once every 9454 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9455 * to avoid unnecessary load to the system. Also once a view has a pending 9456 * notification this method is a NOP until the notification has been sent. 9457 * 9458 * @hide 9459 */ 9460 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9461 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9462 return; 9463 } 9464 if (mSendViewStateChangedAccessibilityEvent == null) { 9465 mSendViewStateChangedAccessibilityEvent = 9466 new SendViewStateChangedAccessibilityEvent(); 9467 } 9468 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9469 } 9470 9471 /** 9472 * Notifies that the accessibility state of this view changed. The change 9473 * is *not* local to this view and does represent structural changes such 9474 * as children and parent. For example, the view size changed. The 9475 * notification is at at most once every 9476 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9477 * to avoid unnecessary load to the system. Also once a view has a pending 9478 * notification this method is a NOP until the notification has been sent. 9479 * 9480 * @hide 9481 */ 9482 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9483 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9484 return; 9485 } 9486 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9487 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9488 if (mParent != null) { 9489 try { 9490 mParent.notifySubtreeAccessibilityStateChanged( 9491 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9492 } catch (AbstractMethodError e) { 9493 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9494 " does not fully implement ViewParent", e); 9495 } 9496 } 9497 } 9498 } 9499 9500 /** 9501 * Change the visibility of the View without triggering any other changes. This is 9502 * important for transitions, where visibility changes should not adjust focus or 9503 * trigger a new layout. This is only used when the visibility has already been changed 9504 * and we need a transient value during an animation. When the animation completes, 9505 * the original visibility value is always restored. 9506 * 9507 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9508 * @hide 9509 */ 9510 public void setTransitionVisibility(@Visibility int visibility) { 9511 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9512 } 9513 9514 /** 9515 * Reset the flag indicating the accessibility state of the subtree rooted 9516 * at this view changed. 9517 */ 9518 void resetSubtreeAccessibilityStateChanged() { 9519 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9520 } 9521 9522 /** 9523 * Report an accessibility action to this view's parents for delegated processing. 9524 * 9525 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9526 * call this method to delegate an accessibility action to a supporting parent. If the parent 9527 * returns true from its 9528 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9529 * method this method will return true to signify that the action was consumed.</p> 9530 * 9531 * <p>This method is useful for implementing nested scrolling child views. If 9532 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9533 * a custom view implementation may invoke this method to allow a parent to consume the 9534 * scroll first. If this method returns true the custom view should skip its own scrolling 9535 * behavior.</p> 9536 * 9537 * @param action Accessibility action to delegate 9538 * @param arguments Optional action arguments 9539 * @return true if the action was consumed by a parent 9540 */ 9541 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9542 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9543 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9544 return true; 9545 } 9546 } 9547 return false; 9548 } 9549 9550 /** 9551 * Performs the specified accessibility action on the view. For 9552 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9553 * <p> 9554 * If an {@link AccessibilityDelegate} has been specified via calling 9555 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9556 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9557 * is responsible for handling this call. 9558 * </p> 9559 * 9560 * <p>The default implementation will delegate 9561 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9562 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9563 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9564 * 9565 * @param action The action to perform. 9566 * @param arguments Optional action arguments. 9567 * @return Whether the action was performed. 9568 */ 9569 public boolean performAccessibilityAction(int action, Bundle arguments) { 9570 if (mAccessibilityDelegate != null) { 9571 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9572 } else { 9573 return performAccessibilityActionInternal(action, arguments); 9574 } 9575 } 9576 9577 /** 9578 * @see #performAccessibilityAction(int, Bundle) 9579 * 9580 * Note: Called from the default {@link AccessibilityDelegate}. 9581 * 9582 * @hide 9583 */ 9584 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9585 if (isNestedScrollingEnabled() 9586 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9587 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9588 || action == R.id.accessibilityActionScrollUp 9589 || action == R.id.accessibilityActionScrollLeft 9590 || action == R.id.accessibilityActionScrollDown 9591 || action == R.id.accessibilityActionScrollRight)) { 9592 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9593 return true; 9594 } 9595 } 9596 9597 switch (action) { 9598 case AccessibilityNodeInfo.ACTION_CLICK: { 9599 if (isClickable()) { 9600 performClick(); 9601 return true; 9602 } 9603 } break; 9604 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9605 if (isLongClickable()) { 9606 performLongClick(); 9607 return true; 9608 } 9609 } break; 9610 case AccessibilityNodeInfo.ACTION_FOCUS: { 9611 if (!hasFocus()) { 9612 // Get out of touch mode since accessibility 9613 // wants to move focus around. 9614 getViewRootImpl().ensureTouchMode(false); 9615 return requestFocus(); 9616 } 9617 } break; 9618 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9619 if (hasFocus()) { 9620 clearFocus(); 9621 return !isFocused(); 9622 } 9623 } break; 9624 case AccessibilityNodeInfo.ACTION_SELECT: { 9625 if (!isSelected()) { 9626 setSelected(true); 9627 return isSelected(); 9628 } 9629 } break; 9630 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9631 if (isSelected()) { 9632 setSelected(false); 9633 return !isSelected(); 9634 } 9635 } break; 9636 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9637 if (!isAccessibilityFocused()) { 9638 return requestAccessibilityFocus(); 9639 } 9640 } break; 9641 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9642 if (isAccessibilityFocused()) { 9643 clearAccessibilityFocus(); 9644 return true; 9645 } 9646 } break; 9647 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9648 if (arguments != null) { 9649 final int granularity = arguments.getInt( 9650 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9651 final boolean extendSelection = arguments.getBoolean( 9652 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9653 return traverseAtGranularity(granularity, true, extendSelection); 9654 } 9655 } break; 9656 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9657 if (arguments != null) { 9658 final int granularity = arguments.getInt( 9659 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9660 final boolean extendSelection = arguments.getBoolean( 9661 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9662 return traverseAtGranularity(granularity, false, extendSelection); 9663 } 9664 } break; 9665 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9666 CharSequence text = getIterableTextForAccessibility(); 9667 if (text == null) { 9668 return false; 9669 } 9670 final int start = (arguments != null) ? arguments.getInt( 9671 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9672 final int end = (arguments != null) ? arguments.getInt( 9673 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9674 // Only cursor position can be specified (selection length == 0) 9675 if ((getAccessibilitySelectionStart() != start 9676 || getAccessibilitySelectionEnd() != end) 9677 && (start == end)) { 9678 setAccessibilitySelection(start, end); 9679 notifyViewAccessibilityStateChangedIfNeeded( 9680 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9681 return true; 9682 } 9683 } break; 9684 case R.id.accessibilityActionShowOnScreen: { 9685 if (mAttachInfo != null) { 9686 final Rect r = mAttachInfo.mTmpInvalRect; 9687 getDrawingRect(r); 9688 return requestRectangleOnScreen(r, true); 9689 } 9690 } break; 9691 case R.id.accessibilityActionContextClick: { 9692 if (isContextClickable()) { 9693 performContextClick(); 9694 return true; 9695 } 9696 } break; 9697 } 9698 return false; 9699 } 9700 9701 private boolean traverseAtGranularity(int granularity, boolean forward, 9702 boolean extendSelection) { 9703 CharSequence text = getIterableTextForAccessibility(); 9704 if (text == null || text.length() == 0) { 9705 return false; 9706 } 9707 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9708 if (iterator == null) { 9709 return false; 9710 } 9711 int current = getAccessibilitySelectionEnd(); 9712 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9713 current = forward ? 0 : text.length(); 9714 } 9715 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9716 if (range == null) { 9717 return false; 9718 } 9719 final int segmentStart = range[0]; 9720 final int segmentEnd = range[1]; 9721 int selectionStart; 9722 int selectionEnd; 9723 if (extendSelection && isAccessibilitySelectionExtendable()) { 9724 selectionStart = getAccessibilitySelectionStart(); 9725 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9726 selectionStart = forward ? segmentStart : segmentEnd; 9727 } 9728 selectionEnd = forward ? segmentEnd : segmentStart; 9729 } else { 9730 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9731 } 9732 setAccessibilitySelection(selectionStart, selectionEnd); 9733 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9734 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9735 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9736 return true; 9737 } 9738 9739 /** 9740 * Gets the text reported for accessibility purposes. 9741 * 9742 * @return The accessibility text. 9743 * 9744 * @hide 9745 */ 9746 public CharSequence getIterableTextForAccessibility() { 9747 return getContentDescription(); 9748 } 9749 9750 /** 9751 * Gets whether accessibility selection can be extended. 9752 * 9753 * @return If selection is extensible. 9754 * 9755 * @hide 9756 */ 9757 public boolean isAccessibilitySelectionExtendable() { 9758 return false; 9759 } 9760 9761 /** 9762 * @hide 9763 */ 9764 public int getAccessibilitySelectionStart() { 9765 return mAccessibilityCursorPosition; 9766 } 9767 9768 /** 9769 * @hide 9770 */ 9771 public int getAccessibilitySelectionEnd() { 9772 return getAccessibilitySelectionStart(); 9773 } 9774 9775 /** 9776 * @hide 9777 */ 9778 public void setAccessibilitySelection(int start, int end) { 9779 if (start == end && end == mAccessibilityCursorPosition) { 9780 return; 9781 } 9782 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9783 mAccessibilityCursorPosition = start; 9784 } else { 9785 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9786 } 9787 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9788 } 9789 9790 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9791 int fromIndex, int toIndex) { 9792 if (mParent == null) { 9793 return; 9794 } 9795 AccessibilityEvent event = AccessibilityEvent.obtain( 9796 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9797 onInitializeAccessibilityEvent(event); 9798 onPopulateAccessibilityEvent(event); 9799 event.setFromIndex(fromIndex); 9800 event.setToIndex(toIndex); 9801 event.setAction(action); 9802 event.setMovementGranularity(granularity); 9803 mParent.requestSendAccessibilityEvent(this, event); 9804 } 9805 9806 /** 9807 * @hide 9808 */ 9809 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9810 switch (granularity) { 9811 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9812 CharSequence text = getIterableTextForAccessibility(); 9813 if (text != null && text.length() > 0) { 9814 CharacterTextSegmentIterator iterator = 9815 CharacterTextSegmentIterator.getInstance( 9816 mContext.getResources().getConfiguration().locale); 9817 iterator.initialize(text.toString()); 9818 return iterator; 9819 } 9820 } break; 9821 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9822 CharSequence text = getIterableTextForAccessibility(); 9823 if (text != null && text.length() > 0) { 9824 WordTextSegmentIterator iterator = 9825 WordTextSegmentIterator.getInstance( 9826 mContext.getResources().getConfiguration().locale); 9827 iterator.initialize(text.toString()); 9828 return iterator; 9829 } 9830 } break; 9831 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9832 CharSequence text = getIterableTextForAccessibility(); 9833 if (text != null && text.length() > 0) { 9834 ParagraphTextSegmentIterator iterator = 9835 ParagraphTextSegmentIterator.getInstance(); 9836 iterator.initialize(text.toString()); 9837 return iterator; 9838 } 9839 } break; 9840 } 9841 return null; 9842 } 9843 9844 /** 9845 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 9846 * and {@link #onFinishTemporaryDetach()}. 9847 * 9848 * <p>This method always returns {@code true} when called directly or indirectly from 9849 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 9850 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 9851 * <ul> 9852 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 9853 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 9854 * </ul> 9855 * </p> 9856 * 9857 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9858 * and {@link #onFinishTemporaryDetach()}. 9859 */ 9860 public final boolean isTemporarilyDetached() { 9861 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9862 } 9863 9864 /** 9865 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9866 * a container View. 9867 */ 9868 @CallSuper 9869 public void dispatchStartTemporaryDetach() { 9870 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9871 onStartTemporaryDetach(); 9872 } 9873 9874 /** 9875 * This is called when a container is going to temporarily detach a child, with 9876 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9877 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9878 * {@link #onDetachedFromWindow()} when the container is done. 9879 */ 9880 public void onStartTemporaryDetach() { 9881 removeUnsetPressCallback(); 9882 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9883 } 9884 9885 /** 9886 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9887 * a container View. 9888 */ 9889 @CallSuper 9890 public void dispatchFinishTemporaryDetach() { 9891 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9892 onFinishTemporaryDetach(); 9893 if (hasWindowFocus() && hasFocus()) { 9894 InputMethodManager.getInstance().focusIn(this); 9895 } 9896 } 9897 9898 /** 9899 * Called after {@link #onStartTemporaryDetach} when the container is done 9900 * changing the view. 9901 */ 9902 public void onFinishTemporaryDetach() { 9903 } 9904 9905 /** 9906 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9907 * for this view's window. Returns null if the view is not currently attached 9908 * to the window. Normally you will not need to use this directly, but 9909 * just use the standard high-level event callbacks like 9910 * {@link #onKeyDown(int, KeyEvent)}. 9911 */ 9912 public KeyEvent.DispatcherState getKeyDispatcherState() { 9913 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9914 } 9915 9916 /** 9917 * Dispatch a key event before it is processed by any input method 9918 * associated with the view hierarchy. This can be used to intercept 9919 * key events in special situations before the IME consumes them; a 9920 * typical example would be handling the BACK key to update the application's 9921 * UI instead of allowing the IME to see it and close itself. 9922 * 9923 * @param event The key event to be dispatched. 9924 * @return True if the event was handled, false otherwise. 9925 */ 9926 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9927 return onKeyPreIme(event.getKeyCode(), event); 9928 } 9929 9930 /** 9931 * Dispatch a key event to the next view on the focus path. This path runs 9932 * from the top of the view tree down to the currently focused view. If this 9933 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9934 * the next node down the focus path. This method also fires any key 9935 * listeners. 9936 * 9937 * @param event The key event to be dispatched. 9938 * @return True if the event was handled, false otherwise. 9939 */ 9940 public boolean dispatchKeyEvent(KeyEvent event) { 9941 if (mInputEventConsistencyVerifier != null) { 9942 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9943 } 9944 9945 // Give any attached key listener a first crack at the event. 9946 //noinspection SimplifiableIfStatement 9947 ListenerInfo li = mListenerInfo; 9948 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9949 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9950 return true; 9951 } 9952 9953 if (event.dispatch(this, mAttachInfo != null 9954 ? mAttachInfo.mKeyDispatchState : null, this)) { 9955 return true; 9956 } 9957 9958 if (mInputEventConsistencyVerifier != null) { 9959 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9960 } 9961 return false; 9962 } 9963 9964 /** 9965 * Dispatches a key shortcut event. 9966 * 9967 * @param event The key event to be dispatched. 9968 * @return True if the event was handled by the view, false otherwise. 9969 */ 9970 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9971 return onKeyShortcut(event.getKeyCode(), event); 9972 } 9973 9974 /** 9975 * Pass the touch screen motion event down to the target view, or this 9976 * view if it is the target. 9977 * 9978 * @param event The motion event to be dispatched. 9979 * @return True if the event was handled by the view, false otherwise. 9980 */ 9981 public boolean dispatchTouchEvent(MotionEvent event) { 9982 // If the event should be handled by accessibility focus first. 9983 if (event.isTargetAccessibilityFocus()) { 9984 // We don't have focus or no virtual descendant has it, do not handle the event. 9985 if (!isAccessibilityFocusedViewOrHost()) { 9986 return false; 9987 } 9988 // We have focus and got the event, then use normal event dispatch. 9989 event.setTargetAccessibilityFocus(false); 9990 } 9991 9992 boolean result = false; 9993 9994 if (mInputEventConsistencyVerifier != null) { 9995 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9996 } 9997 9998 final int actionMasked = event.getActionMasked(); 9999 if (actionMasked == MotionEvent.ACTION_DOWN) { 10000 // Defensive cleanup for new gesture 10001 stopNestedScroll(); 10002 } 10003 10004 if (onFilterTouchEventForSecurity(event)) { 10005 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 10006 result = true; 10007 } 10008 //noinspection SimplifiableIfStatement 10009 ListenerInfo li = mListenerInfo; 10010 if (li != null && li.mOnTouchListener != null 10011 && (mViewFlags & ENABLED_MASK) == ENABLED 10012 && li.mOnTouchListener.onTouch(this, event)) { 10013 result = true; 10014 } 10015 10016 if (!result && onTouchEvent(event)) { 10017 result = true; 10018 } 10019 } 10020 10021 if (!result && mInputEventConsistencyVerifier != null) { 10022 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10023 } 10024 10025 // Clean up after nested scrolls if this is the end of a gesture; 10026 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 10027 // of the gesture. 10028 if (actionMasked == MotionEvent.ACTION_UP || 10029 actionMasked == MotionEvent.ACTION_CANCEL || 10030 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 10031 stopNestedScroll(); 10032 } 10033 10034 return result; 10035 } 10036 10037 boolean isAccessibilityFocusedViewOrHost() { 10038 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 10039 .getAccessibilityFocusedHost() == this); 10040 } 10041 10042 /** 10043 * Filter the touch event to apply security policies. 10044 * 10045 * @param event The motion event to be filtered. 10046 * @return True if the event should be dispatched, false if the event should be dropped. 10047 * 10048 * @see #getFilterTouchesWhenObscured 10049 */ 10050 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 10051 //noinspection RedundantIfStatement 10052 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 10053 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 10054 // Window is obscured, drop this touch. 10055 return false; 10056 } 10057 return true; 10058 } 10059 10060 /** 10061 * Pass a trackball motion event down to the focused view. 10062 * 10063 * @param event The motion event to be dispatched. 10064 * @return True if the event was handled by the view, false otherwise. 10065 */ 10066 public boolean dispatchTrackballEvent(MotionEvent event) { 10067 if (mInputEventConsistencyVerifier != null) { 10068 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 10069 } 10070 10071 return onTrackballEvent(event); 10072 } 10073 10074 /** 10075 * Dispatch a generic motion event. 10076 * <p> 10077 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10078 * are delivered to the view under the pointer. All other generic motion events are 10079 * delivered to the focused view. Hover events are handled specially and are delivered 10080 * to {@link #onHoverEvent(MotionEvent)}. 10081 * </p> 10082 * 10083 * @param event The motion event to be dispatched. 10084 * @return True if the event was handled by the view, false otherwise. 10085 */ 10086 public boolean dispatchGenericMotionEvent(MotionEvent event) { 10087 if (mInputEventConsistencyVerifier != null) { 10088 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10089 } 10090 10091 final int source = event.getSource(); 10092 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10093 final int action = event.getAction(); 10094 if (action == MotionEvent.ACTION_HOVER_ENTER 10095 || action == MotionEvent.ACTION_HOVER_MOVE 10096 || action == MotionEvent.ACTION_HOVER_EXIT) { 10097 if (dispatchHoverEvent(event)) { 10098 return true; 10099 } 10100 } else if (dispatchGenericPointerEvent(event)) { 10101 return true; 10102 } 10103 } else if (dispatchGenericFocusedEvent(event)) { 10104 return true; 10105 } 10106 10107 if (dispatchGenericMotionEventInternal(event)) { 10108 return true; 10109 } 10110 10111 if (mInputEventConsistencyVerifier != null) { 10112 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10113 } 10114 return false; 10115 } 10116 10117 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10118 //noinspection SimplifiableIfStatement 10119 ListenerInfo li = mListenerInfo; 10120 if (li != null && li.mOnGenericMotionListener != null 10121 && (mViewFlags & ENABLED_MASK) == ENABLED 10122 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10123 return true; 10124 } 10125 10126 if (onGenericMotionEvent(event)) { 10127 return true; 10128 } 10129 10130 final int actionButton = event.getActionButton(); 10131 switch (event.getActionMasked()) { 10132 case MotionEvent.ACTION_BUTTON_PRESS: 10133 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10134 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10135 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10136 if (performContextClick(event.getX(), event.getY())) { 10137 mInContextButtonPress = true; 10138 setPressed(true, event.getX(), event.getY()); 10139 removeTapCallback(); 10140 removeLongPressCallback(); 10141 return true; 10142 } 10143 } 10144 break; 10145 10146 case MotionEvent.ACTION_BUTTON_RELEASE: 10147 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10148 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10149 mInContextButtonPress = false; 10150 mIgnoreNextUpEvent = true; 10151 } 10152 break; 10153 } 10154 10155 if (mInputEventConsistencyVerifier != null) { 10156 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10157 } 10158 return false; 10159 } 10160 10161 /** 10162 * Dispatch a hover event. 10163 * <p> 10164 * Do not call this method directly. 10165 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10166 * </p> 10167 * 10168 * @param event The motion event to be dispatched. 10169 * @return True if the event was handled by the view, false otherwise. 10170 */ 10171 protected boolean dispatchHoverEvent(MotionEvent event) { 10172 ListenerInfo li = mListenerInfo; 10173 //noinspection SimplifiableIfStatement 10174 if (li != null && li.mOnHoverListener != null 10175 && (mViewFlags & ENABLED_MASK) == ENABLED 10176 && li.mOnHoverListener.onHover(this, event)) { 10177 return true; 10178 } 10179 10180 return onHoverEvent(event); 10181 } 10182 10183 /** 10184 * Returns true if the view has a child to which it has recently sent 10185 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10186 * it does not have a hovered child, then it must be the innermost hovered view. 10187 * @hide 10188 */ 10189 protected boolean hasHoveredChild() { 10190 return false; 10191 } 10192 10193 /** 10194 * Dispatch a generic motion event to the view under the first pointer. 10195 * <p> 10196 * Do not call this method directly. 10197 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10198 * </p> 10199 * 10200 * @param event The motion event to be dispatched. 10201 * @return True if the event was handled by the view, false otherwise. 10202 */ 10203 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10204 return false; 10205 } 10206 10207 /** 10208 * Dispatch a generic motion event to the currently focused view. 10209 * <p> 10210 * Do not call this method directly. 10211 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10212 * </p> 10213 * 10214 * @param event The motion event to be dispatched. 10215 * @return True if the event was handled by the view, false otherwise. 10216 */ 10217 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10218 return false; 10219 } 10220 10221 /** 10222 * Dispatch a pointer event. 10223 * <p> 10224 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10225 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10226 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10227 * and should not be expected to handle other pointing device features. 10228 * </p> 10229 * 10230 * @param event The motion event to be dispatched. 10231 * @return True if the event was handled by the view, false otherwise. 10232 * @hide 10233 */ 10234 public final boolean dispatchPointerEvent(MotionEvent event) { 10235 if (event.isTouchEvent()) { 10236 return dispatchTouchEvent(event); 10237 } else { 10238 return dispatchGenericMotionEvent(event); 10239 } 10240 } 10241 10242 /** 10243 * Called when the window containing this view gains or loses window focus. 10244 * ViewGroups should override to route to their children. 10245 * 10246 * @param hasFocus True if the window containing this view now has focus, 10247 * false otherwise. 10248 */ 10249 public void dispatchWindowFocusChanged(boolean hasFocus) { 10250 onWindowFocusChanged(hasFocus); 10251 } 10252 10253 /** 10254 * Called when the window containing this view gains or loses focus. Note 10255 * that this is separate from view focus: to receive key events, both 10256 * your view and its window must have focus. If a window is displayed 10257 * on top of yours that takes input focus, then your own window will lose 10258 * focus but the view focus will remain unchanged. 10259 * 10260 * @param hasWindowFocus True if the window containing this view now has 10261 * focus, false otherwise. 10262 */ 10263 public void onWindowFocusChanged(boolean hasWindowFocus) { 10264 InputMethodManager imm = InputMethodManager.peekInstance(); 10265 if (!hasWindowFocus) { 10266 if (isPressed()) { 10267 setPressed(false); 10268 } 10269 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10270 imm.focusOut(this); 10271 } 10272 removeLongPressCallback(); 10273 removeTapCallback(); 10274 onFocusLost(); 10275 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10276 imm.focusIn(this); 10277 } 10278 refreshDrawableState(); 10279 } 10280 10281 /** 10282 * Returns true if this view is in a window that currently has window focus. 10283 * Note that this is not the same as the view itself having focus. 10284 * 10285 * @return True if this view is in a window that currently has window focus. 10286 */ 10287 public boolean hasWindowFocus() { 10288 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10289 } 10290 10291 /** 10292 * Dispatch a view visibility change down the view hierarchy. 10293 * ViewGroups should override to route to their children. 10294 * @param changedView The view whose visibility changed. Could be 'this' or 10295 * an ancestor view. 10296 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10297 * {@link #INVISIBLE} or {@link #GONE}. 10298 */ 10299 protected void dispatchVisibilityChanged(@NonNull View changedView, 10300 @Visibility int visibility) { 10301 onVisibilityChanged(changedView, visibility); 10302 } 10303 10304 /** 10305 * Called when the visibility of the view or an ancestor of the view has 10306 * changed. 10307 * 10308 * @param changedView The view whose visibility changed. May be 10309 * {@code this} or an ancestor view. 10310 * @param visibility The new visibility, one of {@link #VISIBLE}, 10311 * {@link #INVISIBLE} or {@link #GONE}. 10312 */ 10313 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10314 } 10315 10316 /** 10317 * Dispatch a hint about whether this view is displayed. For instance, when 10318 * a View moves out of the screen, it might receives a display hint indicating 10319 * the view is not displayed. Applications should not <em>rely</em> on this hint 10320 * as there is no guarantee that they will receive one. 10321 * 10322 * @param hint A hint about whether or not this view is displayed: 10323 * {@link #VISIBLE} or {@link #INVISIBLE}. 10324 */ 10325 public void dispatchDisplayHint(@Visibility int hint) { 10326 onDisplayHint(hint); 10327 } 10328 10329 /** 10330 * Gives this view a hint about whether is displayed or not. For instance, when 10331 * a View moves out of the screen, it might receives a display hint indicating 10332 * the view is not displayed. Applications should not <em>rely</em> on this hint 10333 * as there is no guarantee that they will receive one. 10334 * 10335 * @param hint A hint about whether or not this view is displayed: 10336 * {@link #VISIBLE} or {@link #INVISIBLE}. 10337 */ 10338 protected void onDisplayHint(@Visibility int hint) { 10339 } 10340 10341 /** 10342 * Dispatch a window visibility change down the view hierarchy. 10343 * ViewGroups should override to route to their children. 10344 * 10345 * @param visibility The new visibility of the window. 10346 * 10347 * @see #onWindowVisibilityChanged(int) 10348 */ 10349 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10350 onWindowVisibilityChanged(visibility); 10351 } 10352 10353 /** 10354 * Called when the window containing has change its visibility 10355 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10356 * that this tells you whether or not your window is being made visible 10357 * to the window manager; this does <em>not</em> tell you whether or not 10358 * your window is obscured by other windows on the screen, even if it 10359 * is itself visible. 10360 * 10361 * @param visibility The new visibility of the window. 10362 */ 10363 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10364 if (visibility == VISIBLE) { 10365 initialAwakenScrollBars(); 10366 } 10367 } 10368 10369 /** 10370 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10371 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10372 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10373 * 10374 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10375 * ancestors or by window visibility 10376 * @return true if this view is visible to the user, not counting clipping or overlapping 10377 */ 10378 boolean dispatchVisibilityAggregated(boolean isVisible) { 10379 final boolean thisVisible = getVisibility() == VISIBLE; 10380 // If we're not visible but something is telling us we are, ignore it. 10381 if (thisVisible || !isVisible) { 10382 onVisibilityAggregated(isVisible); 10383 } 10384 return thisVisible && isVisible; 10385 } 10386 10387 /** 10388 * Called when the user-visibility of this View is potentially affected by a change 10389 * to this view itself, an ancestor view or the window this view is attached to. 10390 * 10391 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10392 * and this view's window is also visible 10393 */ 10394 @CallSuper 10395 public void onVisibilityAggregated(boolean isVisible) { 10396 if (isVisible && mAttachInfo != null) { 10397 initialAwakenScrollBars(); 10398 } 10399 10400 final Drawable dr = mBackground; 10401 if (dr != null && isVisible != dr.isVisible()) { 10402 dr.setVisible(isVisible, false); 10403 } 10404 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10405 if (fg != null && isVisible != fg.isVisible()) { 10406 fg.setVisible(isVisible, false); 10407 } 10408 } 10409 10410 /** 10411 * Returns the current visibility of the window this view is attached to 10412 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10413 * 10414 * @return Returns the current visibility of the view's window. 10415 */ 10416 @Visibility 10417 public int getWindowVisibility() { 10418 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10419 } 10420 10421 /** 10422 * Retrieve the overall visible display size in which the window this view is 10423 * attached to has been positioned in. This takes into account screen 10424 * decorations above the window, for both cases where the window itself 10425 * is being position inside of them or the window is being placed under 10426 * then and covered insets are used for the window to position its content 10427 * inside. In effect, this tells you the available area where content can 10428 * be placed and remain visible to users. 10429 * 10430 * <p>This function requires an IPC back to the window manager to retrieve 10431 * the requested information, so should not be used in performance critical 10432 * code like drawing. 10433 * 10434 * @param outRect Filled in with the visible display frame. If the view 10435 * is not attached to a window, this is simply the raw display size. 10436 */ 10437 public void getWindowVisibleDisplayFrame(Rect outRect) { 10438 if (mAttachInfo != null) { 10439 try { 10440 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10441 } catch (RemoteException e) { 10442 return; 10443 } 10444 // XXX This is really broken, and probably all needs to be done 10445 // in the window manager, and we need to know more about whether 10446 // we want the area behind or in front of the IME. 10447 final Rect insets = mAttachInfo.mVisibleInsets; 10448 outRect.left += insets.left; 10449 outRect.top += insets.top; 10450 outRect.right -= insets.right; 10451 outRect.bottom -= insets.bottom; 10452 return; 10453 } 10454 // The view is not attached to a display so we don't have a context. 10455 // Make a best guess about the display size. 10456 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10457 d.getRectSize(outRect); 10458 } 10459 10460 /** 10461 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10462 * is currently in without any insets. 10463 * 10464 * @hide 10465 */ 10466 public void getWindowDisplayFrame(Rect outRect) { 10467 if (mAttachInfo != null) { 10468 try { 10469 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10470 } catch (RemoteException e) { 10471 return; 10472 } 10473 return; 10474 } 10475 // The view is not attached to a display so we don't have a context. 10476 // Make a best guess about the display size. 10477 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10478 d.getRectSize(outRect); 10479 } 10480 10481 /** 10482 * Dispatch a notification about a resource configuration change down 10483 * the view hierarchy. 10484 * ViewGroups should override to route to their children. 10485 * 10486 * @param newConfig The new resource configuration. 10487 * 10488 * @see #onConfigurationChanged(android.content.res.Configuration) 10489 */ 10490 public void dispatchConfigurationChanged(Configuration newConfig) { 10491 onConfigurationChanged(newConfig); 10492 } 10493 10494 /** 10495 * Called when the current configuration of the resources being used 10496 * by the application have changed. You can use this to decide when 10497 * to reload resources that can changed based on orientation and other 10498 * configuration characteristics. You only need to use this if you are 10499 * not relying on the normal {@link android.app.Activity} mechanism of 10500 * recreating the activity instance upon a configuration change. 10501 * 10502 * @param newConfig The new resource configuration. 10503 */ 10504 protected void onConfigurationChanged(Configuration newConfig) { 10505 } 10506 10507 /** 10508 * Private function to aggregate all per-view attributes in to the view 10509 * root. 10510 */ 10511 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10512 performCollectViewAttributes(attachInfo, visibility); 10513 } 10514 10515 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10516 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10517 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10518 attachInfo.mKeepScreenOn = true; 10519 } 10520 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10521 ListenerInfo li = mListenerInfo; 10522 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10523 attachInfo.mHasSystemUiListeners = true; 10524 } 10525 } 10526 } 10527 10528 void needGlobalAttributesUpdate(boolean force) { 10529 final AttachInfo ai = mAttachInfo; 10530 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10531 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10532 || ai.mHasSystemUiListeners) { 10533 ai.mRecomputeGlobalAttributes = true; 10534 } 10535 } 10536 } 10537 10538 /** 10539 * Returns whether the device is currently in touch mode. Touch mode is entered 10540 * once the user begins interacting with the device by touch, and affects various 10541 * things like whether focus is always visible to the user. 10542 * 10543 * @return Whether the device is in touch mode. 10544 */ 10545 @ViewDebug.ExportedProperty 10546 public boolean isInTouchMode() { 10547 if (mAttachInfo != null) { 10548 return mAttachInfo.mInTouchMode; 10549 } else { 10550 return ViewRootImpl.isInTouchMode(); 10551 } 10552 } 10553 10554 /** 10555 * Returns the context the view is running in, through which it can 10556 * access the current theme, resources, etc. 10557 * 10558 * @return The view's Context. 10559 */ 10560 @ViewDebug.CapturedViewProperty 10561 public final Context getContext() { 10562 return mContext; 10563 } 10564 10565 /** 10566 * Handle a key event before it is processed by any input method 10567 * associated with the view hierarchy. This can be used to intercept 10568 * key events in special situations before the IME consumes them; a 10569 * typical example would be handling the BACK key to update the application's 10570 * UI instead of allowing the IME to see it and close itself. 10571 * 10572 * @param keyCode The value in event.getKeyCode(). 10573 * @param event Description of the key event. 10574 * @return If you handled the event, return true. If you want to allow the 10575 * event to be handled by the next receiver, return false. 10576 */ 10577 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10578 return false; 10579 } 10580 10581 /** 10582 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10583 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10584 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10585 * is released, if the view is enabled and clickable. 10586 * <p> 10587 * Key presses in software keyboards will generally NOT trigger this 10588 * listener, although some may elect to do so in some situations. Do not 10589 * rely on this to catch software key presses. 10590 * 10591 * @param keyCode a key code that represents the button pressed, from 10592 * {@link android.view.KeyEvent} 10593 * @param event the KeyEvent object that defines the button action 10594 */ 10595 public boolean onKeyDown(int keyCode, KeyEvent event) { 10596 if (KeyEvent.isConfirmKey(keyCode)) { 10597 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10598 return true; 10599 } 10600 10601 // Long clickable items don't necessarily have to be clickable. 10602 if (((mViewFlags & CLICKABLE) == CLICKABLE 10603 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10604 && (event.getRepeatCount() == 0)) { 10605 // For the purposes of menu anchoring and drawable hotspots, 10606 // key events are considered to be at the center of the view. 10607 final float x = getWidth() / 2f; 10608 final float y = getHeight() / 2f; 10609 setPressed(true, x, y); 10610 checkForLongClick(0, x, y); 10611 return true; 10612 } 10613 } 10614 10615 return false; 10616 } 10617 10618 /** 10619 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10620 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10621 * the event). 10622 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10623 * although some may elect to do so in some situations. Do not rely on this to 10624 * catch software key presses. 10625 */ 10626 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10627 return false; 10628 } 10629 10630 /** 10631 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10632 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10633 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10634 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10635 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10636 * although some may elect to do so in some situations. Do not rely on this to 10637 * catch software key presses. 10638 * 10639 * @param keyCode A key code that represents the button pressed, from 10640 * {@link android.view.KeyEvent}. 10641 * @param event The KeyEvent object that defines the button action. 10642 */ 10643 public boolean onKeyUp(int keyCode, KeyEvent event) { 10644 if (KeyEvent.isConfirmKey(keyCode)) { 10645 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10646 return true; 10647 } 10648 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10649 setPressed(false); 10650 10651 if (!mHasPerformedLongPress) { 10652 // This is a tap, so remove the longpress check 10653 removeLongPressCallback(); 10654 return performClick(); 10655 } 10656 } 10657 } 10658 return false; 10659 } 10660 10661 /** 10662 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10663 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10664 * the event). 10665 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10666 * although some may elect to do so in some situations. Do not rely on this to 10667 * catch software key presses. 10668 * 10669 * @param keyCode A key code that represents the button pressed, from 10670 * {@link android.view.KeyEvent}. 10671 * @param repeatCount The number of times the action was made. 10672 * @param event The KeyEvent object that defines the button action. 10673 */ 10674 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10675 return false; 10676 } 10677 10678 /** 10679 * Called on the focused view when a key shortcut event is not handled. 10680 * Override this method to implement local key shortcuts for the View. 10681 * Key shortcuts can also be implemented by setting the 10682 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10683 * 10684 * @param keyCode The value in event.getKeyCode(). 10685 * @param event Description of the key event. 10686 * @return If you handled the event, return true. If you want to allow the 10687 * event to be handled by the next receiver, return false. 10688 */ 10689 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10690 return false; 10691 } 10692 10693 /** 10694 * Check whether the called view is a text editor, in which case it 10695 * would make sense to automatically display a soft input window for 10696 * it. Subclasses should override this if they implement 10697 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10698 * a call on that method would return a non-null InputConnection, and 10699 * they are really a first-class editor that the user would normally 10700 * start typing on when the go into a window containing your view. 10701 * 10702 * <p>The default implementation always returns false. This does 10703 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10704 * will not be called or the user can not otherwise perform edits on your 10705 * view; it is just a hint to the system that this is not the primary 10706 * purpose of this view. 10707 * 10708 * @return Returns true if this view is a text editor, else false. 10709 */ 10710 public boolean onCheckIsTextEditor() { 10711 return false; 10712 } 10713 10714 /** 10715 * Create a new InputConnection for an InputMethod to interact 10716 * with the view. The default implementation returns null, since it doesn't 10717 * support input methods. You can override this to implement such support. 10718 * This is only needed for views that take focus and text input. 10719 * 10720 * <p>When implementing this, you probably also want to implement 10721 * {@link #onCheckIsTextEditor()} to indicate you will return a 10722 * non-null InputConnection.</p> 10723 * 10724 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10725 * object correctly and in its entirety, so that the connected IME can rely 10726 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10727 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10728 * must be filled in with the correct cursor position for IMEs to work correctly 10729 * with your application.</p> 10730 * 10731 * @param outAttrs Fill in with attribute information about the connection. 10732 */ 10733 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10734 return null; 10735 } 10736 10737 /** 10738 * Called by the {@link android.view.inputmethod.InputMethodManager} 10739 * when a view who is not the current 10740 * input connection target is trying to make a call on the manager. The 10741 * default implementation returns false; you can override this to return 10742 * true for certain views if you are performing InputConnection proxying 10743 * to them. 10744 * @param view The View that is making the InputMethodManager call. 10745 * @return Return true to allow the call, false to reject. 10746 */ 10747 public boolean checkInputConnectionProxy(View view) { 10748 return false; 10749 } 10750 10751 /** 10752 * Show the context menu for this view. It is not safe to hold on to the 10753 * menu after returning from this method. 10754 * 10755 * You should normally not overload this method. Overload 10756 * {@link #onCreateContextMenu(ContextMenu)} or define an 10757 * {@link OnCreateContextMenuListener} to add items to the context menu. 10758 * 10759 * @param menu The context menu to populate 10760 */ 10761 public void createContextMenu(ContextMenu menu) { 10762 ContextMenuInfo menuInfo = getContextMenuInfo(); 10763 10764 // Sets the current menu info so all items added to menu will have 10765 // my extra info set. 10766 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10767 10768 onCreateContextMenu(menu); 10769 ListenerInfo li = mListenerInfo; 10770 if (li != null && li.mOnCreateContextMenuListener != null) { 10771 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10772 } 10773 10774 // Clear the extra information so subsequent items that aren't mine don't 10775 // have my extra info. 10776 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10777 10778 if (mParent != null) { 10779 mParent.createContextMenu(menu); 10780 } 10781 } 10782 10783 /** 10784 * Views should implement this if they have extra information to associate 10785 * with the context menu. The return result is supplied as a parameter to 10786 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10787 * callback. 10788 * 10789 * @return Extra information about the item for which the context menu 10790 * should be shown. This information will vary across different 10791 * subclasses of View. 10792 */ 10793 protected ContextMenuInfo getContextMenuInfo() { 10794 return null; 10795 } 10796 10797 /** 10798 * Views should implement this if the view itself is going to add items to 10799 * the context menu. 10800 * 10801 * @param menu the context menu to populate 10802 */ 10803 protected void onCreateContextMenu(ContextMenu menu) { 10804 } 10805 10806 /** 10807 * Implement this method to handle trackball motion events. The 10808 * <em>relative</em> movement of the trackball since the last event 10809 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10810 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10811 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10812 * they will often be fractional values, representing the more fine-grained 10813 * movement information available from a trackball). 10814 * 10815 * @param event The motion event. 10816 * @return True if the event was handled, false otherwise. 10817 */ 10818 public boolean onTrackballEvent(MotionEvent event) { 10819 return false; 10820 } 10821 10822 /** 10823 * Implement this method to handle generic motion events. 10824 * <p> 10825 * Generic motion events describe joystick movements, mouse hovers, track pad 10826 * touches, scroll wheel movements and other input events. The 10827 * {@link MotionEvent#getSource() source} of the motion event specifies 10828 * the class of input that was received. Implementations of this method 10829 * must examine the bits in the source before processing the event. 10830 * The following code example shows how this is done. 10831 * </p><p> 10832 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10833 * are delivered to the view under the pointer. All other generic motion events are 10834 * delivered to the focused view. 10835 * </p> 10836 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10837 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10838 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10839 * // process the joystick movement... 10840 * return true; 10841 * } 10842 * } 10843 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10844 * switch (event.getAction()) { 10845 * case MotionEvent.ACTION_HOVER_MOVE: 10846 * // process the mouse hover movement... 10847 * return true; 10848 * case MotionEvent.ACTION_SCROLL: 10849 * // process the scroll wheel movement... 10850 * return true; 10851 * } 10852 * } 10853 * return super.onGenericMotionEvent(event); 10854 * }</pre> 10855 * 10856 * @param event The generic motion event being processed. 10857 * @return True if the event was handled, false otherwise. 10858 */ 10859 public boolean onGenericMotionEvent(MotionEvent event) { 10860 return false; 10861 } 10862 10863 /** 10864 * Implement this method to handle hover events. 10865 * <p> 10866 * This method is called whenever a pointer is hovering into, over, or out of the 10867 * bounds of a view and the view is not currently being touched. 10868 * Hover events are represented as pointer events with action 10869 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10870 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10871 * </p> 10872 * <ul> 10873 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10874 * when the pointer enters the bounds of the view.</li> 10875 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10876 * when the pointer has already entered the bounds of the view and has moved.</li> 10877 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10878 * when the pointer has exited the bounds of the view or when the pointer is 10879 * about to go down due to a button click, tap, or similar user action that 10880 * causes the view to be touched.</li> 10881 * </ul> 10882 * <p> 10883 * The view should implement this method to return true to indicate that it is 10884 * handling the hover event, such as by changing its drawable state. 10885 * </p><p> 10886 * The default implementation calls {@link #setHovered} to update the hovered state 10887 * of the view when a hover enter or hover exit event is received, if the view 10888 * is enabled and is clickable. The default implementation also sends hover 10889 * accessibility events. 10890 * </p> 10891 * 10892 * @param event The motion event that describes the hover. 10893 * @return True if the view handled the hover event. 10894 * 10895 * @see #isHovered 10896 * @see #setHovered 10897 * @see #onHoverChanged 10898 */ 10899 public boolean onHoverEvent(MotionEvent event) { 10900 // The root view may receive hover (or touch) events that are outside the bounds of 10901 // the window. This code ensures that we only send accessibility events for 10902 // hovers that are actually within the bounds of the root view. 10903 final int action = event.getActionMasked(); 10904 if (!mSendingHoverAccessibilityEvents) { 10905 if ((action == MotionEvent.ACTION_HOVER_ENTER 10906 || action == MotionEvent.ACTION_HOVER_MOVE) 10907 && !hasHoveredChild() 10908 && pointInView(event.getX(), event.getY())) { 10909 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10910 mSendingHoverAccessibilityEvents = true; 10911 } 10912 } else { 10913 if (action == MotionEvent.ACTION_HOVER_EXIT 10914 || (action == MotionEvent.ACTION_MOVE 10915 && !pointInView(event.getX(), event.getY()))) { 10916 mSendingHoverAccessibilityEvents = false; 10917 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10918 } 10919 } 10920 10921 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10922 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10923 && isOnScrollbar(event.getX(), event.getY())) { 10924 awakenScrollBars(); 10925 } 10926 if (isHoverable()) { 10927 switch (action) { 10928 case MotionEvent.ACTION_HOVER_ENTER: 10929 setHovered(true); 10930 break; 10931 case MotionEvent.ACTION_HOVER_EXIT: 10932 setHovered(false); 10933 break; 10934 } 10935 10936 // Dispatch the event to onGenericMotionEvent before returning true. 10937 // This is to provide compatibility with existing applications that 10938 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10939 // break because of the new default handling for hoverable views 10940 // in onHoverEvent. 10941 // Note that onGenericMotionEvent will be called by default when 10942 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10943 dispatchGenericMotionEventInternal(event); 10944 // The event was already handled by calling setHovered(), so always 10945 // return true. 10946 return true; 10947 } 10948 10949 return false; 10950 } 10951 10952 /** 10953 * Returns true if the view should handle {@link #onHoverEvent} 10954 * by calling {@link #setHovered} to change its hovered state. 10955 * 10956 * @return True if the view is hoverable. 10957 */ 10958 private boolean isHoverable() { 10959 final int viewFlags = mViewFlags; 10960 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10961 return false; 10962 } 10963 10964 return (viewFlags & CLICKABLE) == CLICKABLE 10965 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10966 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10967 } 10968 10969 /** 10970 * Returns true if the view is currently hovered. 10971 * 10972 * @return True if the view is currently hovered. 10973 * 10974 * @see #setHovered 10975 * @see #onHoverChanged 10976 */ 10977 @ViewDebug.ExportedProperty 10978 public boolean isHovered() { 10979 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10980 } 10981 10982 /** 10983 * Sets whether the view is currently hovered. 10984 * <p> 10985 * Calling this method also changes the drawable state of the view. This 10986 * enables the view to react to hover by using different drawable resources 10987 * to change its appearance. 10988 * </p><p> 10989 * The {@link #onHoverChanged} method is called when the hovered state changes. 10990 * </p> 10991 * 10992 * @param hovered True if the view is hovered. 10993 * 10994 * @see #isHovered 10995 * @see #onHoverChanged 10996 */ 10997 public void setHovered(boolean hovered) { 10998 if (hovered) { 10999 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 11000 mPrivateFlags |= PFLAG_HOVERED; 11001 refreshDrawableState(); 11002 onHoverChanged(true); 11003 } 11004 } else { 11005 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 11006 mPrivateFlags &= ~PFLAG_HOVERED; 11007 refreshDrawableState(); 11008 onHoverChanged(false); 11009 } 11010 } 11011 } 11012 11013 /** 11014 * Implement this method to handle hover state changes. 11015 * <p> 11016 * This method is called whenever the hover state changes as a result of a 11017 * call to {@link #setHovered}. 11018 * </p> 11019 * 11020 * @param hovered The current hover state, as returned by {@link #isHovered}. 11021 * 11022 * @see #isHovered 11023 * @see #setHovered 11024 */ 11025 public void onHoverChanged(boolean hovered) { 11026 } 11027 11028 /** 11029 * Handles scroll bar dragging by mouse input. 11030 * 11031 * @hide 11032 * @param event The motion event. 11033 * 11034 * @return true if the event was handled as a scroll bar dragging, false otherwise. 11035 */ 11036 protected boolean handleScrollBarDragging(MotionEvent event) { 11037 if (mScrollCache == null) { 11038 return false; 11039 } 11040 final float x = event.getX(); 11041 final float y = event.getY(); 11042 final int action = event.getAction(); 11043 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 11044 && action != MotionEvent.ACTION_DOWN) 11045 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 11046 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 11047 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11048 return false; 11049 } 11050 11051 switch (action) { 11052 case MotionEvent.ACTION_MOVE: 11053 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 11054 return false; 11055 } 11056 if (mScrollCache.mScrollBarDraggingState 11057 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 11058 final Rect bounds = mScrollCache.mScrollBarBounds; 11059 getVerticalScrollBarBounds(bounds); 11060 final int range = computeVerticalScrollRange(); 11061 final int offset = computeVerticalScrollOffset(); 11062 final int extent = computeVerticalScrollExtent(); 11063 11064 final int thumbLength = ScrollBarUtils.getThumbLength( 11065 bounds.height(), bounds.width(), extent, range); 11066 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11067 bounds.height(), thumbLength, extent, range, offset); 11068 11069 final float diff = y - mScrollCache.mScrollBarDraggingPos; 11070 final float maxThumbOffset = bounds.height() - thumbLength; 11071 final float newThumbOffset = 11072 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11073 final int height = getHeight(); 11074 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11075 && height > 0 && extent > 0) { 11076 final int newY = Math.round((range - extent) 11077 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 11078 if (newY != getScrollY()) { 11079 mScrollCache.mScrollBarDraggingPos = y; 11080 setScrollY(newY); 11081 } 11082 } 11083 return true; 11084 } 11085 if (mScrollCache.mScrollBarDraggingState 11086 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 11087 final Rect bounds = mScrollCache.mScrollBarBounds; 11088 getHorizontalScrollBarBounds(bounds); 11089 final int range = computeHorizontalScrollRange(); 11090 final int offset = computeHorizontalScrollOffset(); 11091 final int extent = computeHorizontalScrollExtent(); 11092 11093 final int thumbLength = ScrollBarUtils.getThumbLength( 11094 bounds.width(), bounds.height(), extent, range); 11095 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11096 bounds.width(), thumbLength, extent, range, offset); 11097 11098 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11099 final float maxThumbOffset = bounds.width() - thumbLength; 11100 final float newThumbOffset = 11101 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11102 final int width = getWidth(); 11103 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11104 && width > 0 && extent > 0) { 11105 final int newX = Math.round((range - extent) 11106 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11107 if (newX != getScrollX()) { 11108 mScrollCache.mScrollBarDraggingPos = x; 11109 setScrollX(newX); 11110 } 11111 } 11112 return true; 11113 } 11114 case MotionEvent.ACTION_DOWN: 11115 if (mScrollCache.state == ScrollabilityCache.OFF) { 11116 return false; 11117 } 11118 if (isOnVerticalScrollbarThumb(x, y)) { 11119 mScrollCache.mScrollBarDraggingState = 11120 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11121 mScrollCache.mScrollBarDraggingPos = y; 11122 return true; 11123 } 11124 if (isOnHorizontalScrollbarThumb(x, y)) { 11125 mScrollCache.mScrollBarDraggingState = 11126 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11127 mScrollCache.mScrollBarDraggingPos = x; 11128 return true; 11129 } 11130 } 11131 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11132 return false; 11133 } 11134 11135 /** 11136 * Implement this method to handle touch screen motion events. 11137 * <p> 11138 * If this method is used to detect click actions, it is recommended that 11139 * the actions be performed by implementing and calling 11140 * {@link #performClick()}. This will ensure consistent system behavior, 11141 * including: 11142 * <ul> 11143 * <li>obeying click sound preferences 11144 * <li>dispatching OnClickListener calls 11145 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11146 * accessibility features are enabled 11147 * </ul> 11148 * 11149 * @param event The motion event. 11150 * @return True if the event was handled, false otherwise. 11151 */ 11152 public boolean onTouchEvent(MotionEvent event) { 11153 final float x = event.getX(); 11154 final float y = event.getY(); 11155 final int viewFlags = mViewFlags; 11156 final int action = event.getAction(); 11157 11158 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11159 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11160 setPressed(false); 11161 } 11162 // A disabled view that is clickable still consumes the touch 11163 // events, it just doesn't respond to them. 11164 return (((viewFlags & CLICKABLE) == CLICKABLE 11165 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11166 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11167 } 11168 if (mTouchDelegate != null) { 11169 if (mTouchDelegate.onTouchEvent(event)) { 11170 return true; 11171 } 11172 } 11173 11174 if (((viewFlags & CLICKABLE) == CLICKABLE || 11175 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11176 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11177 switch (action) { 11178 case MotionEvent.ACTION_UP: 11179 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11180 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11181 // take focus if we don't have it already and we should in 11182 // touch mode. 11183 boolean focusTaken = false; 11184 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11185 focusTaken = requestFocus(); 11186 } 11187 11188 if (prepressed) { 11189 // The button is being released before we actually 11190 // showed it as pressed. Make it show the pressed 11191 // state now (before scheduling the click) to ensure 11192 // the user sees it. 11193 setPressed(true, x, y); 11194 } 11195 11196 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11197 // This is a tap, so remove the longpress check 11198 removeLongPressCallback(); 11199 11200 // Only perform take click actions if we were in the pressed state 11201 if (!focusTaken) { 11202 // Use a Runnable and post this rather than calling 11203 // performClick directly. This lets other visual state 11204 // of the view update before click actions start. 11205 if (mPerformClick == null) { 11206 mPerformClick = new PerformClick(); 11207 } 11208 if (!post(mPerformClick)) { 11209 performClick(); 11210 } 11211 } 11212 } 11213 11214 if (mUnsetPressedState == null) { 11215 mUnsetPressedState = new UnsetPressedState(); 11216 } 11217 11218 if (prepressed) { 11219 postDelayed(mUnsetPressedState, 11220 ViewConfiguration.getPressedStateDuration()); 11221 } else if (!post(mUnsetPressedState)) { 11222 // If the post failed, unpress right now 11223 mUnsetPressedState.run(); 11224 } 11225 11226 removeTapCallback(); 11227 } 11228 mIgnoreNextUpEvent = false; 11229 break; 11230 11231 case MotionEvent.ACTION_DOWN: 11232 mHasPerformedLongPress = false; 11233 11234 if (performButtonActionOnTouchDown(event)) { 11235 break; 11236 } 11237 11238 // Walk up the hierarchy to determine if we're inside a scrolling container. 11239 boolean isInScrollingContainer = isInScrollingContainer(); 11240 11241 // For views inside a scrolling container, delay the pressed feedback for 11242 // a short period in case this is a scroll. 11243 if (isInScrollingContainer) { 11244 mPrivateFlags |= PFLAG_PREPRESSED; 11245 if (mPendingCheckForTap == null) { 11246 mPendingCheckForTap = new CheckForTap(); 11247 } 11248 mPendingCheckForTap.x = event.getX(); 11249 mPendingCheckForTap.y = event.getY(); 11250 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11251 } else { 11252 // Not inside a scrolling container, so show the feedback right away 11253 setPressed(true, x, y); 11254 checkForLongClick(0, x, y); 11255 } 11256 break; 11257 11258 case MotionEvent.ACTION_CANCEL: 11259 setPressed(false); 11260 removeTapCallback(); 11261 removeLongPressCallback(); 11262 mInContextButtonPress = false; 11263 mHasPerformedLongPress = false; 11264 mIgnoreNextUpEvent = false; 11265 break; 11266 11267 case MotionEvent.ACTION_MOVE: 11268 drawableHotspotChanged(x, y); 11269 11270 // Be lenient about moving outside of buttons 11271 if (!pointInView(x, y, mTouchSlop)) { 11272 // Outside button 11273 removeTapCallback(); 11274 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11275 // Remove any future long press/tap checks 11276 removeLongPressCallback(); 11277 11278 setPressed(false); 11279 } 11280 } 11281 break; 11282 } 11283 11284 return true; 11285 } 11286 11287 return false; 11288 } 11289 11290 /** 11291 * @hide 11292 */ 11293 public boolean isInScrollingContainer() { 11294 ViewParent p = getParent(); 11295 while (p != null && p instanceof ViewGroup) { 11296 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11297 return true; 11298 } 11299 p = p.getParent(); 11300 } 11301 return false; 11302 } 11303 11304 /** 11305 * Remove the longpress detection timer. 11306 */ 11307 private void removeLongPressCallback() { 11308 if (mPendingCheckForLongPress != null) { 11309 removeCallbacks(mPendingCheckForLongPress); 11310 } 11311 } 11312 11313 /** 11314 * Remove the pending click action 11315 */ 11316 private void removePerformClickCallback() { 11317 if (mPerformClick != null) { 11318 removeCallbacks(mPerformClick); 11319 } 11320 } 11321 11322 /** 11323 * Remove the prepress detection timer. 11324 */ 11325 private void removeUnsetPressCallback() { 11326 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11327 setPressed(false); 11328 removeCallbacks(mUnsetPressedState); 11329 } 11330 } 11331 11332 /** 11333 * Remove the tap detection timer. 11334 */ 11335 private void removeTapCallback() { 11336 if (mPendingCheckForTap != null) { 11337 mPrivateFlags &= ~PFLAG_PREPRESSED; 11338 removeCallbacks(mPendingCheckForTap); 11339 } 11340 } 11341 11342 /** 11343 * Cancels a pending long press. Your subclass can use this if you 11344 * want the context menu to come up if the user presses and holds 11345 * at the same place, but you don't want it to come up if they press 11346 * and then move around enough to cause scrolling. 11347 */ 11348 public void cancelLongPress() { 11349 removeLongPressCallback(); 11350 11351 /* 11352 * The prepressed state handled by the tap callback is a display 11353 * construct, but the tap callback will post a long press callback 11354 * less its own timeout. Remove it here. 11355 */ 11356 removeTapCallback(); 11357 } 11358 11359 /** 11360 * Remove the pending callback for sending a 11361 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11362 */ 11363 private void removeSendViewScrolledAccessibilityEventCallback() { 11364 if (mSendViewScrolledAccessibilityEvent != null) { 11365 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11366 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11367 } 11368 } 11369 11370 /** 11371 * Sets the TouchDelegate for this View. 11372 */ 11373 public void setTouchDelegate(TouchDelegate delegate) { 11374 mTouchDelegate = delegate; 11375 } 11376 11377 /** 11378 * Gets the TouchDelegate for this View. 11379 */ 11380 public TouchDelegate getTouchDelegate() { 11381 return mTouchDelegate; 11382 } 11383 11384 /** 11385 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11386 * 11387 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11388 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11389 * available. This method should only be called for touch events. 11390 * 11391 * <p class="note">This api is not intended for most applications. Buffered dispatch 11392 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11393 * streams will not improve your input latency. Side effects include: increased latency, 11394 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11395 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11396 * you.</p> 11397 */ 11398 public final void requestUnbufferedDispatch(MotionEvent event) { 11399 final int action = event.getAction(); 11400 if (mAttachInfo == null 11401 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11402 || !event.isTouchEvent()) { 11403 return; 11404 } 11405 mAttachInfo.mUnbufferedDispatchRequested = true; 11406 } 11407 11408 /** 11409 * Set flags controlling behavior of this view. 11410 * 11411 * @param flags Constant indicating the value which should be set 11412 * @param mask Constant indicating the bit range that should be changed 11413 */ 11414 void setFlags(int flags, int mask) { 11415 final boolean accessibilityEnabled = 11416 AccessibilityManager.getInstance(mContext).isEnabled(); 11417 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11418 11419 int old = mViewFlags; 11420 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11421 11422 int changed = mViewFlags ^ old; 11423 if (changed == 0) { 11424 return; 11425 } 11426 int privateFlags = mPrivateFlags; 11427 11428 /* Check if the FOCUSABLE bit has changed */ 11429 if (((changed & FOCUSABLE_MASK) != 0) && 11430 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11431 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11432 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11433 /* Give up focus if we are no longer focusable */ 11434 clearFocus(); 11435 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11436 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11437 /* 11438 * Tell the view system that we are now available to take focus 11439 * if no one else already has it. 11440 */ 11441 if (mParent != null) mParent.focusableViewAvailable(this); 11442 } 11443 } 11444 11445 final int newVisibility = flags & VISIBILITY_MASK; 11446 if (newVisibility == VISIBLE) { 11447 if ((changed & VISIBILITY_MASK) != 0) { 11448 /* 11449 * If this view is becoming visible, invalidate it in case it changed while 11450 * it was not visible. Marking it drawn ensures that the invalidation will 11451 * go through. 11452 */ 11453 mPrivateFlags |= PFLAG_DRAWN; 11454 invalidate(true); 11455 11456 needGlobalAttributesUpdate(true); 11457 11458 // a view becoming visible is worth notifying the parent 11459 // about in case nothing has focus. even if this specific view 11460 // isn't focusable, it may contain something that is, so let 11461 // the root view try to give this focus if nothing else does. 11462 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11463 mParent.focusableViewAvailable(this); 11464 } 11465 } 11466 } 11467 11468 /* Check if the GONE bit has changed */ 11469 if ((changed & GONE) != 0) { 11470 needGlobalAttributesUpdate(false); 11471 requestLayout(); 11472 11473 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11474 if (hasFocus()) clearFocus(); 11475 clearAccessibilityFocus(); 11476 destroyDrawingCache(); 11477 if (mParent instanceof View) { 11478 // GONE views noop invalidation, so invalidate the parent 11479 ((View) mParent).invalidate(true); 11480 } 11481 // Mark the view drawn to ensure that it gets invalidated properly the next 11482 // time it is visible and gets invalidated 11483 mPrivateFlags |= PFLAG_DRAWN; 11484 } 11485 if (mAttachInfo != null) { 11486 mAttachInfo.mViewVisibilityChanged = true; 11487 } 11488 } 11489 11490 /* Check if the VISIBLE bit has changed */ 11491 if ((changed & INVISIBLE) != 0) { 11492 needGlobalAttributesUpdate(false); 11493 /* 11494 * If this view is becoming invisible, set the DRAWN flag so that 11495 * the next invalidate() will not be skipped. 11496 */ 11497 mPrivateFlags |= PFLAG_DRAWN; 11498 11499 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11500 // root view becoming invisible shouldn't clear focus and accessibility focus 11501 if (getRootView() != this) { 11502 if (hasFocus()) clearFocus(); 11503 clearAccessibilityFocus(); 11504 } 11505 } 11506 if (mAttachInfo != null) { 11507 mAttachInfo.mViewVisibilityChanged = true; 11508 } 11509 } 11510 11511 if ((changed & VISIBILITY_MASK) != 0) { 11512 // If the view is invisible, cleanup its display list to free up resources 11513 if (newVisibility != VISIBLE && mAttachInfo != null) { 11514 cleanupDraw(); 11515 } 11516 11517 if (mParent instanceof ViewGroup) { 11518 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11519 (changed & VISIBILITY_MASK), newVisibility); 11520 ((View) mParent).invalidate(true); 11521 } else if (mParent != null) { 11522 mParent.invalidateChild(this, null); 11523 } 11524 11525 if (mAttachInfo != null) { 11526 dispatchVisibilityChanged(this, newVisibility); 11527 11528 // Aggregated visibility changes are dispatched to attached views 11529 // in visible windows where the parent is currently shown/drawn 11530 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11531 // discounting clipping or overlapping. This makes it a good place 11532 // to change animation states. 11533 if (mParent != null && getWindowVisibility() == VISIBLE && 11534 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11535 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11536 } 11537 notifySubtreeAccessibilityStateChangedIfNeeded(); 11538 } 11539 } 11540 11541 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11542 destroyDrawingCache(); 11543 } 11544 11545 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11546 destroyDrawingCache(); 11547 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11548 invalidateParentCaches(); 11549 } 11550 11551 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11552 destroyDrawingCache(); 11553 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11554 } 11555 11556 if ((changed & DRAW_MASK) != 0) { 11557 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11558 if (mBackground != null 11559 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11560 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11561 } else { 11562 mPrivateFlags |= PFLAG_SKIP_DRAW; 11563 } 11564 } else { 11565 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11566 } 11567 requestLayout(); 11568 invalidate(true); 11569 } 11570 11571 if ((changed & KEEP_SCREEN_ON) != 0) { 11572 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11573 mParent.recomputeViewAttributes(this); 11574 } 11575 } 11576 11577 if (accessibilityEnabled) { 11578 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11579 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11580 || (changed & CONTEXT_CLICKABLE) != 0) { 11581 if (oldIncludeForAccessibility != includeForAccessibility()) { 11582 notifySubtreeAccessibilityStateChangedIfNeeded(); 11583 } else { 11584 notifyViewAccessibilityStateChangedIfNeeded( 11585 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11586 } 11587 } else if ((changed & ENABLED_MASK) != 0) { 11588 notifyViewAccessibilityStateChangedIfNeeded( 11589 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11590 } 11591 } 11592 } 11593 11594 /** 11595 * Change the view's z order in the tree, so it's on top of other sibling 11596 * views. This ordering change may affect layout, if the parent container 11597 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11598 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11599 * method should be followed by calls to {@link #requestLayout()} and 11600 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11601 * with the new child ordering. 11602 * 11603 * @see ViewGroup#bringChildToFront(View) 11604 */ 11605 public void bringToFront() { 11606 if (mParent != null) { 11607 mParent.bringChildToFront(this); 11608 } 11609 } 11610 11611 /** 11612 * This is called in response to an internal scroll in this view (i.e., the 11613 * view scrolled its own contents). This is typically as a result of 11614 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11615 * called. 11616 * 11617 * @param l Current horizontal scroll origin. 11618 * @param t Current vertical scroll origin. 11619 * @param oldl Previous horizontal scroll origin. 11620 * @param oldt Previous vertical scroll origin. 11621 */ 11622 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11623 notifySubtreeAccessibilityStateChangedIfNeeded(); 11624 11625 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11626 postSendViewScrolledAccessibilityEventCallback(); 11627 } 11628 11629 mBackgroundSizeChanged = true; 11630 if (mForegroundInfo != null) { 11631 mForegroundInfo.mBoundsChanged = true; 11632 } 11633 11634 final AttachInfo ai = mAttachInfo; 11635 if (ai != null) { 11636 ai.mViewScrollChanged = true; 11637 } 11638 11639 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11640 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11641 } 11642 } 11643 11644 /** 11645 * Interface definition for a callback to be invoked when the scroll 11646 * X or Y positions of a view change. 11647 * <p> 11648 * <b>Note:</b> Some views handle scrolling independently from View and may 11649 * have their own separate listeners for scroll-type events. For example, 11650 * {@link android.widget.ListView ListView} allows clients to register an 11651 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11652 * to listen for changes in list scroll position. 11653 * 11654 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11655 */ 11656 public interface OnScrollChangeListener { 11657 /** 11658 * Called when the scroll position of a view changes. 11659 * 11660 * @param v The view whose scroll position has changed. 11661 * @param scrollX Current horizontal scroll origin. 11662 * @param scrollY Current vertical scroll origin. 11663 * @param oldScrollX Previous horizontal scroll origin. 11664 * @param oldScrollY Previous vertical scroll origin. 11665 */ 11666 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11667 } 11668 11669 /** 11670 * Interface definition for a callback to be invoked when the layout bounds of a view 11671 * changes due to layout processing. 11672 */ 11673 public interface OnLayoutChangeListener { 11674 /** 11675 * Called when the layout bounds of a view changes due to layout processing. 11676 * 11677 * @param v The view whose bounds have changed. 11678 * @param left The new value of the view's left property. 11679 * @param top The new value of the view's top property. 11680 * @param right The new value of the view's right property. 11681 * @param bottom The new value of the view's bottom property. 11682 * @param oldLeft The previous value of the view's left property. 11683 * @param oldTop The previous value of the view's top property. 11684 * @param oldRight The previous value of the view's right property. 11685 * @param oldBottom The previous value of the view's bottom property. 11686 */ 11687 void onLayoutChange(View v, int left, int top, int right, int bottom, 11688 int oldLeft, int oldTop, int oldRight, int oldBottom); 11689 } 11690 11691 /** 11692 * This is called during layout when the size of this view has changed. If 11693 * you were just added to the view hierarchy, you're called with the old 11694 * values of 0. 11695 * 11696 * @param w Current width of this view. 11697 * @param h Current height of this view. 11698 * @param oldw Old width of this view. 11699 * @param oldh Old height of this view. 11700 */ 11701 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11702 } 11703 11704 /** 11705 * Called by draw to draw the child views. This may be overridden 11706 * by derived classes to gain control just before its children are drawn 11707 * (but after its own view has been drawn). 11708 * @param canvas the canvas on which to draw the view 11709 */ 11710 protected void dispatchDraw(Canvas canvas) { 11711 11712 } 11713 11714 /** 11715 * Gets the parent of this view. Note that the parent is a 11716 * ViewParent and not necessarily a View. 11717 * 11718 * @return Parent of this view. 11719 */ 11720 public final ViewParent getParent() { 11721 return mParent; 11722 } 11723 11724 /** 11725 * Set the horizontal scrolled position of your view. This will cause a call to 11726 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11727 * invalidated. 11728 * @param value the x position to scroll to 11729 */ 11730 public void setScrollX(int value) { 11731 scrollTo(value, mScrollY); 11732 } 11733 11734 /** 11735 * Set the vertical scrolled position of your view. This will cause a call to 11736 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11737 * invalidated. 11738 * @param value the y position to scroll to 11739 */ 11740 public void setScrollY(int value) { 11741 scrollTo(mScrollX, value); 11742 } 11743 11744 /** 11745 * Return the scrolled left position of this view. This is the left edge of 11746 * the displayed part of your view. You do not need to draw any pixels 11747 * farther left, since those are outside of the frame of your view on 11748 * screen. 11749 * 11750 * @return The left edge of the displayed part of your view, in pixels. 11751 */ 11752 public final int getScrollX() { 11753 return mScrollX; 11754 } 11755 11756 /** 11757 * Return the scrolled top position of this view. This is the top edge of 11758 * the displayed part of your view. You do not need to draw any pixels above 11759 * it, since those are outside of the frame of your view on screen. 11760 * 11761 * @return The top edge of the displayed part of your view, in pixels. 11762 */ 11763 public final int getScrollY() { 11764 return mScrollY; 11765 } 11766 11767 /** 11768 * Return the width of the your view. 11769 * 11770 * @return The width of your view, in pixels. 11771 */ 11772 @ViewDebug.ExportedProperty(category = "layout") 11773 public final int getWidth() { 11774 return mRight - mLeft; 11775 } 11776 11777 /** 11778 * Return the height of your view. 11779 * 11780 * @return The height of your view, in pixels. 11781 */ 11782 @ViewDebug.ExportedProperty(category = "layout") 11783 public final int getHeight() { 11784 return mBottom - mTop; 11785 } 11786 11787 /** 11788 * Return the visible drawing bounds of your view. Fills in the output 11789 * rectangle with the values from getScrollX(), getScrollY(), 11790 * getWidth(), and getHeight(). These bounds do not account for any 11791 * transformation properties currently set on the view, such as 11792 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11793 * 11794 * @param outRect The (scrolled) drawing bounds of the view. 11795 */ 11796 public void getDrawingRect(Rect outRect) { 11797 outRect.left = mScrollX; 11798 outRect.top = mScrollY; 11799 outRect.right = mScrollX + (mRight - mLeft); 11800 outRect.bottom = mScrollY + (mBottom - mTop); 11801 } 11802 11803 /** 11804 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11805 * raw width component (that is the result is masked by 11806 * {@link #MEASURED_SIZE_MASK}). 11807 * 11808 * @return The raw measured width of this view. 11809 */ 11810 public final int getMeasuredWidth() { 11811 return mMeasuredWidth & MEASURED_SIZE_MASK; 11812 } 11813 11814 /** 11815 * Return the full width measurement information for this view as computed 11816 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11817 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11818 * This should be used during measurement and layout calculations only. Use 11819 * {@link #getWidth()} to see how wide a view is after layout. 11820 * 11821 * @return The measured width of this view as a bit mask. 11822 */ 11823 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11824 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11825 name = "MEASURED_STATE_TOO_SMALL"), 11826 }) 11827 public final int getMeasuredWidthAndState() { 11828 return mMeasuredWidth; 11829 } 11830 11831 /** 11832 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11833 * raw height component (that is the result is masked by 11834 * {@link #MEASURED_SIZE_MASK}). 11835 * 11836 * @return The raw measured height of this view. 11837 */ 11838 public final int getMeasuredHeight() { 11839 return mMeasuredHeight & MEASURED_SIZE_MASK; 11840 } 11841 11842 /** 11843 * Return the full height measurement information for this view as computed 11844 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11845 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11846 * This should be used during measurement and layout calculations only. Use 11847 * {@link #getHeight()} to see how wide a view is after layout. 11848 * 11849 * @return The measured height of this view as a bit mask. 11850 */ 11851 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11852 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11853 name = "MEASURED_STATE_TOO_SMALL"), 11854 }) 11855 public final int getMeasuredHeightAndState() { 11856 return mMeasuredHeight; 11857 } 11858 11859 /** 11860 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11861 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11862 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11863 * and the height component is at the shifted bits 11864 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11865 */ 11866 public final int getMeasuredState() { 11867 return (mMeasuredWidth&MEASURED_STATE_MASK) 11868 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11869 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11870 } 11871 11872 /** 11873 * The transform matrix of this view, which is calculated based on the current 11874 * rotation, scale, and pivot properties. 11875 * 11876 * @see #getRotation() 11877 * @see #getScaleX() 11878 * @see #getScaleY() 11879 * @see #getPivotX() 11880 * @see #getPivotY() 11881 * @return The current transform matrix for the view 11882 */ 11883 public Matrix getMatrix() { 11884 ensureTransformationInfo(); 11885 final Matrix matrix = mTransformationInfo.mMatrix; 11886 mRenderNode.getMatrix(matrix); 11887 return matrix; 11888 } 11889 11890 /** 11891 * Returns true if the transform matrix is the identity matrix. 11892 * Recomputes the matrix if necessary. 11893 * 11894 * @return True if the transform matrix is the identity matrix, false otherwise. 11895 */ 11896 final boolean hasIdentityMatrix() { 11897 return mRenderNode.hasIdentityMatrix(); 11898 } 11899 11900 void ensureTransformationInfo() { 11901 if (mTransformationInfo == null) { 11902 mTransformationInfo = new TransformationInfo(); 11903 } 11904 } 11905 11906 /** 11907 * Utility method to retrieve the inverse of the current mMatrix property. 11908 * We cache the matrix to avoid recalculating it when transform properties 11909 * have not changed. 11910 * 11911 * @return The inverse of the current matrix of this view. 11912 * @hide 11913 */ 11914 public final Matrix getInverseMatrix() { 11915 ensureTransformationInfo(); 11916 if (mTransformationInfo.mInverseMatrix == null) { 11917 mTransformationInfo.mInverseMatrix = new Matrix(); 11918 } 11919 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11920 mRenderNode.getInverseMatrix(matrix); 11921 return matrix; 11922 } 11923 11924 /** 11925 * Gets the distance along the Z axis from the camera to this view. 11926 * 11927 * @see #setCameraDistance(float) 11928 * 11929 * @return The distance along the Z axis. 11930 */ 11931 public float getCameraDistance() { 11932 final float dpi = mResources.getDisplayMetrics().densityDpi; 11933 return -(mRenderNode.getCameraDistance() * dpi); 11934 } 11935 11936 /** 11937 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11938 * views are drawn) from the camera to this view. The camera's distance 11939 * affects 3D transformations, for instance rotations around the X and Y 11940 * axis. If the rotationX or rotationY properties are changed and this view is 11941 * large (more than half the size of the screen), it is recommended to always 11942 * use a camera distance that's greater than the height (X axis rotation) or 11943 * the width (Y axis rotation) of this view.</p> 11944 * 11945 * <p>The distance of the camera from the view plane can have an affect on the 11946 * perspective distortion of the view when it is rotated around the x or y axis. 11947 * For example, a large distance will result in a large viewing angle, and there 11948 * will not be much perspective distortion of the view as it rotates. A short 11949 * distance may cause much more perspective distortion upon rotation, and can 11950 * also result in some drawing artifacts if the rotated view ends up partially 11951 * behind the camera (which is why the recommendation is to use a distance at 11952 * least as far as the size of the view, if the view is to be rotated.)</p> 11953 * 11954 * <p>The distance is expressed in "depth pixels." The default distance depends 11955 * on the screen density. For instance, on a medium density display, the 11956 * default distance is 1280. On a high density display, the default distance 11957 * is 1920.</p> 11958 * 11959 * <p>If you want to specify a distance that leads to visually consistent 11960 * results across various densities, use the following formula:</p> 11961 * <pre> 11962 * float scale = context.getResources().getDisplayMetrics().density; 11963 * view.setCameraDistance(distance * scale); 11964 * </pre> 11965 * 11966 * <p>The density scale factor of a high density display is 1.5, 11967 * and 1920 = 1280 * 1.5.</p> 11968 * 11969 * @param distance The distance in "depth pixels", if negative the opposite 11970 * value is used 11971 * 11972 * @see #setRotationX(float) 11973 * @see #setRotationY(float) 11974 */ 11975 public void setCameraDistance(float distance) { 11976 final float dpi = mResources.getDisplayMetrics().densityDpi; 11977 11978 invalidateViewProperty(true, false); 11979 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11980 invalidateViewProperty(false, false); 11981 11982 invalidateParentIfNeededAndWasQuickRejected(); 11983 } 11984 11985 /** 11986 * The degrees that the view is rotated around the pivot point. 11987 * 11988 * @see #setRotation(float) 11989 * @see #getPivotX() 11990 * @see #getPivotY() 11991 * 11992 * @return The degrees of rotation. 11993 */ 11994 @ViewDebug.ExportedProperty(category = "drawing") 11995 public float getRotation() { 11996 return mRenderNode.getRotation(); 11997 } 11998 11999 /** 12000 * Sets the degrees that the view is rotated around the pivot point. Increasing values 12001 * result in clockwise rotation. 12002 * 12003 * @param rotation The degrees of rotation. 12004 * 12005 * @see #getRotation() 12006 * @see #getPivotX() 12007 * @see #getPivotY() 12008 * @see #setRotationX(float) 12009 * @see #setRotationY(float) 12010 * 12011 * @attr ref android.R.styleable#View_rotation 12012 */ 12013 public void setRotation(float rotation) { 12014 if (rotation != getRotation()) { 12015 // Double-invalidation is necessary to capture view's old and new areas 12016 invalidateViewProperty(true, false); 12017 mRenderNode.setRotation(rotation); 12018 invalidateViewProperty(false, true); 12019 12020 invalidateParentIfNeededAndWasQuickRejected(); 12021 notifySubtreeAccessibilityStateChangedIfNeeded(); 12022 } 12023 } 12024 12025 /** 12026 * The degrees that the view is rotated around the vertical axis through the pivot point. 12027 * 12028 * @see #getPivotX() 12029 * @see #getPivotY() 12030 * @see #setRotationY(float) 12031 * 12032 * @return The degrees of Y rotation. 12033 */ 12034 @ViewDebug.ExportedProperty(category = "drawing") 12035 public float getRotationY() { 12036 return mRenderNode.getRotationY(); 12037 } 12038 12039 /** 12040 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 12041 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 12042 * down the y axis. 12043 * 12044 * When rotating large views, it is recommended to adjust the camera distance 12045 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12046 * 12047 * @param rotationY The degrees of Y rotation. 12048 * 12049 * @see #getRotationY() 12050 * @see #getPivotX() 12051 * @see #getPivotY() 12052 * @see #setRotation(float) 12053 * @see #setRotationX(float) 12054 * @see #setCameraDistance(float) 12055 * 12056 * @attr ref android.R.styleable#View_rotationY 12057 */ 12058 public void setRotationY(float rotationY) { 12059 if (rotationY != getRotationY()) { 12060 invalidateViewProperty(true, false); 12061 mRenderNode.setRotationY(rotationY); 12062 invalidateViewProperty(false, true); 12063 12064 invalidateParentIfNeededAndWasQuickRejected(); 12065 notifySubtreeAccessibilityStateChangedIfNeeded(); 12066 } 12067 } 12068 12069 /** 12070 * The degrees that the view is rotated around the horizontal axis through the pivot point. 12071 * 12072 * @see #getPivotX() 12073 * @see #getPivotY() 12074 * @see #setRotationX(float) 12075 * 12076 * @return The degrees of X rotation. 12077 */ 12078 @ViewDebug.ExportedProperty(category = "drawing") 12079 public float getRotationX() { 12080 return mRenderNode.getRotationX(); 12081 } 12082 12083 /** 12084 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 12085 * Increasing values result in clockwise rotation from the viewpoint of looking down the 12086 * x axis. 12087 * 12088 * When rotating large views, it is recommended to adjust the camera distance 12089 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12090 * 12091 * @param rotationX The degrees of X rotation. 12092 * 12093 * @see #getRotationX() 12094 * @see #getPivotX() 12095 * @see #getPivotY() 12096 * @see #setRotation(float) 12097 * @see #setRotationY(float) 12098 * @see #setCameraDistance(float) 12099 * 12100 * @attr ref android.R.styleable#View_rotationX 12101 */ 12102 public void setRotationX(float rotationX) { 12103 if (rotationX != getRotationX()) { 12104 invalidateViewProperty(true, false); 12105 mRenderNode.setRotationX(rotationX); 12106 invalidateViewProperty(false, true); 12107 12108 invalidateParentIfNeededAndWasQuickRejected(); 12109 notifySubtreeAccessibilityStateChangedIfNeeded(); 12110 } 12111 } 12112 12113 /** 12114 * The amount that the view is scaled in x around the pivot point, as a proportion of 12115 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12116 * 12117 * <p>By default, this is 1.0f. 12118 * 12119 * @see #getPivotX() 12120 * @see #getPivotY() 12121 * @return The scaling factor. 12122 */ 12123 @ViewDebug.ExportedProperty(category = "drawing") 12124 public float getScaleX() { 12125 return mRenderNode.getScaleX(); 12126 } 12127 12128 /** 12129 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12130 * the view's unscaled width. A value of 1 means that no scaling is applied. 12131 * 12132 * @param scaleX The scaling factor. 12133 * @see #getPivotX() 12134 * @see #getPivotY() 12135 * 12136 * @attr ref android.R.styleable#View_scaleX 12137 */ 12138 public void setScaleX(float scaleX) { 12139 if (scaleX != getScaleX()) { 12140 invalidateViewProperty(true, false); 12141 mRenderNode.setScaleX(scaleX); 12142 invalidateViewProperty(false, true); 12143 12144 invalidateParentIfNeededAndWasQuickRejected(); 12145 notifySubtreeAccessibilityStateChangedIfNeeded(); 12146 } 12147 } 12148 12149 /** 12150 * The amount that the view is scaled in y around the pivot point, as a proportion of 12151 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12152 * 12153 * <p>By default, this is 1.0f. 12154 * 12155 * @see #getPivotX() 12156 * @see #getPivotY() 12157 * @return The scaling factor. 12158 */ 12159 @ViewDebug.ExportedProperty(category = "drawing") 12160 public float getScaleY() { 12161 return mRenderNode.getScaleY(); 12162 } 12163 12164 /** 12165 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12166 * the view's unscaled width. A value of 1 means that no scaling is applied. 12167 * 12168 * @param scaleY The scaling factor. 12169 * @see #getPivotX() 12170 * @see #getPivotY() 12171 * 12172 * @attr ref android.R.styleable#View_scaleY 12173 */ 12174 public void setScaleY(float scaleY) { 12175 if (scaleY != getScaleY()) { 12176 invalidateViewProperty(true, false); 12177 mRenderNode.setScaleY(scaleY); 12178 invalidateViewProperty(false, true); 12179 12180 invalidateParentIfNeededAndWasQuickRejected(); 12181 notifySubtreeAccessibilityStateChangedIfNeeded(); 12182 } 12183 } 12184 12185 /** 12186 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12187 * and {@link #setScaleX(float) scaled}. 12188 * 12189 * @see #getRotation() 12190 * @see #getScaleX() 12191 * @see #getScaleY() 12192 * @see #getPivotY() 12193 * @return The x location of the pivot point. 12194 * 12195 * @attr ref android.R.styleable#View_transformPivotX 12196 */ 12197 @ViewDebug.ExportedProperty(category = "drawing") 12198 public float getPivotX() { 12199 return mRenderNode.getPivotX(); 12200 } 12201 12202 /** 12203 * Sets the x location of the point around which the view is 12204 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12205 * By default, the pivot point is centered on the object. 12206 * Setting this property disables this behavior and causes the view to use only the 12207 * explicitly set pivotX and pivotY values. 12208 * 12209 * @param pivotX The x location of the pivot point. 12210 * @see #getRotation() 12211 * @see #getScaleX() 12212 * @see #getScaleY() 12213 * @see #getPivotY() 12214 * 12215 * @attr ref android.R.styleable#View_transformPivotX 12216 */ 12217 public void setPivotX(float pivotX) { 12218 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12219 invalidateViewProperty(true, false); 12220 mRenderNode.setPivotX(pivotX); 12221 invalidateViewProperty(false, true); 12222 12223 invalidateParentIfNeededAndWasQuickRejected(); 12224 } 12225 } 12226 12227 /** 12228 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12229 * and {@link #setScaleY(float) scaled}. 12230 * 12231 * @see #getRotation() 12232 * @see #getScaleX() 12233 * @see #getScaleY() 12234 * @see #getPivotY() 12235 * @return The y location of the pivot point. 12236 * 12237 * @attr ref android.R.styleable#View_transformPivotY 12238 */ 12239 @ViewDebug.ExportedProperty(category = "drawing") 12240 public float getPivotY() { 12241 return mRenderNode.getPivotY(); 12242 } 12243 12244 /** 12245 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12246 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12247 * Setting this property disables this behavior and causes the view to use only the 12248 * explicitly set pivotX and pivotY values. 12249 * 12250 * @param pivotY The y location of the pivot point. 12251 * @see #getRotation() 12252 * @see #getScaleX() 12253 * @see #getScaleY() 12254 * @see #getPivotY() 12255 * 12256 * @attr ref android.R.styleable#View_transformPivotY 12257 */ 12258 public void setPivotY(float pivotY) { 12259 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12260 invalidateViewProperty(true, false); 12261 mRenderNode.setPivotY(pivotY); 12262 invalidateViewProperty(false, true); 12263 12264 invalidateParentIfNeededAndWasQuickRejected(); 12265 } 12266 } 12267 12268 /** 12269 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12270 * completely transparent and 1 means the view is completely opaque. 12271 * 12272 * <p>By default this is 1.0f. 12273 * @return The opacity of the view. 12274 */ 12275 @ViewDebug.ExportedProperty(category = "drawing") 12276 public float getAlpha() { 12277 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12278 } 12279 12280 /** 12281 * Sets the behavior for overlapping rendering for this view (see {@link 12282 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12283 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12284 * providing the value which is then used internally. That is, when {@link 12285 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12286 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12287 * instead. 12288 * 12289 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12290 * instead of that returned by {@link #hasOverlappingRendering()}. 12291 * 12292 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12293 */ 12294 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12295 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12296 if (hasOverlappingRendering) { 12297 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12298 } else { 12299 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12300 } 12301 } 12302 12303 /** 12304 * Returns the value for overlapping rendering that is used internally. This is either 12305 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12306 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12307 * 12308 * @return The value for overlapping rendering being used internally. 12309 */ 12310 public final boolean getHasOverlappingRendering() { 12311 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12312 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12313 hasOverlappingRendering(); 12314 } 12315 12316 /** 12317 * Returns whether this View has content which overlaps. 12318 * 12319 * <p>This function, intended to be overridden by specific View types, is an optimization when 12320 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12321 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12322 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12323 * directly. An example of overlapping rendering is a TextView with a background image, such as 12324 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12325 * ImageView with only the foreground image. The default implementation returns true; subclasses 12326 * should override if they have cases which can be optimized.</p> 12327 * 12328 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12329 * necessitates that a View return true if it uses the methods internally without passing the 12330 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12331 * 12332 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12333 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12334 * 12335 * @return true if the content in this view might overlap, false otherwise. 12336 */ 12337 @ViewDebug.ExportedProperty(category = "drawing") 12338 public boolean hasOverlappingRendering() { 12339 return true; 12340 } 12341 12342 /** 12343 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12344 * completely transparent and 1 means the view is completely opaque. 12345 * 12346 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12347 * can have significant performance implications, especially for large views. It is best to use 12348 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12349 * 12350 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12351 * strongly recommended for performance reasons to either override 12352 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12353 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12354 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12355 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12356 * of rendering cost, even for simple or small views. Starting with 12357 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12358 * applied to the view at the rendering level.</p> 12359 * 12360 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12361 * responsible for applying the opacity itself.</p> 12362 * 12363 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12364 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12365 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12366 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12367 * 12368 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12369 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12370 * {@link #hasOverlappingRendering}.</p> 12371 * 12372 * @param alpha The opacity of the view. 12373 * 12374 * @see #hasOverlappingRendering() 12375 * @see #setLayerType(int, android.graphics.Paint) 12376 * 12377 * @attr ref android.R.styleable#View_alpha 12378 */ 12379 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12380 ensureTransformationInfo(); 12381 if (mTransformationInfo.mAlpha != alpha) { 12382 // Report visibility changes, which can affect children, to accessibility 12383 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 12384 notifySubtreeAccessibilityStateChangedIfNeeded(); 12385 } 12386 mTransformationInfo.mAlpha = alpha; 12387 if (onSetAlpha((int) (alpha * 255))) { 12388 mPrivateFlags |= PFLAG_ALPHA_SET; 12389 // subclass is handling alpha - don't optimize rendering cache invalidation 12390 invalidateParentCaches(); 12391 invalidate(true); 12392 } else { 12393 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12394 invalidateViewProperty(true, false); 12395 mRenderNode.setAlpha(getFinalAlpha()); 12396 } 12397 } 12398 } 12399 12400 /** 12401 * Faster version of setAlpha() which performs the same steps except there are 12402 * no calls to invalidate(). The caller of this function should perform proper invalidation 12403 * on the parent and this object. The return value indicates whether the subclass handles 12404 * alpha (the return value for onSetAlpha()). 12405 * 12406 * @param alpha The new value for the alpha property 12407 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12408 * the new value for the alpha property is different from the old value 12409 */ 12410 boolean setAlphaNoInvalidation(float alpha) { 12411 ensureTransformationInfo(); 12412 if (mTransformationInfo.mAlpha != alpha) { 12413 mTransformationInfo.mAlpha = alpha; 12414 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12415 if (subclassHandlesAlpha) { 12416 mPrivateFlags |= PFLAG_ALPHA_SET; 12417 return true; 12418 } else { 12419 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12420 mRenderNode.setAlpha(getFinalAlpha()); 12421 } 12422 } 12423 return false; 12424 } 12425 12426 /** 12427 * This property is hidden and intended only for use by the Fade transition, which 12428 * animates it to produce a visual translucency that does not side-effect (or get 12429 * affected by) the real alpha property. This value is composited with the other 12430 * alpha value (and the AlphaAnimation value, when that is present) to produce 12431 * a final visual translucency result, which is what is passed into the DisplayList. 12432 * 12433 * @hide 12434 */ 12435 public void setTransitionAlpha(float alpha) { 12436 ensureTransformationInfo(); 12437 if (mTransformationInfo.mTransitionAlpha != alpha) { 12438 mTransformationInfo.mTransitionAlpha = alpha; 12439 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12440 invalidateViewProperty(true, false); 12441 mRenderNode.setAlpha(getFinalAlpha()); 12442 } 12443 } 12444 12445 /** 12446 * Calculates the visual alpha of this view, which is a combination of the actual 12447 * alpha value and the transitionAlpha value (if set). 12448 */ 12449 private float getFinalAlpha() { 12450 if (mTransformationInfo != null) { 12451 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12452 } 12453 return 1; 12454 } 12455 12456 /** 12457 * This property is hidden and intended only for use by the Fade transition, which 12458 * animates it to produce a visual translucency that does not side-effect (or get 12459 * affected by) the real alpha property. This value is composited with the other 12460 * alpha value (and the AlphaAnimation value, when that is present) to produce 12461 * a final visual translucency result, which is what is passed into the DisplayList. 12462 * 12463 * @hide 12464 */ 12465 @ViewDebug.ExportedProperty(category = "drawing") 12466 public float getTransitionAlpha() { 12467 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12468 } 12469 12470 /** 12471 * Top position of this view relative to its parent. 12472 * 12473 * @return The top of this view, in pixels. 12474 */ 12475 @ViewDebug.CapturedViewProperty 12476 public final int getTop() { 12477 return mTop; 12478 } 12479 12480 /** 12481 * Sets the top position of this view relative to its parent. This method is meant to be called 12482 * by the layout system and should not generally be called otherwise, because the property 12483 * may be changed at any time by the layout. 12484 * 12485 * @param top The top of this view, in pixels. 12486 */ 12487 public final void setTop(int top) { 12488 if (top != mTop) { 12489 final boolean matrixIsIdentity = hasIdentityMatrix(); 12490 if (matrixIsIdentity) { 12491 if (mAttachInfo != null) { 12492 int minTop; 12493 int yLoc; 12494 if (top < mTop) { 12495 minTop = top; 12496 yLoc = top - mTop; 12497 } else { 12498 minTop = mTop; 12499 yLoc = 0; 12500 } 12501 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12502 } 12503 } else { 12504 // Double-invalidation is necessary to capture view's old and new areas 12505 invalidate(true); 12506 } 12507 12508 int width = mRight - mLeft; 12509 int oldHeight = mBottom - mTop; 12510 12511 mTop = top; 12512 mRenderNode.setTop(mTop); 12513 12514 sizeChange(width, mBottom - mTop, width, oldHeight); 12515 12516 if (!matrixIsIdentity) { 12517 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12518 invalidate(true); 12519 } 12520 mBackgroundSizeChanged = true; 12521 if (mForegroundInfo != null) { 12522 mForegroundInfo.mBoundsChanged = true; 12523 } 12524 invalidateParentIfNeeded(); 12525 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12526 // View was rejected last time it was drawn by its parent; this may have changed 12527 invalidateParentIfNeeded(); 12528 } 12529 } 12530 } 12531 12532 /** 12533 * Bottom position of this view relative to its parent. 12534 * 12535 * @return The bottom of this view, in pixels. 12536 */ 12537 @ViewDebug.CapturedViewProperty 12538 public final int getBottom() { 12539 return mBottom; 12540 } 12541 12542 /** 12543 * True if this view has changed since the last time being drawn. 12544 * 12545 * @return The dirty state of this view. 12546 */ 12547 public boolean isDirty() { 12548 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12549 } 12550 12551 /** 12552 * Sets the bottom position of this view relative to its parent. This method is meant to be 12553 * called by the layout system and should not generally be called otherwise, because the 12554 * property may be changed at any time by the layout. 12555 * 12556 * @param bottom The bottom of this view, in pixels. 12557 */ 12558 public final void setBottom(int bottom) { 12559 if (bottom != mBottom) { 12560 final boolean matrixIsIdentity = hasIdentityMatrix(); 12561 if (matrixIsIdentity) { 12562 if (mAttachInfo != null) { 12563 int maxBottom; 12564 if (bottom < mBottom) { 12565 maxBottom = mBottom; 12566 } else { 12567 maxBottom = bottom; 12568 } 12569 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12570 } 12571 } else { 12572 // Double-invalidation is necessary to capture view's old and new areas 12573 invalidate(true); 12574 } 12575 12576 int width = mRight - mLeft; 12577 int oldHeight = mBottom - mTop; 12578 12579 mBottom = bottom; 12580 mRenderNode.setBottom(mBottom); 12581 12582 sizeChange(width, mBottom - mTop, width, oldHeight); 12583 12584 if (!matrixIsIdentity) { 12585 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12586 invalidate(true); 12587 } 12588 mBackgroundSizeChanged = true; 12589 if (mForegroundInfo != null) { 12590 mForegroundInfo.mBoundsChanged = true; 12591 } 12592 invalidateParentIfNeeded(); 12593 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12594 // View was rejected last time it was drawn by its parent; this may have changed 12595 invalidateParentIfNeeded(); 12596 } 12597 } 12598 } 12599 12600 /** 12601 * Left position of this view relative to its parent. 12602 * 12603 * @return The left edge of this view, in pixels. 12604 */ 12605 @ViewDebug.CapturedViewProperty 12606 public final int getLeft() { 12607 return mLeft; 12608 } 12609 12610 /** 12611 * Sets the left position of this view relative to its parent. This method is meant to be called 12612 * by the layout system and should not generally be called otherwise, because the property 12613 * may be changed at any time by the layout. 12614 * 12615 * @param left The left of this view, in pixels. 12616 */ 12617 public final void setLeft(int left) { 12618 if (left != mLeft) { 12619 final boolean matrixIsIdentity = hasIdentityMatrix(); 12620 if (matrixIsIdentity) { 12621 if (mAttachInfo != null) { 12622 int minLeft; 12623 int xLoc; 12624 if (left < mLeft) { 12625 minLeft = left; 12626 xLoc = left - mLeft; 12627 } else { 12628 minLeft = mLeft; 12629 xLoc = 0; 12630 } 12631 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12632 } 12633 } else { 12634 // Double-invalidation is necessary to capture view's old and new areas 12635 invalidate(true); 12636 } 12637 12638 int oldWidth = mRight - mLeft; 12639 int height = mBottom - mTop; 12640 12641 mLeft = left; 12642 mRenderNode.setLeft(left); 12643 12644 sizeChange(mRight - mLeft, height, oldWidth, height); 12645 12646 if (!matrixIsIdentity) { 12647 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12648 invalidate(true); 12649 } 12650 mBackgroundSizeChanged = true; 12651 if (mForegroundInfo != null) { 12652 mForegroundInfo.mBoundsChanged = true; 12653 } 12654 invalidateParentIfNeeded(); 12655 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12656 // View was rejected last time it was drawn by its parent; this may have changed 12657 invalidateParentIfNeeded(); 12658 } 12659 } 12660 } 12661 12662 /** 12663 * Right position of this view relative to its parent. 12664 * 12665 * @return The right edge of this view, in pixels. 12666 */ 12667 @ViewDebug.CapturedViewProperty 12668 public final int getRight() { 12669 return mRight; 12670 } 12671 12672 /** 12673 * Sets the right position of this view relative to its parent. This method is meant to be called 12674 * by the layout system and should not generally be called otherwise, because the property 12675 * may be changed at any time by the layout. 12676 * 12677 * @param right The right of this view, in pixels. 12678 */ 12679 public final void setRight(int right) { 12680 if (right != mRight) { 12681 final boolean matrixIsIdentity = hasIdentityMatrix(); 12682 if (matrixIsIdentity) { 12683 if (mAttachInfo != null) { 12684 int maxRight; 12685 if (right < mRight) { 12686 maxRight = mRight; 12687 } else { 12688 maxRight = right; 12689 } 12690 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12691 } 12692 } else { 12693 // Double-invalidation is necessary to capture view's old and new areas 12694 invalidate(true); 12695 } 12696 12697 int oldWidth = mRight - mLeft; 12698 int height = mBottom - mTop; 12699 12700 mRight = right; 12701 mRenderNode.setRight(mRight); 12702 12703 sizeChange(mRight - mLeft, height, oldWidth, height); 12704 12705 if (!matrixIsIdentity) { 12706 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12707 invalidate(true); 12708 } 12709 mBackgroundSizeChanged = true; 12710 if (mForegroundInfo != null) { 12711 mForegroundInfo.mBoundsChanged = true; 12712 } 12713 invalidateParentIfNeeded(); 12714 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12715 // View was rejected last time it was drawn by its parent; this may have changed 12716 invalidateParentIfNeeded(); 12717 } 12718 } 12719 } 12720 12721 /** 12722 * The visual x position of this view, in pixels. This is equivalent to the 12723 * {@link #setTranslationX(float) translationX} property plus the current 12724 * {@link #getLeft() left} property. 12725 * 12726 * @return The visual x position of this view, in pixels. 12727 */ 12728 @ViewDebug.ExportedProperty(category = "drawing") 12729 public float getX() { 12730 return mLeft + getTranslationX(); 12731 } 12732 12733 /** 12734 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12735 * {@link #setTranslationX(float) translationX} property to be the difference between 12736 * the x value passed in and the current {@link #getLeft() left} property. 12737 * 12738 * @param x The visual x position of this view, in pixels. 12739 */ 12740 public void setX(float x) { 12741 setTranslationX(x - mLeft); 12742 } 12743 12744 /** 12745 * The visual y position of this view, in pixels. This is equivalent to the 12746 * {@link #setTranslationY(float) translationY} property plus the current 12747 * {@link #getTop() top} property. 12748 * 12749 * @return The visual y position of this view, in pixels. 12750 */ 12751 @ViewDebug.ExportedProperty(category = "drawing") 12752 public float getY() { 12753 return mTop + getTranslationY(); 12754 } 12755 12756 /** 12757 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12758 * {@link #setTranslationY(float) translationY} property to be the difference between 12759 * the y value passed in and the current {@link #getTop() top} property. 12760 * 12761 * @param y The visual y position of this view, in pixels. 12762 */ 12763 public void setY(float y) { 12764 setTranslationY(y - mTop); 12765 } 12766 12767 /** 12768 * The visual z position of this view, in pixels. This is equivalent to the 12769 * {@link #setTranslationZ(float) translationZ} property plus the current 12770 * {@link #getElevation() elevation} property. 12771 * 12772 * @return The visual z position of this view, in pixels. 12773 */ 12774 @ViewDebug.ExportedProperty(category = "drawing") 12775 public float getZ() { 12776 return getElevation() + getTranslationZ(); 12777 } 12778 12779 /** 12780 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12781 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12782 * the x value passed in and the current {@link #getElevation() elevation} property. 12783 * 12784 * @param z The visual z position of this view, in pixels. 12785 */ 12786 public void setZ(float z) { 12787 setTranslationZ(z - getElevation()); 12788 } 12789 12790 /** 12791 * The base elevation of this view relative to its parent, in pixels. 12792 * 12793 * @return The base depth position of the view, in pixels. 12794 */ 12795 @ViewDebug.ExportedProperty(category = "drawing") 12796 public float getElevation() { 12797 return mRenderNode.getElevation(); 12798 } 12799 12800 /** 12801 * Sets the base elevation of this view, in pixels. 12802 * 12803 * @attr ref android.R.styleable#View_elevation 12804 */ 12805 public void setElevation(float elevation) { 12806 if (elevation != getElevation()) { 12807 invalidateViewProperty(true, false); 12808 mRenderNode.setElevation(elevation); 12809 invalidateViewProperty(false, true); 12810 12811 invalidateParentIfNeededAndWasQuickRejected(); 12812 } 12813 } 12814 12815 /** 12816 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12817 * This position is post-layout, in addition to wherever the object's 12818 * layout placed it. 12819 * 12820 * @return The horizontal position of this view relative to its left position, in pixels. 12821 */ 12822 @ViewDebug.ExportedProperty(category = "drawing") 12823 public float getTranslationX() { 12824 return mRenderNode.getTranslationX(); 12825 } 12826 12827 /** 12828 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12829 * This effectively positions the object post-layout, in addition to wherever the object's 12830 * layout placed it. 12831 * 12832 * @param translationX The horizontal position of this view relative to its left position, 12833 * in pixels. 12834 * 12835 * @attr ref android.R.styleable#View_translationX 12836 */ 12837 public void setTranslationX(float translationX) { 12838 if (translationX != getTranslationX()) { 12839 invalidateViewProperty(true, false); 12840 mRenderNode.setTranslationX(translationX); 12841 invalidateViewProperty(false, true); 12842 12843 invalidateParentIfNeededAndWasQuickRejected(); 12844 notifySubtreeAccessibilityStateChangedIfNeeded(); 12845 } 12846 } 12847 12848 /** 12849 * The vertical location of this view relative to its {@link #getTop() top} position. 12850 * This position is post-layout, in addition to wherever the object's 12851 * layout placed it. 12852 * 12853 * @return The vertical position of this view relative to its top position, 12854 * in pixels. 12855 */ 12856 @ViewDebug.ExportedProperty(category = "drawing") 12857 public float getTranslationY() { 12858 return mRenderNode.getTranslationY(); 12859 } 12860 12861 /** 12862 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12863 * This effectively positions the object post-layout, in addition to wherever the object's 12864 * layout placed it. 12865 * 12866 * @param translationY The vertical position of this view relative to its top position, 12867 * in pixels. 12868 * 12869 * @attr ref android.R.styleable#View_translationY 12870 */ 12871 public void setTranslationY(float translationY) { 12872 if (translationY != getTranslationY()) { 12873 invalidateViewProperty(true, false); 12874 mRenderNode.setTranslationY(translationY); 12875 invalidateViewProperty(false, true); 12876 12877 invalidateParentIfNeededAndWasQuickRejected(); 12878 notifySubtreeAccessibilityStateChangedIfNeeded(); 12879 } 12880 } 12881 12882 /** 12883 * The depth location of this view relative to its {@link #getElevation() elevation}. 12884 * 12885 * @return The depth of this view relative to its elevation. 12886 */ 12887 @ViewDebug.ExportedProperty(category = "drawing") 12888 public float getTranslationZ() { 12889 return mRenderNode.getTranslationZ(); 12890 } 12891 12892 /** 12893 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12894 * 12895 * @attr ref android.R.styleable#View_translationZ 12896 */ 12897 public void setTranslationZ(float translationZ) { 12898 if (translationZ != getTranslationZ()) { 12899 invalidateViewProperty(true, false); 12900 mRenderNode.setTranslationZ(translationZ); 12901 invalidateViewProperty(false, true); 12902 12903 invalidateParentIfNeededAndWasQuickRejected(); 12904 } 12905 } 12906 12907 /** @hide */ 12908 public void setAnimationMatrix(Matrix matrix) { 12909 invalidateViewProperty(true, false); 12910 mRenderNode.setAnimationMatrix(matrix); 12911 invalidateViewProperty(false, true); 12912 12913 invalidateParentIfNeededAndWasQuickRejected(); 12914 } 12915 12916 /** 12917 * Returns the current StateListAnimator if exists. 12918 * 12919 * @return StateListAnimator or null if it does not exists 12920 * @see #setStateListAnimator(android.animation.StateListAnimator) 12921 */ 12922 public StateListAnimator getStateListAnimator() { 12923 return mStateListAnimator; 12924 } 12925 12926 /** 12927 * Attaches the provided StateListAnimator to this View. 12928 * <p> 12929 * Any previously attached StateListAnimator will be detached. 12930 * 12931 * @param stateListAnimator The StateListAnimator to update the view 12932 * @see {@link android.animation.StateListAnimator} 12933 */ 12934 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12935 if (mStateListAnimator == stateListAnimator) { 12936 return; 12937 } 12938 if (mStateListAnimator != null) { 12939 mStateListAnimator.setTarget(null); 12940 } 12941 mStateListAnimator = stateListAnimator; 12942 if (stateListAnimator != null) { 12943 stateListAnimator.setTarget(this); 12944 if (isAttachedToWindow()) { 12945 stateListAnimator.setState(getDrawableState()); 12946 } 12947 } 12948 } 12949 12950 /** 12951 * Returns whether the Outline should be used to clip the contents of the View. 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 #setClipToOutline(boolean) 12958 */ 12959 public final boolean getClipToOutline() { 12960 return mRenderNode.getClipToOutline(); 12961 } 12962 12963 /** 12964 * Sets whether the View's Outline should be used to clip the contents of the View. 12965 * <p> 12966 * Only a single non-rectangular clip can be applied on a View at any time. 12967 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12968 * circular reveal} animation take priority over Outline clipping, and 12969 * child Outline clipping takes priority over Outline clipping done by a 12970 * parent. 12971 * <p> 12972 * Note that this flag will only be respected if the View's Outline returns true from 12973 * {@link Outline#canClip()}. 12974 * 12975 * @see #setOutlineProvider(ViewOutlineProvider) 12976 * @see #getClipToOutline() 12977 */ 12978 public void setClipToOutline(boolean clipToOutline) { 12979 damageInParent(); 12980 if (getClipToOutline() != clipToOutline) { 12981 mRenderNode.setClipToOutline(clipToOutline); 12982 } 12983 } 12984 12985 // correspond to the enum values of View_outlineProvider 12986 private static final int PROVIDER_BACKGROUND = 0; 12987 private static final int PROVIDER_NONE = 1; 12988 private static final int PROVIDER_BOUNDS = 2; 12989 private static final int PROVIDER_PADDED_BOUNDS = 3; 12990 private void setOutlineProviderFromAttribute(int providerInt) { 12991 switch (providerInt) { 12992 case PROVIDER_BACKGROUND: 12993 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12994 break; 12995 case PROVIDER_NONE: 12996 setOutlineProvider(null); 12997 break; 12998 case PROVIDER_BOUNDS: 12999 setOutlineProvider(ViewOutlineProvider.BOUNDS); 13000 break; 13001 case PROVIDER_PADDED_BOUNDS: 13002 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 13003 break; 13004 } 13005 } 13006 13007 /** 13008 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 13009 * the shape of the shadow it casts, and enables outline clipping. 13010 * <p> 13011 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 13012 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 13013 * outline provider with this method allows this behavior to be overridden. 13014 * <p> 13015 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 13016 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 13017 * <p> 13018 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 13019 * 13020 * @see #setClipToOutline(boolean) 13021 * @see #getClipToOutline() 13022 * @see #getOutlineProvider() 13023 */ 13024 public void setOutlineProvider(ViewOutlineProvider provider) { 13025 mOutlineProvider = provider; 13026 invalidateOutline(); 13027 } 13028 13029 /** 13030 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 13031 * that defines the shape of the shadow it casts, and enables outline clipping. 13032 * 13033 * @see #setOutlineProvider(ViewOutlineProvider) 13034 */ 13035 public ViewOutlineProvider getOutlineProvider() { 13036 return mOutlineProvider; 13037 } 13038 13039 /** 13040 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 13041 * 13042 * @see #setOutlineProvider(ViewOutlineProvider) 13043 */ 13044 public void invalidateOutline() { 13045 rebuildOutline(); 13046 13047 notifySubtreeAccessibilityStateChangedIfNeeded(); 13048 invalidateViewProperty(false, false); 13049 } 13050 13051 /** 13052 * Internal version of {@link #invalidateOutline()} which invalidates the 13053 * outline without invalidating the view itself. This is intended to be called from 13054 * within methods in the View class itself which are the result of the view being 13055 * invalidated already. For example, when we are drawing the background of a View, 13056 * we invalidate the outline in case it changed in the meantime, but we do not 13057 * need to invalidate the view because we're already drawing the background as part 13058 * of drawing the view in response to an earlier invalidation of the view. 13059 */ 13060 private void rebuildOutline() { 13061 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 13062 if (mAttachInfo == null) return; 13063 13064 if (mOutlineProvider == null) { 13065 // no provider, remove outline 13066 mRenderNode.setOutline(null); 13067 } else { 13068 final Outline outline = mAttachInfo.mTmpOutline; 13069 outline.setEmpty(); 13070 outline.setAlpha(1.0f); 13071 13072 mOutlineProvider.getOutline(this, outline); 13073 mRenderNode.setOutline(outline); 13074 } 13075 } 13076 13077 /** 13078 * HierarchyViewer only 13079 * 13080 * @hide 13081 */ 13082 @ViewDebug.ExportedProperty(category = "drawing") 13083 public boolean hasShadow() { 13084 return mRenderNode.hasShadow(); 13085 } 13086 13087 13088 /** @hide */ 13089 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13090 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13091 invalidateViewProperty(false, false); 13092 } 13093 13094 /** 13095 * Hit rectangle in parent's coordinates 13096 * 13097 * @param outRect The hit rectangle of the view. 13098 */ 13099 public void getHitRect(Rect outRect) { 13100 if (hasIdentityMatrix() || mAttachInfo == null) { 13101 outRect.set(mLeft, mTop, mRight, mBottom); 13102 } else { 13103 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13104 tmpRect.set(0, 0, getWidth(), getHeight()); 13105 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13106 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13107 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13108 } 13109 } 13110 13111 /** 13112 * Determines whether the given point, in local coordinates is inside the view. 13113 */ 13114 /*package*/ final boolean pointInView(float localX, float localY) { 13115 return pointInView(localX, localY, 0); 13116 } 13117 13118 /** 13119 * Utility method to determine whether the given point, in local coordinates, 13120 * is inside the view, where the area of the view is expanded by the slop factor. 13121 * This method is called while processing touch-move events to determine if the event 13122 * is still within the view. 13123 * 13124 * @hide 13125 */ 13126 public boolean pointInView(float localX, float localY, float slop) { 13127 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13128 localY < ((mBottom - mTop) + slop); 13129 } 13130 13131 /** 13132 * When a view has focus and the user navigates away from it, the next view is searched for 13133 * starting from the rectangle filled in by this method. 13134 * 13135 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13136 * of the view. However, if your view maintains some idea of internal selection, 13137 * such as a cursor, or a selected row or column, you should override this method and 13138 * fill in a more specific rectangle. 13139 * 13140 * @param r The rectangle to fill in, in this view's coordinates. 13141 */ 13142 public void getFocusedRect(Rect r) { 13143 getDrawingRect(r); 13144 } 13145 13146 /** 13147 * If some part of this view is not clipped by any of its parents, then 13148 * return that area in r in global (root) coordinates. To convert r to local 13149 * coordinates (without taking possible View rotations into account), offset 13150 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13151 * If the view is completely clipped or translated out, return false. 13152 * 13153 * @param r If true is returned, r holds the global coordinates of the 13154 * visible portion of this view. 13155 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13156 * between this view and its root. globalOffet may be null. 13157 * @return true if r is non-empty (i.e. part of the view is visible at the 13158 * root level. 13159 */ 13160 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13161 int width = mRight - mLeft; 13162 int height = mBottom - mTop; 13163 if (width > 0 && height > 0) { 13164 r.set(0, 0, width, height); 13165 if (globalOffset != null) { 13166 globalOffset.set(-mScrollX, -mScrollY); 13167 } 13168 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13169 } 13170 return false; 13171 } 13172 13173 public final boolean getGlobalVisibleRect(Rect r) { 13174 return getGlobalVisibleRect(r, null); 13175 } 13176 13177 public final boolean getLocalVisibleRect(Rect r) { 13178 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13179 if (getGlobalVisibleRect(r, offset)) { 13180 r.offset(-offset.x, -offset.y); // make r local 13181 return true; 13182 } 13183 return false; 13184 } 13185 13186 /** 13187 * Offset this view's vertical location by the specified number of pixels. 13188 * 13189 * @param offset the number of pixels to offset the view by 13190 */ 13191 public void offsetTopAndBottom(int offset) { 13192 if (offset != 0) { 13193 final boolean matrixIsIdentity = hasIdentityMatrix(); 13194 if (matrixIsIdentity) { 13195 if (isHardwareAccelerated()) { 13196 invalidateViewProperty(false, false); 13197 } else { 13198 final ViewParent p = mParent; 13199 if (p != null && mAttachInfo != null) { 13200 final Rect r = mAttachInfo.mTmpInvalRect; 13201 int minTop; 13202 int maxBottom; 13203 int yLoc; 13204 if (offset < 0) { 13205 minTop = mTop + offset; 13206 maxBottom = mBottom; 13207 yLoc = offset; 13208 } else { 13209 minTop = mTop; 13210 maxBottom = mBottom + offset; 13211 yLoc = 0; 13212 } 13213 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13214 p.invalidateChild(this, r); 13215 } 13216 } 13217 } else { 13218 invalidateViewProperty(false, false); 13219 } 13220 13221 mTop += offset; 13222 mBottom += offset; 13223 mRenderNode.offsetTopAndBottom(offset); 13224 if (isHardwareAccelerated()) { 13225 invalidateViewProperty(false, false); 13226 invalidateParentIfNeededAndWasQuickRejected(); 13227 } else { 13228 if (!matrixIsIdentity) { 13229 invalidateViewProperty(false, true); 13230 } 13231 invalidateParentIfNeeded(); 13232 } 13233 notifySubtreeAccessibilityStateChangedIfNeeded(); 13234 } 13235 } 13236 13237 /** 13238 * Offset this view's horizontal location by the specified amount of pixels. 13239 * 13240 * @param offset the number of pixels to offset the view by 13241 */ 13242 public void offsetLeftAndRight(int offset) { 13243 if (offset != 0) { 13244 final boolean matrixIsIdentity = hasIdentityMatrix(); 13245 if (matrixIsIdentity) { 13246 if (isHardwareAccelerated()) { 13247 invalidateViewProperty(false, false); 13248 } else { 13249 final ViewParent p = mParent; 13250 if (p != null && mAttachInfo != null) { 13251 final Rect r = mAttachInfo.mTmpInvalRect; 13252 int minLeft; 13253 int maxRight; 13254 if (offset < 0) { 13255 minLeft = mLeft + offset; 13256 maxRight = mRight; 13257 } else { 13258 minLeft = mLeft; 13259 maxRight = mRight + offset; 13260 } 13261 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13262 p.invalidateChild(this, r); 13263 } 13264 } 13265 } else { 13266 invalidateViewProperty(false, false); 13267 } 13268 13269 mLeft += offset; 13270 mRight += offset; 13271 mRenderNode.offsetLeftAndRight(offset); 13272 if (isHardwareAccelerated()) { 13273 invalidateViewProperty(false, false); 13274 invalidateParentIfNeededAndWasQuickRejected(); 13275 } else { 13276 if (!matrixIsIdentity) { 13277 invalidateViewProperty(false, true); 13278 } 13279 invalidateParentIfNeeded(); 13280 } 13281 notifySubtreeAccessibilityStateChangedIfNeeded(); 13282 } 13283 } 13284 13285 /** 13286 * Get the LayoutParams associated with this view. All views should have 13287 * layout parameters. These supply parameters to the <i>parent</i> of this 13288 * view specifying how it should be arranged. There are many subclasses of 13289 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13290 * of ViewGroup that are responsible for arranging their children. 13291 * 13292 * This method may return null if this View is not attached to a parent 13293 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13294 * was not invoked successfully. When a View is attached to a parent 13295 * ViewGroup, this method must not return null. 13296 * 13297 * @return The LayoutParams associated with this view, or null if no 13298 * parameters have been set yet 13299 */ 13300 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13301 public ViewGroup.LayoutParams getLayoutParams() { 13302 return mLayoutParams; 13303 } 13304 13305 /** 13306 * Set the layout parameters associated with this view. These supply 13307 * parameters to the <i>parent</i> of this view specifying how it should be 13308 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13309 * correspond to the different subclasses of ViewGroup that are responsible 13310 * for arranging their children. 13311 * 13312 * @param params The layout parameters for this view, cannot be null 13313 */ 13314 public void setLayoutParams(ViewGroup.LayoutParams params) { 13315 if (params == null) { 13316 throw new NullPointerException("Layout parameters cannot be null"); 13317 } 13318 mLayoutParams = params; 13319 resolveLayoutParams(); 13320 if (mParent instanceof ViewGroup) { 13321 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13322 } 13323 requestLayout(); 13324 } 13325 13326 /** 13327 * Resolve the layout parameters depending on the resolved layout direction 13328 * 13329 * @hide 13330 */ 13331 public void resolveLayoutParams() { 13332 if (mLayoutParams != null) { 13333 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13334 } 13335 } 13336 13337 /** 13338 * Set the scrolled position of your view. This will cause a call to 13339 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13340 * invalidated. 13341 * @param x the x position to scroll to 13342 * @param y the y position to scroll to 13343 */ 13344 public void scrollTo(int x, int y) { 13345 if (mScrollX != x || mScrollY != y) { 13346 int oldX = mScrollX; 13347 int oldY = mScrollY; 13348 mScrollX = x; 13349 mScrollY = y; 13350 invalidateParentCaches(); 13351 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13352 if (!awakenScrollBars()) { 13353 postInvalidateOnAnimation(); 13354 } 13355 } 13356 } 13357 13358 /** 13359 * Move the scrolled position of your view. This will cause a call to 13360 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13361 * invalidated. 13362 * @param x the amount of pixels to scroll by horizontally 13363 * @param y the amount of pixels to scroll by vertically 13364 */ 13365 public void scrollBy(int x, int y) { 13366 scrollTo(mScrollX + x, mScrollY + y); 13367 } 13368 13369 /** 13370 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13371 * animation to fade the scrollbars out after a default delay. If a subclass 13372 * provides animated scrolling, the start delay should equal the duration 13373 * of the scrolling animation.</p> 13374 * 13375 * <p>The animation starts only if at least one of the scrollbars is 13376 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13377 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13378 * this method returns true, and false otherwise. If the animation is 13379 * started, this method calls {@link #invalidate()}; in that case the 13380 * caller should not call {@link #invalidate()}.</p> 13381 * 13382 * <p>This method should be invoked every time a subclass directly updates 13383 * the scroll parameters.</p> 13384 * 13385 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13386 * and {@link #scrollTo(int, int)}.</p> 13387 * 13388 * @return true if the animation is played, false otherwise 13389 * 13390 * @see #awakenScrollBars(int) 13391 * @see #scrollBy(int, int) 13392 * @see #scrollTo(int, int) 13393 * @see #isHorizontalScrollBarEnabled() 13394 * @see #isVerticalScrollBarEnabled() 13395 * @see #setHorizontalScrollBarEnabled(boolean) 13396 * @see #setVerticalScrollBarEnabled(boolean) 13397 */ 13398 protected boolean awakenScrollBars() { 13399 return mScrollCache != null && 13400 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13401 } 13402 13403 /** 13404 * Trigger the scrollbars to draw. 13405 * This method differs from awakenScrollBars() only in its default duration. 13406 * initialAwakenScrollBars() will show the scroll bars for longer than 13407 * usual to give the user more of a chance to notice them. 13408 * 13409 * @return true if the animation is played, false otherwise. 13410 */ 13411 private boolean initialAwakenScrollBars() { 13412 return mScrollCache != null && 13413 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13414 } 13415 13416 /** 13417 * <p> 13418 * Trigger the scrollbars to draw. When invoked this method starts an 13419 * animation to fade the scrollbars out after a fixed delay. If a subclass 13420 * provides animated scrolling, the start delay should equal the duration of 13421 * the scrolling animation. 13422 * </p> 13423 * 13424 * <p> 13425 * The animation starts only if at least one of the scrollbars is enabled, 13426 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13427 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13428 * this method returns true, and false otherwise. If the animation is 13429 * started, this method calls {@link #invalidate()}; in that case the caller 13430 * should not call {@link #invalidate()}. 13431 * </p> 13432 * 13433 * <p> 13434 * This method should be invoked every time a subclass directly updates the 13435 * scroll parameters. 13436 * </p> 13437 * 13438 * @param startDelay the delay, in milliseconds, after which the animation 13439 * should start; when the delay is 0, the animation starts 13440 * immediately 13441 * @return true if the animation is played, false otherwise 13442 * 13443 * @see #scrollBy(int, int) 13444 * @see #scrollTo(int, int) 13445 * @see #isHorizontalScrollBarEnabled() 13446 * @see #isVerticalScrollBarEnabled() 13447 * @see #setHorizontalScrollBarEnabled(boolean) 13448 * @see #setVerticalScrollBarEnabled(boolean) 13449 */ 13450 protected boolean awakenScrollBars(int startDelay) { 13451 return awakenScrollBars(startDelay, true); 13452 } 13453 13454 /** 13455 * <p> 13456 * Trigger the scrollbars to draw. When invoked this method starts an 13457 * animation to fade the scrollbars out after a fixed delay. If a subclass 13458 * provides animated scrolling, the start delay should equal the duration of 13459 * the scrolling animation. 13460 * </p> 13461 * 13462 * <p> 13463 * The animation starts only if at least one of the scrollbars is enabled, 13464 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13465 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13466 * this method returns true, and false otherwise. If the animation is 13467 * started, this method calls {@link #invalidate()} if the invalidate parameter 13468 * is set to true; in that case the caller 13469 * should not call {@link #invalidate()}. 13470 * </p> 13471 * 13472 * <p> 13473 * This method should be invoked every time a subclass directly updates the 13474 * scroll parameters. 13475 * </p> 13476 * 13477 * @param startDelay the delay, in milliseconds, after which the animation 13478 * should start; when the delay is 0, the animation starts 13479 * immediately 13480 * 13481 * @param invalidate Whether this method should call invalidate 13482 * 13483 * @return true if the animation is played, false otherwise 13484 * 13485 * @see #scrollBy(int, int) 13486 * @see #scrollTo(int, int) 13487 * @see #isHorizontalScrollBarEnabled() 13488 * @see #isVerticalScrollBarEnabled() 13489 * @see #setHorizontalScrollBarEnabled(boolean) 13490 * @see #setVerticalScrollBarEnabled(boolean) 13491 */ 13492 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13493 final ScrollabilityCache scrollCache = mScrollCache; 13494 13495 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13496 return false; 13497 } 13498 13499 if (scrollCache.scrollBar == null) { 13500 scrollCache.scrollBar = new ScrollBarDrawable(); 13501 scrollCache.scrollBar.setState(getDrawableState()); 13502 scrollCache.scrollBar.setCallback(this); 13503 } 13504 13505 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13506 13507 if (invalidate) { 13508 // Invalidate to show the scrollbars 13509 postInvalidateOnAnimation(); 13510 } 13511 13512 if (scrollCache.state == ScrollabilityCache.OFF) { 13513 // FIXME: this is copied from WindowManagerService. 13514 // We should get this value from the system when it 13515 // is possible to do so. 13516 final int KEY_REPEAT_FIRST_DELAY = 750; 13517 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13518 } 13519 13520 // Tell mScrollCache when we should start fading. This may 13521 // extend the fade start time if one was already scheduled 13522 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13523 scrollCache.fadeStartTime = fadeStartTime; 13524 scrollCache.state = ScrollabilityCache.ON; 13525 13526 // Schedule our fader to run, unscheduling any old ones first 13527 if (mAttachInfo != null) { 13528 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13529 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13530 } 13531 13532 return true; 13533 } 13534 13535 return false; 13536 } 13537 13538 /** 13539 * Do not invalidate views which are not visible and which are not running an animation. They 13540 * will not get drawn and they should not set dirty flags as if they will be drawn 13541 */ 13542 private boolean skipInvalidate() { 13543 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13544 (!(mParent instanceof ViewGroup) || 13545 !((ViewGroup) mParent).isViewTransitioning(this)); 13546 } 13547 13548 /** 13549 * Mark the area defined by dirty as needing to be drawn. If the view is 13550 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13551 * point in the future. 13552 * <p> 13553 * This must be called from a UI thread. To call from a non-UI thread, call 13554 * {@link #postInvalidate()}. 13555 * <p> 13556 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13557 * {@code dirty}. 13558 * 13559 * @param dirty the rectangle representing the bounds of the dirty region 13560 */ 13561 public void invalidate(Rect dirty) { 13562 final int scrollX = mScrollX; 13563 final int scrollY = mScrollY; 13564 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13565 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13566 } 13567 13568 /** 13569 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13570 * coordinates of the dirty rect are relative to the view. If the view is 13571 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13572 * point in 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 * @param l the left position of the dirty region 13578 * @param t the top position of the dirty region 13579 * @param r the right position of the dirty region 13580 * @param b the bottom position of the dirty region 13581 */ 13582 public void invalidate(int l, int t, int r, int b) { 13583 final int scrollX = mScrollX; 13584 final int scrollY = mScrollY; 13585 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13586 } 13587 13588 /** 13589 * Invalidate the whole view. If the view is visible, 13590 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13591 * the future. 13592 * <p> 13593 * This must be called from a UI thread. To call from a non-UI thread, call 13594 * {@link #postInvalidate()}. 13595 */ 13596 public void invalidate() { 13597 invalidate(true); 13598 } 13599 13600 /** 13601 * This is where the invalidate() work actually happens. A full invalidate() 13602 * causes the drawing cache to be invalidated, but this function can be 13603 * called with invalidateCache set to false to skip that invalidation step 13604 * for cases that do not need it (for example, a component that remains at 13605 * the same dimensions with the same content). 13606 * 13607 * @param invalidateCache Whether the drawing cache for this view should be 13608 * invalidated as well. This is usually true for a full 13609 * invalidate, but may be set to false if the View's contents or 13610 * dimensions have not changed. 13611 */ 13612 void invalidate(boolean invalidateCache) { 13613 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13614 } 13615 13616 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13617 boolean fullInvalidate) { 13618 if (mGhostView != null) { 13619 mGhostView.invalidate(true); 13620 return; 13621 } 13622 13623 if (skipInvalidate()) { 13624 return; 13625 } 13626 13627 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13628 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13629 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13630 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13631 if (fullInvalidate) { 13632 mLastIsOpaque = isOpaque(); 13633 mPrivateFlags &= ~PFLAG_DRAWN; 13634 } 13635 13636 mPrivateFlags |= PFLAG_DIRTY; 13637 13638 if (invalidateCache) { 13639 mPrivateFlags |= PFLAG_INVALIDATED; 13640 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13641 } 13642 13643 // Propagate the damage rectangle to the parent view. 13644 final AttachInfo ai = mAttachInfo; 13645 final ViewParent p = mParent; 13646 if (p != null && ai != null && l < r && t < b) { 13647 final Rect damage = ai.mTmpInvalRect; 13648 damage.set(l, t, r, b); 13649 p.invalidateChild(this, damage); 13650 } 13651 13652 // Damage the entire projection receiver, if necessary. 13653 if (mBackground != null && mBackground.isProjected()) { 13654 final View receiver = getProjectionReceiver(); 13655 if (receiver != null) { 13656 receiver.damageInParent(); 13657 } 13658 } 13659 13660 // Damage the entire IsolatedZVolume receiving this view's shadow. 13661 if (isHardwareAccelerated() && getZ() != 0) { 13662 damageShadowReceiver(); 13663 } 13664 } 13665 } 13666 13667 /** 13668 * @return this view's projection receiver, or {@code null} if none exists 13669 */ 13670 private View getProjectionReceiver() { 13671 ViewParent p = getParent(); 13672 while (p != null && p instanceof View) { 13673 final View v = (View) p; 13674 if (v.isProjectionReceiver()) { 13675 return v; 13676 } 13677 p = p.getParent(); 13678 } 13679 13680 return null; 13681 } 13682 13683 /** 13684 * @return whether the view is a projection receiver 13685 */ 13686 private boolean isProjectionReceiver() { 13687 return mBackground != null; 13688 } 13689 13690 /** 13691 * Damage area of the screen that can be covered by this View's shadow. 13692 * 13693 * This method will guarantee that any changes to shadows cast by a View 13694 * are damaged on the screen for future redraw. 13695 */ 13696 private void damageShadowReceiver() { 13697 final AttachInfo ai = mAttachInfo; 13698 if (ai != null) { 13699 ViewParent p = getParent(); 13700 if (p != null && p instanceof ViewGroup) { 13701 final ViewGroup vg = (ViewGroup) p; 13702 vg.damageInParent(); 13703 } 13704 } 13705 } 13706 13707 /** 13708 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13709 * set any flags or handle all of the cases handled by the default invalidation methods. 13710 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13711 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13712 * walk up the hierarchy, transforming the dirty rect as necessary. 13713 * 13714 * The method also handles normal invalidation logic if display list properties are not 13715 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13716 * backup approach, to handle these cases used in the various property-setting methods. 13717 * 13718 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13719 * are not being used in this view 13720 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13721 * list properties are not being used in this view 13722 */ 13723 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13724 if (!isHardwareAccelerated() 13725 || !mRenderNode.isValid() 13726 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13727 if (invalidateParent) { 13728 invalidateParentCaches(); 13729 } 13730 if (forceRedraw) { 13731 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13732 } 13733 invalidate(false); 13734 } else { 13735 damageInParent(); 13736 } 13737 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13738 damageShadowReceiver(); 13739 } 13740 } 13741 13742 /** 13743 * Tells the parent view to damage this view's bounds. 13744 * 13745 * @hide 13746 */ 13747 protected void damageInParent() { 13748 final AttachInfo ai = mAttachInfo; 13749 final ViewParent p = mParent; 13750 if (p != null && ai != null) { 13751 final Rect r = ai.mTmpInvalRect; 13752 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13753 if (mParent instanceof ViewGroup) { 13754 ((ViewGroup) mParent).damageChild(this, r); 13755 } else { 13756 mParent.invalidateChild(this, r); 13757 } 13758 } 13759 } 13760 13761 /** 13762 * Utility method to transform a given Rect by the current matrix of this view. 13763 */ 13764 void transformRect(final Rect rect) { 13765 if (!getMatrix().isIdentity()) { 13766 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13767 boundingRect.set(rect); 13768 getMatrix().mapRect(boundingRect); 13769 rect.set((int) Math.floor(boundingRect.left), 13770 (int) Math.floor(boundingRect.top), 13771 (int) Math.ceil(boundingRect.right), 13772 (int) Math.ceil(boundingRect.bottom)); 13773 } 13774 } 13775 13776 /** 13777 * Used to indicate that the parent of this view should clear its caches. This functionality 13778 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13779 * which is necessary when various parent-managed properties of the view change, such as 13780 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13781 * clears the parent caches and does not causes an invalidate event. 13782 * 13783 * @hide 13784 */ 13785 protected void invalidateParentCaches() { 13786 if (mParent instanceof View) { 13787 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13788 } 13789 } 13790 13791 /** 13792 * Used to indicate that the parent of this view should be invalidated. This functionality 13793 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13794 * which is necessary when various parent-managed properties of the view change, such as 13795 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13796 * an invalidation event to the parent. 13797 * 13798 * @hide 13799 */ 13800 protected void invalidateParentIfNeeded() { 13801 if (isHardwareAccelerated() && mParent instanceof View) { 13802 ((View) mParent).invalidate(true); 13803 } 13804 } 13805 13806 /** 13807 * @hide 13808 */ 13809 protected void invalidateParentIfNeededAndWasQuickRejected() { 13810 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13811 // View was rejected last time it was drawn by its parent; this may have changed 13812 invalidateParentIfNeeded(); 13813 } 13814 } 13815 13816 /** 13817 * Indicates whether this View is opaque. An opaque View guarantees that it will 13818 * draw all the pixels overlapping its bounds using a fully opaque color. 13819 * 13820 * Subclasses of View should override this method whenever possible to indicate 13821 * whether an instance is opaque. Opaque Views are treated in a special way by 13822 * the View hierarchy, possibly allowing it to perform optimizations during 13823 * invalidate/draw passes. 13824 * 13825 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13826 */ 13827 @ViewDebug.ExportedProperty(category = "drawing") 13828 public boolean isOpaque() { 13829 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13830 getFinalAlpha() >= 1.0f; 13831 } 13832 13833 /** 13834 * @hide 13835 */ 13836 protected void computeOpaqueFlags() { 13837 // Opaque if: 13838 // - Has a background 13839 // - Background is opaque 13840 // - Doesn't have scrollbars or scrollbars overlay 13841 13842 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13843 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13844 } else { 13845 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13846 } 13847 13848 final int flags = mViewFlags; 13849 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13850 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13851 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13852 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13853 } else { 13854 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13855 } 13856 } 13857 13858 /** 13859 * @hide 13860 */ 13861 protected boolean hasOpaqueScrollbars() { 13862 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13863 } 13864 13865 /** 13866 * @return A handler associated with the thread running the View. This 13867 * handler can be used to pump events in the UI events queue. 13868 */ 13869 public Handler getHandler() { 13870 final AttachInfo attachInfo = mAttachInfo; 13871 if (attachInfo != null) { 13872 return attachInfo.mHandler; 13873 } 13874 return null; 13875 } 13876 13877 /** 13878 * Returns the queue of runnable for this view. 13879 * 13880 * @return the queue of runnables for this view 13881 */ 13882 private HandlerActionQueue getRunQueue() { 13883 if (mRunQueue == null) { 13884 mRunQueue = new HandlerActionQueue(); 13885 } 13886 return mRunQueue; 13887 } 13888 13889 /** 13890 * Gets the view root associated with the View. 13891 * @return The view root, or null if none. 13892 * @hide 13893 */ 13894 public ViewRootImpl getViewRootImpl() { 13895 if (mAttachInfo != null) { 13896 return mAttachInfo.mViewRootImpl; 13897 } 13898 return null; 13899 } 13900 13901 /** 13902 * @hide 13903 */ 13904 public ThreadedRenderer getThreadedRenderer() { 13905 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 13906 } 13907 13908 /** 13909 * <p>Causes the Runnable to be added to the message queue. 13910 * The runnable will be run on the user interface thread.</p> 13911 * 13912 * @param action The Runnable that will be executed. 13913 * 13914 * @return Returns true if the Runnable was successfully placed in to the 13915 * message queue. Returns false on failure, usually because the 13916 * looper processing the message queue is exiting. 13917 * 13918 * @see #postDelayed 13919 * @see #removeCallbacks 13920 */ 13921 public boolean post(Runnable action) { 13922 final AttachInfo attachInfo = mAttachInfo; 13923 if (attachInfo != null) { 13924 return attachInfo.mHandler.post(action); 13925 } 13926 13927 // Postpone the runnable until we know on which thread it needs to run. 13928 // Assume that the runnable will be successfully placed after attach. 13929 getRunQueue().post(action); 13930 return true; 13931 } 13932 13933 /** 13934 * <p>Causes the Runnable to be added to the message queue, to be run 13935 * after the specified amount of time elapses. 13936 * The runnable will be run on the user interface thread.</p> 13937 * 13938 * @param action The Runnable that will be executed. 13939 * @param delayMillis The delay (in milliseconds) until the Runnable 13940 * will be executed. 13941 * 13942 * @return true if the Runnable was successfully placed in to the 13943 * message queue. Returns false on failure, usually because the 13944 * looper processing the message queue is exiting. Note that a 13945 * result of true does not mean the Runnable will be processed -- 13946 * if the looper is quit before the delivery time of the message 13947 * occurs then the message will be dropped. 13948 * 13949 * @see #post 13950 * @see #removeCallbacks 13951 */ 13952 public boolean postDelayed(Runnable action, long delayMillis) { 13953 final AttachInfo attachInfo = mAttachInfo; 13954 if (attachInfo != null) { 13955 return attachInfo.mHandler.postDelayed(action, delayMillis); 13956 } 13957 13958 // Postpone the runnable until we know on which thread it needs to run. 13959 // Assume that the runnable will be successfully placed after attach. 13960 getRunQueue().postDelayed(action, delayMillis); 13961 return true; 13962 } 13963 13964 /** 13965 * <p>Causes the Runnable to execute on the next animation time step. 13966 * The runnable will be run on the user interface thread.</p> 13967 * 13968 * @param action The Runnable that will be executed. 13969 * 13970 * @see #postOnAnimationDelayed 13971 * @see #removeCallbacks 13972 */ 13973 public void postOnAnimation(Runnable action) { 13974 final AttachInfo attachInfo = mAttachInfo; 13975 if (attachInfo != null) { 13976 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13977 Choreographer.CALLBACK_ANIMATION, action, null); 13978 } else { 13979 // Postpone the runnable until we know 13980 // on which thread it needs to run. 13981 getRunQueue().post(action); 13982 } 13983 } 13984 13985 /** 13986 * <p>Causes the Runnable to execute on the next animation time step, 13987 * after the specified amount of time elapses. 13988 * The runnable will be run on the user interface thread.</p> 13989 * 13990 * @param action The Runnable that will be executed. 13991 * @param delayMillis The delay (in milliseconds) until the Runnable 13992 * will be executed. 13993 * 13994 * @see #postOnAnimation 13995 * @see #removeCallbacks 13996 */ 13997 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13998 final AttachInfo attachInfo = mAttachInfo; 13999 if (attachInfo != null) { 14000 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14001 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 14002 } else { 14003 // Postpone the runnable until we know 14004 // on which thread it needs to run. 14005 getRunQueue().postDelayed(action, delayMillis); 14006 } 14007 } 14008 14009 /** 14010 * <p>Removes the specified Runnable from the message queue.</p> 14011 * 14012 * @param action The Runnable to remove from the message handling queue 14013 * 14014 * @return true if this view could ask the Handler to remove the Runnable, 14015 * false otherwise. When the returned value is true, the Runnable 14016 * may or may not have been actually removed from the message queue 14017 * (for instance, if the Runnable was not in the queue already.) 14018 * 14019 * @see #post 14020 * @see #postDelayed 14021 * @see #postOnAnimation 14022 * @see #postOnAnimationDelayed 14023 */ 14024 public boolean removeCallbacks(Runnable action) { 14025 if (action != null) { 14026 final AttachInfo attachInfo = mAttachInfo; 14027 if (attachInfo != null) { 14028 attachInfo.mHandler.removeCallbacks(action); 14029 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14030 Choreographer.CALLBACK_ANIMATION, action, null); 14031 } 14032 getRunQueue().removeCallbacks(action); 14033 } 14034 return true; 14035 } 14036 14037 /** 14038 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 14039 * Use this to invalidate the View from a non-UI thread.</p> 14040 * 14041 * <p>This method can be invoked from outside of the UI thread 14042 * only when this View is attached to a window.</p> 14043 * 14044 * @see #invalidate() 14045 * @see #postInvalidateDelayed(long) 14046 */ 14047 public void postInvalidate() { 14048 postInvalidateDelayed(0); 14049 } 14050 14051 /** 14052 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14053 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 14054 * 14055 * <p>This method can be invoked from outside of the UI thread 14056 * only when this View is attached to a window.</p> 14057 * 14058 * @param left The left coordinate of the rectangle to invalidate. 14059 * @param top The top coordinate of the rectangle to invalidate. 14060 * @param right The right coordinate of the rectangle to invalidate. 14061 * @param bottom The bottom coordinate of the rectangle to invalidate. 14062 * 14063 * @see #invalidate(int, int, int, int) 14064 * @see #invalidate(Rect) 14065 * @see #postInvalidateDelayed(long, int, int, int, int) 14066 */ 14067 public void postInvalidate(int left, int top, int right, int bottom) { 14068 postInvalidateDelayed(0, left, top, right, bottom); 14069 } 14070 14071 /** 14072 * <p>Cause an invalidate to happen on a subsequent cycle through the event 14073 * loop. Waits for the specified amount of time.</p> 14074 * 14075 * <p>This method can be invoked from outside of the UI thread 14076 * only when this View is attached to a window.</p> 14077 * 14078 * @param delayMilliseconds the duration in milliseconds to delay the 14079 * invalidation by 14080 * 14081 * @see #invalidate() 14082 * @see #postInvalidate() 14083 */ 14084 public void postInvalidateDelayed(long delayMilliseconds) { 14085 // We try only with the AttachInfo because there's no point in invalidating 14086 // if we are not attached to our window 14087 final AttachInfo attachInfo = mAttachInfo; 14088 if (attachInfo != null) { 14089 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14090 } 14091 } 14092 14093 /** 14094 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14095 * through the event loop. Waits for the specified amount of time.</p> 14096 * 14097 * <p>This method can be invoked from outside of the UI thread 14098 * only when this View is attached to a window.</p> 14099 * 14100 * @param delayMilliseconds the duration in milliseconds to delay the 14101 * invalidation by 14102 * @param left The left coordinate of the rectangle to invalidate. 14103 * @param top The top coordinate of the rectangle to invalidate. 14104 * @param right The right coordinate of the rectangle to invalidate. 14105 * @param bottom The bottom coordinate of the rectangle to invalidate. 14106 * 14107 * @see #invalidate(int, int, int, int) 14108 * @see #invalidate(Rect) 14109 * @see #postInvalidate(int, int, int, int) 14110 */ 14111 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14112 int right, int bottom) { 14113 14114 // We try only with the AttachInfo because there's no point in invalidating 14115 // if we are not attached to our window 14116 final AttachInfo attachInfo = mAttachInfo; 14117 if (attachInfo != null) { 14118 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14119 info.target = this; 14120 info.left = left; 14121 info.top = top; 14122 info.right = right; 14123 info.bottom = bottom; 14124 14125 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14126 } 14127 } 14128 14129 /** 14130 * <p>Cause an invalidate to happen on the next animation time step, typically the 14131 * next display frame.</p> 14132 * 14133 * <p>This method can be invoked from outside of the UI thread 14134 * only when this View is attached to a window.</p> 14135 * 14136 * @see #invalidate() 14137 */ 14138 public void postInvalidateOnAnimation() { 14139 // We try only with the AttachInfo because there's no point in invalidating 14140 // if we are not attached to our window 14141 final AttachInfo attachInfo = mAttachInfo; 14142 if (attachInfo != null) { 14143 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14144 } 14145 } 14146 14147 /** 14148 * <p>Cause an invalidate of the specified area to happen on the next animation 14149 * time step, typically the next display frame.</p> 14150 * 14151 * <p>This method can be invoked from outside of the UI thread 14152 * only when this View is attached to a window.</p> 14153 * 14154 * @param left The left coordinate of the rectangle to invalidate. 14155 * @param top The top coordinate of the rectangle to invalidate. 14156 * @param right The right coordinate of the rectangle to invalidate. 14157 * @param bottom The bottom coordinate of the rectangle to invalidate. 14158 * 14159 * @see #invalidate(int, int, int, int) 14160 * @see #invalidate(Rect) 14161 */ 14162 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14163 // We try only with the AttachInfo because there's no point in invalidating 14164 // if we are not attached to our window 14165 final AttachInfo attachInfo = mAttachInfo; 14166 if (attachInfo != null) { 14167 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14168 info.target = this; 14169 info.left = left; 14170 info.top = top; 14171 info.right = right; 14172 info.bottom = bottom; 14173 14174 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14175 } 14176 } 14177 14178 /** 14179 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14180 * This event is sent at most once every 14181 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14182 */ 14183 private void postSendViewScrolledAccessibilityEventCallback() { 14184 if (mSendViewScrolledAccessibilityEvent == null) { 14185 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14186 } 14187 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14188 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14189 postDelayed(mSendViewScrolledAccessibilityEvent, 14190 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14191 } 14192 } 14193 14194 /** 14195 * Called by a parent to request that a child update its values for mScrollX 14196 * and mScrollY if necessary. This will typically be done if the child is 14197 * animating a scroll using a {@link android.widget.Scroller Scroller} 14198 * object. 14199 */ 14200 public void computeScroll() { 14201 } 14202 14203 /** 14204 * <p>Indicate whether the horizontal edges are faded when the view is 14205 * scrolled horizontally.</p> 14206 * 14207 * @return true if the horizontal edges should are faded on scroll, false 14208 * otherwise 14209 * 14210 * @see #setHorizontalFadingEdgeEnabled(boolean) 14211 * 14212 * @attr ref android.R.styleable#View_requiresFadingEdge 14213 */ 14214 public boolean isHorizontalFadingEdgeEnabled() { 14215 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14216 } 14217 14218 /** 14219 * <p>Define whether the horizontal edges should be faded when this view 14220 * is scrolled horizontally.</p> 14221 * 14222 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14223 * be faded when the view is scrolled 14224 * horizontally 14225 * 14226 * @see #isHorizontalFadingEdgeEnabled() 14227 * 14228 * @attr ref android.R.styleable#View_requiresFadingEdge 14229 */ 14230 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14231 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14232 if (horizontalFadingEdgeEnabled) { 14233 initScrollCache(); 14234 } 14235 14236 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14237 } 14238 } 14239 14240 /** 14241 * <p>Indicate whether the vertical edges are faded when the view is 14242 * scrolled horizontally.</p> 14243 * 14244 * @return true if the vertical edges should are faded on scroll, false 14245 * otherwise 14246 * 14247 * @see #setVerticalFadingEdgeEnabled(boolean) 14248 * 14249 * @attr ref android.R.styleable#View_requiresFadingEdge 14250 */ 14251 public boolean isVerticalFadingEdgeEnabled() { 14252 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14253 } 14254 14255 /** 14256 * <p>Define whether the vertical edges should be faded when this view 14257 * is scrolled vertically.</p> 14258 * 14259 * @param verticalFadingEdgeEnabled true if the vertical edges should 14260 * be faded when the view is scrolled 14261 * vertically 14262 * 14263 * @see #isVerticalFadingEdgeEnabled() 14264 * 14265 * @attr ref android.R.styleable#View_requiresFadingEdge 14266 */ 14267 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14268 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14269 if (verticalFadingEdgeEnabled) { 14270 initScrollCache(); 14271 } 14272 14273 mViewFlags ^= FADING_EDGE_VERTICAL; 14274 } 14275 } 14276 14277 /** 14278 * Returns the strength, or intensity, of the top faded edge. The strength is 14279 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14280 * returns 0.0 or 1.0 but no value in between. 14281 * 14282 * Subclasses should override this method to provide a smoother fade transition 14283 * when scrolling occurs. 14284 * 14285 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14286 */ 14287 protected float getTopFadingEdgeStrength() { 14288 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14289 } 14290 14291 /** 14292 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14293 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14294 * returns 0.0 or 1.0 but no value in between. 14295 * 14296 * Subclasses should override this method to provide a smoother fade transition 14297 * when scrolling occurs. 14298 * 14299 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14300 */ 14301 protected float getBottomFadingEdgeStrength() { 14302 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14303 computeVerticalScrollRange() ? 1.0f : 0.0f; 14304 } 14305 14306 /** 14307 * Returns the strength, or intensity, of the left faded edge. The strength is 14308 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14309 * returns 0.0 or 1.0 but no value in between. 14310 * 14311 * Subclasses should override this method to provide a smoother fade transition 14312 * when scrolling occurs. 14313 * 14314 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14315 */ 14316 protected float getLeftFadingEdgeStrength() { 14317 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14318 } 14319 14320 /** 14321 * Returns the strength, or intensity, of the right faded edge. The strength is 14322 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14323 * returns 0.0 or 1.0 but no value in between. 14324 * 14325 * Subclasses should override this method to provide a smoother fade transition 14326 * when scrolling occurs. 14327 * 14328 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14329 */ 14330 protected float getRightFadingEdgeStrength() { 14331 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14332 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14333 } 14334 14335 /** 14336 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14337 * scrollbar is not drawn by default.</p> 14338 * 14339 * @return true if the horizontal scrollbar should be painted, false 14340 * otherwise 14341 * 14342 * @see #setHorizontalScrollBarEnabled(boolean) 14343 */ 14344 public boolean isHorizontalScrollBarEnabled() { 14345 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14346 } 14347 14348 /** 14349 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14350 * scrollbar is not drawn by default.</p> 14351 * 14352 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14353 * be painted 14354 * 14355 * @see #isHorizontalScrollBarEnabled() 14356 */ 14357 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14358 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14359 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14360 computeOpaqueFlags(); 14361 resolvePadding(); 14362 } 14363 } 14364 14365 /** 14366 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14367 * scrollbar is not drawn by default.</p> 14368 * 14369 * @return true if the vertical scrollbar should be painted, false 14370 * otherwise 14371 * 14372 * @see #setVerticalScrollBarEnabled(boolean) 14373 */ 14374 public boolean isVerticalScrollBarEnabled() { 14375 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14376 } 14377 14378 /** 14379 * <p>Define whether the vertical scrollbar should be drawn or not. The 14380 * scrollbar is not drawn by default.</p> 14381 * 14382 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14383 * be painted 14384 * 14385 * @see #isVerticalScrollBarEnabled() 14386 */ 14387 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14388 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14389 mViewFlags ^= SCROLLBARS_VERTICAL; 14390 computeOpaqueFlags(); 14391 resolvePadding(); 14392 } 14393 } 14394 14395 /** 14396 * @hide 14397 */ 14398 protected void recomputePadding() { 14399 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14400 } 14401 14402 /** 14403 * Define whether scrollbars will fade when the view is not scrolling. 14404 * 14405 * @param fadeScrollbars whether to enable fading 14406 * 14407 * @attr ref android.R.styleable#View_fadeScrollbars 14408 */ 14409 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14410 initScrollCache(); 14411 final ScrollabilityCache scrollabilityCache = mScrollCache; 14412 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14413 if (fadeScrollbars) { 14414 scrollabilityCache.state = ScrollabilityCache.OFF; 14415 } else { 14416 scrollabilityCache.state = ScrollabilityCache.ON; 14417 } 14418 } 14419 14420 /** 14421 * 14422 * Returns true if scrollbars will fade when this view is not scrolling 14423 * 14424 * @return true if scrollbar fading is enabled 14425 * 14426 * @attr ref android.R.styleable#View_fadeScrollbars 14427 */ 14428 public boolean isScrollbarFadingEnabled() { 14429 return mScrollCache != null && mScrollCache.fadeScrollBars; 14430 } 14431 14432 /** 14433 * 14434 * Returns the delay before scrollbars fade. 14435 * 14436 * @return the delay before scrollbars fade 14437 * 14438 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14439 */ 14440 public int getScrollBarDefaultDelayBeforeFade() { 14441 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14442 mScrollCache.scrollBarDefaultDelayBeforeFade; 14443 } 14444 14445 /** 14446 * Define the delay before scrollbars fade. 14447 * 14448 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14449 * 14450 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14451 */ 14452 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14453 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14454 } 14455 14456 /** 14457 * 14458 * Returns the scrollbar fade duration. 14459 * 14460 * @return the scrollbar fade duration, in milliseconds 14461 * 14462 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14463 */ 14464 public int getScrollBarFadeDuration() { 14465 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14466 mScrollCache.scrollBarFadeDuration; 14467 } 14468 14469 /** 14470 * Define the scrollbar fade duration. 14471 * 14472 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 14473 * 14474 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14475 */ 14476 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14477 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14478 } 14479 14480 /** 14481 * 14482 * Returns the scrollbar size. 14483 * 14484 * @return the scrollbar size 14485 * 14486 * @attr ref android.R.styleable#View_scrollbarSize 14487 */ 14488 public int getScrollBarSize() { 14489 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14490 mScrollCache.scrollBarSize; 14491 } 14492 14493 /** 14494 * Define the scrollbar size. 14495 * 14496 * @param scrollBarSize - the scrollbar size 14497 * 14498 * @attr ref android.R.styleable#View_scrollbarSize 14499 */ 14500 public void setScrollBarSize(int scrollBarSize) { 14501 getScrollCache().scrollBarSize = scrollBarSize; 14502 } 14503 14504 /** 14505 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14506 * inset. When inset, they add to the padding of the view. And the scrollbars 14507 * can be drawn inside the padding area or on the edge of the view. For example, 14508 * if a view has a background drawable and you want to draw the scrollbars 14509 * inside the padding specified by the drawable, you can use 14510 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14511 * appear at the edge of the view, ignoring the padding, then you can use 14512 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14513 * @param style the style of the scrollbars. Should be one of 14514 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14515 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14516 * @see #SCROLLBARS_INSIDE_OVERLAY 14517 * @see #SCROLLBARS_INSIDE_INSET 14518 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14519 * @see #SCROLLBARS_OUTSIDE_INSET 14520 * 14521 * @attr ref android.R.styleable#View_scrollbarStyle 14522 */ 14523 public void setScrollBarStyle(@ScrollBarStyle int style) { 14524 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14525 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14526 computeOpaqueFlags(); 14527 resolvePadding(); 14528 } 14529 } 14530 14531 /** 14532 * <p>Returns the current scrollbar style.</p> 14533 * @return the current scrollbar style 14534 * @see #SCROLLBARS_INSIDE_OVERLAY 14535 * @see #SCROLLBARS_INSIDE_INSET 14536 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14537 * @see #SCROLLBARS_OUTSIDE_INSET 14538 * 14539 * @attr ref android.R.styleable#View_scrollbarStyle 14540 */ 14541 @ViewDebug.ExportedProperty(mapping = { 14542 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14543 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14544 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14545 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14546 }) 14547 @ScrollBarStyle 14548 public int getScrollBarStyle() { 14549 return mViewFlags & SCROLLBARS_STYLE_MASK; 14550 } 14551 14552 /** 14553 * <p>Compute the horizontal range that the horizontal scrollbar 14554 * represents.</p> 14555 * 14556 * <p>The range is expressed in arbitrary units that must be the same as the 14557 * units used by {@link #computeHorizontalScrollExtent()} and 14558 * {@link #computeHorizontalScrollOffset()}.</p> 14559 * 14560 * <p>The default range is the drawing width of this view.</p> 14561 * 14562 * @return the total horizontal range represented by the horizontal 14563 * scrollbar 14564 * 14565 * @see #computeHorizontalScrollExtent() 14566 * @see #computeHorizontalScrollOffset() 14567 * @see android.widget.ScrollBarDrawable 14568 */ 14569 protected int computeHorizontalScrollRange() { 14570 return getWidth(); 14571 } 14572 14573 /** 14574 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14575 * within the horizontal range. This value is used to compute the position 14576 * of the thumb within the scrollbar's track.</p> 14577 * 14578 * <p>The range is expressed in arbitrary units that must be the same as the 14579 * units used by {@link #computeHorizontalScrollRange()} and 14580 * {@link #computeHorizontalScrollExtent()}.</p> 14581 * 14582 * <p>The default offset is the scroll offset of this view.</p> 14583 * 14584 * @return the horizontal offset of the scrollbar's thumb 14585 * 14586 * @see #computeHorizontalScrollRange() 14587 * @see #computeHorizontalScrollExtent() 14588 * @see android.widget.ScrollBarDrawable 14589 */ 14590 protected int computeHorizontalScrollOffset() { 14591 return mScrollX; 14592 } 14593 14594 /** 14595 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14596 * within the horizontal range. This value is used to compute the length 14597 * of the thumb within the scrollbar's track.</p> 14598 * 14599 * <p>The range is expressed in arbitrary units that must be the same as the 14600 * units used by {@link #computeHorizontalScrollRange()} and 14601 * {@link #computeHorizontalScrollOffset()}.</p> 14602 * 14603 * <p>The default extent is the drawing width of this view.</p> 14604 * 14605 * @return the horizontal extent of the scrollbar's thumb 14606 * 14607 * @see #computeHorizontalScrollRange() 14608 * @see #computeHorizontalScrollOffset() 14609 * @see android.widget.ScrollBarDrawable 14610 */ 14611 protected int computeHorizontalScrollExtent() { 14612 return getWidth(); 14613 } 14614 14615 /** 14616 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14617 * 14618 * <p>The range is expressed in arbitrary units that must be the same as the 14619 * units used by {@link #computeVerticalScrollExtent()} and 14620 * {@link #computeVerticalScrollOffset()}.</p> 14621 * 14622 * @return the total vertical range represented by the vertical scrollbar 14623 * 14624 * <p>The default range is the drawing height of this view.</p> 14625 * 14626 * @see #computeVerticalScrollExtent() 14627 * @see #computeVerticalScrollOffset() 14628 * @see android.widget.ScrollBarDrawable 14629 */ 14630 protected int computeVerticalScrollRange() { 14631 return getHeight(); 14632 } 14633 14634 /** 14635 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14636 * within the horizontal range. This value is used to compute the position 14637 * of the thumb within the scrollbar's track.</p> 14638 * 14639 * <p>The range is expressed in arbitrary units that must be the same as the 14640 * units used by {@link #computeVerticalScrollRange()} and 14641 * {@link #computeVerticalScrollExtent()}.</p> 14642 * 14643 * <p>The default offset is the scroll offset of this view.</p> 14644 * 14645 * @return the vertical offset of the scrollbar's thumb 14646 * 14647 * @see #computeVerticalScrollRange() 14648 * @see #computeVerticalScrollExtent() 14649 * @see android.widget.ScrollBarDrawable 14650 */ 14651 protected int computeVerticalScrollOffset() { 14652 return mScrollY; 14653 } 14654 14655 /** 14656 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14657 * within the vertical range. This value is used to compute the length 14658 * of the thumb within the scrollbar's track.</p> 14659 * 14660 * <p>The range is expressed in arbitrary units that must be the same as the 14661 * units used by {@link #computeVerticalScrollRange()} and 14662 * {@link #computeVerticalScrollOffset()}.</p> 14663 * 14664 * <p>The default extent is the drawing height of this view.</p> 14665 * 14666 * @return the vertical extent of the scrollbar's thumb 14667 * 14668 * @see #computeVerticalScrollRange() 14669 * @see #computeVerticalScrollOffset() 14670 * @see android.widget.ScrollBarDrawable 14671 */ 14672 protected int computeVerticalScrollExtent() { 14673 return getHeight(); 14674 } 14675 14676 /** 14677 * Check if this view can be scrolled horizontally in a certain direction. 14678 * 14679 * @param direction Negative to check scrolling left, positive to check scrolling right. 14680 * @return true if this view can be scrolled in the specified direction, false otherwise. 14681 */ 14682 public boolean canScrollHorizontally(int direction) { 14683 final int offset = computeHorizontalScrollOffset(); 14684 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14685 if (range == 0) return false; 14686 if (direction < 0) { 14687 return offset > 0; 14688 } else { 14689 return offset < range - 1; 14690 } 14691 } 14692 14693 /** 14694 * Check if this view can be scrolled vertically in a certain direction. 14695 * 14696 * @param direction Negative to check scrolling up, positive to check scrolling down. 14697 * @return true if this view can be scrolled in the specified direction, false otherwise. 14698 */ 14699 public boolean canScrollVertically(int direction) { 14700 final int offset = computeVerticalScrollOffset(); 14701 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14702 if (range == 0) return false; 14703 if (direction < 0) { 14704 return offset > 0; 14705 } else { 14706 return offset < range - 1; 14707 } 14708 } 14709 14710 void getScrollIndicatorBounds(@NonNull Rect out) { 14711 out.left = mScrollX; 14712 out.right = mScrollX + mRight - mLeft; 14713 out.top = mScrollY; 14714 out.bottom = mScrollY + mBottom - mTop; 14715 } 14716 14717 private void onDrawScrollIndicators(Canvas c) { 14718 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14719 // No scroll indicators enabled. 14720 return; 14721 } 14722 14723 final Drawable dr = mScrollIndicatorDrawable; 14724 if (dr == null) { 14725 // Scroll indicators aren't supported here. 14726 return; 14727 } 14728 14729 final int h = dr.getIntrinsicHeight(); 14730 final int w = dr.getIntrinsicWidth(); 14731 final Rect rect = mAttachInfo.mTmpInvalRect; 14732 getScrollIndicatorBounds(rect); 14733 14734 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14735 final boolean canScrollUp = canScrollVertically(-1); 14736 if (canScrollUp) { 14737 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14738 dr.draw(c); 14739 } 14740 } 14741 14742 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14743 final boolean canScrollDown = canScrollVertically(1); 14744 if (canScrollDown) { 14745 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14746 dr.draw(c); 14747 } 14748 } 14749 14750 final int leftRtl; 14751 final int rightRtl; 14752 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14753 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14754 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14755 } else { 14756 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14757 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14758 } 14759 14760 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14761 if ((mPrivateFlags3 & leftMask) != 0) { 14762 final boolean canScrollLeft = canScrollHorizontally(-1); 14763 if (canScrollLeft) { 14764 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14765 dr.draw(c); 14766 } 14767 } 14768 14769 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14770 if ((mPrivateFlags3 & rightMask) != 0) { 14771 final boolean canScrollRight = canScrollHorizontally(1); 14772 if (canScrollRight) { 14773 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14774 dr.draw(c); 14775 } 14776 } 14777 } 14778 14779 private void getHorizontalScrollBarBounds(Rect bounds) { 14780 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14781 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14782 && !isVerticalScrollBarHidden(); 14783 final int size = getHorizontalScrollbarHeight(); 14784 final int verticalScrollBarGap = drawVerticalScrollBar ? 14785 getVerticalScrollbarWidth() : 0; 14786 final int width = mRight - mLeft; 14787 final int height = mBottom - mTop; 14788 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14789 bounds.left = mScrollX + (mPaddingLeft & inside); 14790 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14791 bounds.bottom = bounds.top + size; 14792 } 14793 14794 private void getVerticalScrollBarBounds(Rect bounds) { 14795 if (mRoundScrollbarRenderer == null) { 14796 getStraightVerticalScrollBarBounds(bounds); 14797 } else { 14798 getRoundVerticalScrollBarBounds(bounds); 14799 } 14800 } 14801 14802 private void getRoundVerticalScrollBarBounds(Rect bounds) { 14803 final int width = mRight - mLeft; 14804 final int height = mBottom - mTop; 14805 // Do not take padding into account as we always want the scrollbars 14806 // to hug the screen for round wearable devices. 14807 bounds.left = mScrollX; 14808 bounds.top = mScrollY; 14809 bounds.right = bounds.left + width; 14810 bounds.bottom = mScrollY + height; 14811 } 14812 14813 private void getStraightVerticalScrollBarBounds(Rect bounds) { 14814 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14815 final int size = getVerticalScrollbarWidth(); 14816 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14817 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14818 verticalScrollbarPosition = isLayoutRtl() ? 14819 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14820 } 14821 final int width = mRight - mLeft; 14822 final int height = mBottom - mTop; 14823 switch (verticalScrollbarPosition) { 14824 default: 14825 case SCROLLBAR_POSITION_RIGHT: 14826 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14827 break; 14828 case SCROLLBAR_POSITION_LEFT: 14829 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14830 break; 14831 } 14832 bounds.top = mScrollY + (mPaddingTop & inside); 14833 bounds.right = bounds.left + size; 14834 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14835 } 14836 14837 /** 14838 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14839 * scrollbars are painted only if they have been awakened first.</p> 14840 * 14841 * @param canvas the canvas on which to draw the scrollbars 14842 * 14843 * @see #awakenScrollBars(int) 14844 */ 14845 protected final void onDrawScrollBars(Canvas canvas) { 14846 // scrollbars are drawn only when the animation is running 14847 final ScrollabilityCache cache = mScrollCache; 14848 14849 if (cache != null) { 14850 14851 int state = cache.state; 14852 14853 if (state == ScrollabilityCache.OFF) { 14854 return; 14855 } 14856 14857 boolean invalidate = false; 14858 14859 if (state == ScrollabilityCache.FADING) { 14860 // We're fading -- get our fade interpolation 14861 if (cache.interpolatorValues == null) { 14862 cache.interpolatorValues = new float[1]; 14863 } 14864 14865 float[] values = cache.interpolatorValues; 14866 14867 // Stops the animation if we're done 14868 if (cache.scrollBarInterpolator.timeToValues(values) == 14869 Interpolator.Result.FREEZE_END) { 14870 cache.state = ScrollabilityCache.OFF; 14871 } else { 14872 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14873 } 14874 14875 // This will make the scroll bars inval themselves after 14876 // drawing. We only want this when we're fading so that 14877 // we prevent excessive redraws 14878 invalidate = true; 14879 } else { 14880 // We're just on -- but we may have been fading before so 14881 // reset alpha 14882 cache.scrollBar.mutate().setAlpha(255); 14883 } 14884 14885 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14886 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14887 && !isVerticalScrollBarHidden(); 14888 14889 // Fork out the scroll bar drawing for round wearable devices. 14890 if (mRoundScrollbarRenderer != null) { 14891 if (drawVerticalScrollBar) { 14892 final Rect bounds = cache.mScrollBarBounds; 14893 getVerticalScrollBarBounds(bounds); 14894 mRoundScrollbarRenderer.drawRoundScrollbars( 14895 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 14896 if (invalidate) { 14897 invalidate(); 14898 } 14899 } 14900 // Do not draw horizontal scroll bars for round wearable devices. 14901 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14902 final ScrollBarDrawable scrollBar = cache.scrollBar; 14903 14904 if (drawHorizontalScrollBar) { 14905 scrollBar.setParameters(computeHorizontalScrollRange(), 14906 computeHorizontalScrollOffset(), 14907 computeHorizontalScrollExtent(), false); 14908 final Rect bounds = cache.mScrollBarBounds; 14909 getHorizontalScrollBarBounds(bounds); 14910 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14911 bounds.right, bounds.bottom); 14912 if (invalidate) { 14913 invalidate(bounds); 14914 } 14915 } 14916 14917 if (drawVerticalScrollBar) { 14918 scrollBar.setParameters(computeVerticalScrollRange(), 14919 computeVerticalScrollOffset(), 14920 computeVerticalScrollExtent(), true); 14921 final Rect bounds = cache.mScrollBarBounds; 14922 getVerticalScrollBarBounds(bounds); 14923 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14924 bounds.right, bounds.bottom); 14925 if (invalidate) { 14926 invalidate(bounds); 14927 } 14928 } 14929 } 14930 } 14931 } 14932 14933 /** 14934 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14935 * FastScroller is visible. 14936 * @return whether to temporarily hide the vertical scrollbar 14937 * @hide 14938 */ 14939 protected boolean isVerticalScrollBarHidden() { 14940 return false; 14941 } 14942 14943 /** 14944 * <p>Draw the horizontal scrollbar if 14945 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14946 * 14947 * @param canvas the canvas on which to draw the scrollbar 14948 * @param scrollBar the scrollbar's drawable 14949 * 14950 * @see #isHorizontalScrollBarEnabled() 14951 * @see #computeHorizontalScrollRange() 14952 * @see #computeHorizontalScrollExtent() 14953 * @see #computeHorizontalScrollOffset() 14954 * @see android.widget.ScrollBarDrawable 14955 * @hide 14956 */ 14957 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14958 int l, int t, int r, int b) { 14959 scrollBar.setBounds(l, t, r, b); 14960 scrollBar.draw(canvas); 14961 } 14962 14963 /** 14964 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14965 * returns true.</p> 14966 * 14967 * @param canvas the canvas on which to draw the scrollbar 14968 * @param scrollBar the scrollbar's drawable 14969 * 14970 * @see #isVerticalScrollBarEnabled() 14971 * @see #computeVerticalScrollRange() 14972 * @see #computeVerticalScrollExtent() 14973 * @see #computeVerticalScrollOffset() 14974 * @see android.widget.ScrollBarDrawable 14975 * @hide 14976 */ 14977 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14978 int l, int t, int r, int b) { 14979 scrollBar.setBounds(l, t, r, b); 14980 scrollBar.draw(canvas); 14981 } 14982 14983 /** 14984 * Implement this to do your drawing. 14985 * 14986 * @param canvas the canvas on which the background will be drawn 14987 */ 14988 protected void onDraw(Canvas canvas) { 14989 } 14990 14991 /* 14992 * Caller is responsible for calling requestLayout if necessary. 14993 * (This allows addViewInLayout to not request a new layout.) 14994 */ 14995 void assignParent(ViewParent parent) { 14996 if (mParent == null) { 14997 mParent = parent; 14998 } else if (parent == null) { 14999 mParent = null; 15000 } else { 15001 throw new RuntimeException("view " + this + " being added, but" 15002 + " it already has a parent"); 15003 } 15004 } 15005 15006 /** 15007 * This is called when the view is attached to a window. At this point it 15008 * has a Surface and will start drawing. Note that this function is 15009 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 15010 * however it may be called any time before the first onDraw -- including 15011 * before or after {@link #onMeasure(int, int)}. 15012 * 15013 * @see #onDetachedFromWindow() 15014 */ 15015 @CallSuper 15016 protected void onAttachedToWindow() { 15017 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 15018 mParent.requestTransparentRegion(this); 15019 } 15020 15021 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15022 15023 jumpDrawablesToCurrentState(); 15024 15025 resetSubtreeAccessibilityStateChanged(); 15026 15027 // rebuild, since Outline not maintained while View is detached 15028 rebuildOutline(); 15029 15030 if (isFocused()) { 15031 InputMethodManager imm = InputMethodManager.peekInstance(); 15032 if (imm != null) { 15033 imm.focusIn(this); 15034 } 15035 } 15036 } 15037 15038 /** 15039 * Resolve all RTL related properties. 15040 * 15041 * @return true if resolution of RTL properties has been done 15042 * 15043 * @hide 15044 */ 15045 public boolean resolveRtlPropertiesIfNeeded() { 15046 if (!needRtlPropertiesResolution()) return false; 15047 15048 // Order is important here: LayoutDirection MUST be resolved first 15049 if (!isLayoutDirectionResolved()) { 15050 resolveLayoutDirection(); 15051 resolveLayoutParams(); 15052 } 15053 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 15054 if (!isTextDirectionResolved()) { 15055 resolveTextDirection(); 15056 } 15057 if (!isTextAlignmentResolved()) { 15058 resolveTextAlignment(); 15059 } 15060 // Should resolve Drawables before Padding because we need the layout direction of the 15061 // Drawable to correctly resolve Padding. 15062 if (!areDrawablesResolved()) { 15063 resolveDrawables(); 15064 } 15065 if (!isPaddingResolved()) { 15066 resolvePadding(); 15067 } 15068 onRtlPropertiesChanged(getLayoutDirection()); 15069 return true; 15070 } 15071 15072 /** 15073 * Reset resolution of all RTL related properties. 15074 * 15075 * @hide 15076 */ 15077 public void resetRtlProperties() { 15078 resetResolvedLayoutDirection(); 15079 resetResolvedTextDirection(); 15080 resetResolvedTextAlignment(); 15081 resetResolvedPadding(); 15082 resetResolvedDrawables(); 15083 } 15084 15085 /** 15086 * @see #onScreenStateChanged(int) 15087 */ 15088 void dispatchScreenStateChanged(int screenState) { 15089 onScreenStateChanged(screenState); 15090 } 15091 15092 /** 15093 * This method is called whenever the state of the screen this view is 15094 * attached to changes. A state change will usually occurs when the screen 15095 * turns on or off (whether it happens automatically or the user does it 15096 * manually.) 15097 * 15098 * @param screenState The new state of the screen. Can be either 15099 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 15100 */ 15101 public void onScreenStateChanged(int screenState) { 15102 } 15103 15104 /** 15105 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 15106 */ 15107 private boolean hasRtlSupport() { 15108 return mContext.getApplicationInfo().hasRtlSupport(); 15109 } 15110 15111 /** 15112 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 15113 * RTL not supported) 15114 */ 15115 private boolean isRtlCompatibilityMode() { 15116 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 15117 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 15118 } 15119 15120 /** 15121 * @return true if RTL properties need resolution. 15122 * 15123 */ 15124 private boolean needRtlPropertiesResolution() { 15125 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15126 } 15127 15128 /** 15129 * Called when any RTL property (layout direction or text direction or text alignment) has 15130 * been changed. 15131 * 15132 * Subclasses need to override this method to take care of cached information that depends on the 15133 * resolved layout direction, or to inform child views that inherit their layout direction. 15134 * 15135 * The default implementation does nothing. 15136 * 15137 * @param layoutDirection the direction of the layout 15138 * 15139 * @see #LAYOUT_DIRECTION_LTR 15140 * @see #LAYOUT_DIRECTION_RTL 15141 */ 15142 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15143 } 15144 15145 /** 15146 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15147 * that the parent directionality can and will be resolved before its children. 15148 * 15149 * @return true if resolution has been done, false otherwise. 15150 * 15151 * @hide 15152 */ 15153 public boolean resolveLayoutDirection() { 15154 // Clear any previous layout direction resolution 15155 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15156 15157 if (hasRtlSupport()) { 15158 // Set resolved depending on layout direction 15159 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15160 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15161 case LAYOUT_DIRECTION_INHERIT: 15162 // We cannot resolve yet. LTR is by default and let the resolution happen again 15163 // later to get the correct resolved value 15164 if (!canResolveLayoutDirection()) return false; 15165 15166 // Parent has not yet resolved, LTR is still the default 15167 try { 15168 if (!mParent.isLayoutDirectionResolved()) return false; 15169 15170 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15171 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15172 } 15173 } catch (AbstractMethodError e) { 15174 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15175 " does not fully implement ViewParent", e); 15176 } 15177 break; 15178 case LAYOUT_DIRECTION_RTL: 15179 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15180 break; 15181 case LAYOUT_DIRECTION_LOCALE: 15182 if((LAYOUT_DIRECTION_RTL == 15183 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15184 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15185 } 15186 break; 15187 default: 15188 // Nothing to do, LTR by default 15189 } 15190 } 15191 15192 // Set to resolved 15193 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15194 return true; 15195 } 15196 15197 /** 15198 * Check if layout direction resolution can be done. 15199 * 15200 * @return true if layout direction resolution can be done otherwise return false. 15201 */ 15202 public boolean canResolveLayoutDirection() { 15203 switch (getRawLayoutDirection()) { 15204 case LAYOUT_DIRECTION_INHERIT: 15205 if (mParent != null) { 15206 try { 15207 return mParent.canResolveLayoutDirection(); 15208 } catch (AbstractMethodError e) { 15209 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15210 " does not fully implement ViewParent", e); 15211 } 15212 } 15213 return false; 15214 15215 default: 15216 return true; 15217 } 15218 } 15219 15220 /** 15221 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15222 * {@link #onMeasure(int, int)}. 15223 * 15224 * @hide 15225 */ 15226 public void resetResolvedLayoutDirection() { 15227 // Reset the current resolved bits 15228 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15229 } 15230 15231 /** 15232 * @return true if the layout direction is inherited. 15233 * 15234 * @hide 15235 */ 15236 public boolean isLayoutDirectionInherited() { 15237 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15238 } 15239 15240 /** 15241 * @return true if layout direction has been resolved. 15242 */ 15243 public boolean isLayoutDirectionResolved() { 15244 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15245 } 15246 15247 /** 15248 * Return if padding has been resolved 15249 * 15250 * @hide 15251 */ 15252 boolean isPaddingResolved() { 15253 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15254 } 15255 15256 /** 15257 * Resolves padding depending on layout direction, if applicable, and 15258 * recomputes internal padding values to adjust for scroll bars. 15259 * 15260 * @hide 15261 */ 15262 public void resolvePadding() { 15263 final int resolvedLayoutDirection = getLayoutDirection(); 15264 15265 if (!isRtlCompatibilityMode()) { 15266 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15267 // If start / end padding are defined, they will be resolved (hence overriding) to 15268 // left / right or right / left depending on the resolved layout direction. 15269 // If start / end padding are not defined, use the left / right ones. 15270 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15271 Rect padding = sThreadLocal.get(); 15272 if (padding == null) { 15273 padding = new Rect(); 15274 sThreadLocal.set(padding); 15275 } 15276 mBackground.getPadding(padding); 15277 if (!mLeftPaddingDefined) { 15278 mUserPaddingLeftInitial = padding.left; 15279 } 15280 if (!mRightPaddingDefined) { 15281 mUserPaddingRightInitial = padding.right; 15282 } 15283 } 15284 switch (resolvedLayoutDirection) { 15285 case LAYOUT_DIRECTION_RTL: 15286 if (mUserPaddingStart != UNDEFINED_PADDING) { 15287 mUserPaddingRight = mUserPaddingStart; 15288 } else { 15289 mUserPaddingRight = mUserPaddingRightInitial; 15290 } 15291 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15292 mUserPaddingLeft = mUserPaddingEnd; 15293 } else { 15294 mUserPaddingLeft = mUserPaddingLeftInitial; 15295 } 15296 break; 15297 case LAYOUT_DIRECTION_LTR: 15298 default: 15299 if (mUserPaddingStart != UNDEFINED_PADDING) { 15300 mUserPaddingLeft = mUserPaddingStart; 15301 } else { 15302 mUserPaddingLeft = mUserPaddingLeftInitial; 15303 } 15304 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15305 mUserPaddingRight = mUserPaddingEnd; 15306 } else { 15307 mUserPaddingRight = mUserPaddingRightInitial; 15308 } 15309 } 15310 15311 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15312 } 15313 15314 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15315 onRtlPropertiesChanged(resolvedLayoutDirection); 15316 15317 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15318 } 15319 15320 /** 15321 * Reset the resolved layout direction. 15322 * 15323 * @hide 15324 */ 15325 public void resetResolvedPadding() { 15326 resetResolvedPaddingInternal(); 15327 } 15328 15329 /** 15330 * Used when we only want to reset *this* view's padding and not trigger overrides 15331 * in ViewGroup that reset children too. 15332 */ 15333 void resetResolvedPaddingInternal() { 15334 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15335 } 15336 15337 /** 15338 * This is called when the view is detached from a window. At this point it 15339 * no longer has a surface for drawing. 15340 * 15341 * @see #onAttachedToWindow() 15342 */ 15343 @CallSuper 15344 protected void onDetachedFromWindow() { 15345 } 15346 15347 /** 15348 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15349 * after onDetachedFromWindow(). 15350 * 15351 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15352 * The super method should be called at the end of the overridden method to ensure 15353 * subclasses are destroyed first 15354 * 15355 * @hide 15356 */ 15357 @CallSuper 15358 protected void onDetachedFromWindowInternal() { 15359 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15360 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15361 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15362 15363 removeUnsetPressCallback(); 15364 removeLongPressCallback(); 15365 removePerformClickCallback(); 15366 removeSendViewScrolledAccessibilityEventCallback(); 15367 stopNestedScroll(); 15368 15369 // Anything that started animating right before detach should already 15370 // be in its final state when re-attached. 15371 jumpDrawablesToCurrentState(); 15372 15373 destroyDrawingCache(); 15374 15375 cleanupDraw(); 15376 mCurrentAnimation = null; 15377 } 15378 15379 private void cleanupDraw() { 15380 resetDisplayList(); 15381 if (mAttachInfo != null) { 15382 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15383 } 15384 } 15385 15386 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15387 } 15388 15389 /** 15390 * @return The number of times this view has been attached to a window 15391 */ 15392 protected int getWindowAttachCount() { 15393 return mWindowAttachCount; 15394 } 15395 15396 /** 15397 * Retrieve a unique token identifying the window this view is attached to. 15398 * @return Return the window's token for use in 15399 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15400 */ 15401 public IBinder getWindowToken() { 15402 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15403 } 15404 15405 /** 15406 * Retrieve the {@link WindowId} for the window this view is 15407 * currently attached to. 15408 */ 15409 public WindowId getWindowId() { 15410 if (mAttachInfo == null) { 15411 return null; 15412 } 15413 if (mAttachInfo.mWindowId == null) { 15414 try { 15415 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15416 mAttachInfo.mWindowToken); 15417 mAttachInfo.mWindowId = new WindowId( 15418 mAttachInfo.mIWindowId); 15419 } catch (RemoteException e) { 15420 } 15421 } 15422 return mAttachInfo.mWindowId; 15423 } 15424 15425 /** 15426 * Retrieve a unique token identifying the top-level "real" window of 15427 * the window that this view is attached to. That is, this is like 15428 * {@link #getWindowToken}, except if the window this view in is a panel 15429 * window (attached to another containing window), then the token of 15430 * the containing window is returned instead. 15431 * 15432 * @return Returns the associated window token, either 15433 * {@link #getWindowToken()} or the containing window's token. 15434 */ 15435 public IBinder getApplicationWindowToken() { 15436 AttachInfo ai = mAttachInfo; 15437 if (ai != null) { 15438 IBinder appWindowToken = ai.mPanelParentWindowToken; 15439 if (appWindowToken == null) { 15440 appWindowToken = ai.mWindowToken; 15441 } 15442 return appWindowToken; 15443 } 15444 return null; 15445 } 15446 15447 /** 15448 * Gets the logical display to which the view's window has been attached. 15449 * 15450 * @return The logical display, or null if the view is not currently attached to a window. 15451 */ 15452 public Display getDisplay() { 15453 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15454 } 15455 15456 /** 15457 * Retrieve private session object this view hierarchy is using to 15458 * communicate with the window manager. 15459 * @return the session object to communicate with the window manager 15460 */ 15461 /*package*/ IWindowSession getWindowSession() { 15462 return mAttachInfo != null ? mAttachInfo.mSession : null; 15463 } 15464 15465 /** 15466 * Return the visibility value of the least visible component passed. 15467 */ 15468 int combineVisibility(int vis1, int vis2) { 15469 // This works because VISIBLE < INVISIBLE < GONE. 15470 return Math.max(vis1, vis2); 15471 } 15472 15473 /** 15474 * @param info the {@link android.view.View.AttachInfo} to associated with 15475 * this view 15476 */ 15477 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15478 mAttachInfo = info; 15479 if (mOverlay != null) { 15480 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15481 } 15482 mWindowAttachCount++; 15483 // We will need to evaluate the drawable state at least once. 15484 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15485 if (mFloatingTreeObserver != null) { 15486 info.mTreeObserver.merge(mFloatingTreeObserver); 15487 mFloatingTreeObserver = null; 15488 } 15489 15490 registerPendingFrameMetricsObservers(); 15491 15492 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15493 mAttachInfo.mScrollContainers.add(this); 15494 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15495 } 15496 // Transfer all pending runnables. 15497 if (mRunQueue != null) { 15498 mRunQueue.executeActions(info.mHandler); 15499 mRunQueue = null; 15500 } 15501 performCollectViewAttributes(mAttachInfo, visibility); 15502 onAttachedToWindow(); 15503 15504 ListenerInfo li = mListenerInfo; 15505 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15506 li != null ? li.mOnAttachStateChangeListeners : null; 15507 if (listeners != null && listeners.size() > 0) { 15508 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15509 // perform the dispatching. The iterator is a safe guard against listeners that 15510 // could mutate the list by calling the various add/remove methods. This prevents 15511 // the array from being modified while we iterate it. 15512 for (OnAttachStateChangeListener listener : listeners) { 15513 listener.onViewAttachedToWindow(this); 15514 } 15515 } 15516 15517 int vis = info.mWindowVisibility; 15518 if (vis != GONE) { 15519 onWindowVisibilityChanged(vis); 15520 if (isShown()) { 15521 // Calling onVisibilityAggregated directly here since the subtree will also 15522 // receive dispatchAttachedToWindow and this same call 15523 onVisibilityAggregated(vis == VISIBLE); 15524 } 15525 } 15526 15527 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15528 // As all views in the subtree will already receive dispatchAttachedToWindow 15529 // traversing the subtree again here is not desired. 15530 onVisibilityChanged(this, visibility); 15531 15532 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15533 // If nobody has evaluated the drawable state yet, then do it now. 15534 refreshDrawableState(); 15535 } 15536 needGlobalAttributesUpdate(false); 15537 } 15538 15539 void dispatchDetachedFromWindow() { 15540 AttachInfo info = mAttachInfo; 15541 if (info != null) { 15542 int vis = info.mWindowVisibility; 15543 if (vis != GONE) { 15544 onWindowVisibilityChanged(GONE); 15545 if (isShown()) { 15546 // Invoking onVisibilityAggregated directly here since the subtree 15547 // will also receive detached from window 15548 onVisibilityAggregated(false); 15549 } 15550 } 15551 } 15552 15553 onDetachedFromWindow(); 15554 onDetachedFromWindowInternal(); 15555 15556 InputMethodManager imm = InputMethodManager.peekInstance(); 15557 if (imm != null) { 15558 imm.onViewDetachedFromWindow(this); 15559 } 15560 15561 ListenerInfo li = mListenerInfo; 15562 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15563 li != null ? li.mOnAttachStateChangeListeners : null; 15564 if (listeners != null && listeners.size() > 0) { 15565 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15566 // perform the dispatching. The iterator is a safe guard against listeners that 15567 // could mutate the list by calling the various add/remove methods. This prevents 15568 // the array from being modified while we iterate it. 15569 for (OnAttachStateChangeListener listener : listeners) { 15570 listener.onViewDetachedFromWindow(this); 15571 } 15572 } 15573 15574 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15575 mAttachInfo.mScrollContainers.remove(this); 15576 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15577 } 15578 15579 mAttachInfo = null; 15580 if (mOverlay != null) { 15581 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15582 } 15583 } 15584 15585 /** 15586 * Cancel any deferred high-level input events that were previously posted to the event queue. 15587 * 15588 * <p>Many views post high-level events such as click handlers to the event queue 15589 * to run deferred in order to preserve a desired user experience - clearing visible 15590 * pressed states before executing, etc. This method will abort any events of this nature 15591 * that are currently in flight.</p> 15592 * 15593 * <p>Custom views that generate their own high-level deferred input events should override 15594 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15595 * 15596 * <p>This will also cancel pending input events for any child views.</p> 15597 * 15598 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15599 * This will not impact newer events posted after this call that may occur as a result of 15600 * lower-level input events still waiting in the queue. If you are trying to prevent 15601 * double-submitted events for the duration of some sort of asynchronous transaction 15602 * you should also take other steps to protect against unexpected double inputs e.g. calling 15603 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15604 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15605 */ 15606 public final void cancelPendingInputEvents() { 15607 dispatchCancelPendingInputEvents(); 15608 } 15609 15610 /** 15611 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15612 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15613 */ 15614 void dispatchCancelPendingInputEvents() { 15615 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15616 onCancelPendingInputEvents(); 15617 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15618 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15619 " did not call through to super.onCancelPendingInputEvents()"); 15620 } 15621 } 15622 15623 /** 15624 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15625 * a parent view. 15626 * 15627 * <p>This method is responsible for removing any pending high-level input events that were 15628 * posted to the event queue to run later. Custom view classes that post their own deferred 15629 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15630 * {@link android.os.Handler} should override this method, call 15631 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15632 * </p> 15633 */ 15634 public void onCancelPendingInputEvents() { 15635 removePerformClickCallback(); 15636 cancelLongPress(); 15637 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15638 } 15639 15640 /** 15641 * Store this view hierarchy's frozen state into the given container. 15642 * 15643 * @param container The SparseArray in which to save the view's state. 15644 * 15645 * @see #restoreHierarchyState(android.util.SparseArray) 15646 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15647 * @see #onSaveInstanceState() 15648 */ 15649 public void saveHierarchyState(SparseArray<Parcelable> container) { 15650 dispatchSaveInstanceState(container); 15651 } 15652 15653 /** 15654 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15655 * this view and its children. May be overridden to modify how freezing happens to a 15656 * view's children; for example, some views may want to not store state for their children. 15657 * 15658 * @param container The SparseArray in which to save the view's state. 15659 * 15660 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15661 * @see #saveHierarchyState(android.util.SparseArray) 15662 * @see #onSaveInstanceState() 15663 */ 15664 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15665 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15666 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15667 Parcelable state = onSaveInstanceState(); 15668 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15669 throw new IllegalStateException( 15670 "Derived class did not call super.onSaveInstanceState()"); 15671 } 15672 if (state != null) { 15673 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15674 // + ": " + state); 15675 container.put(mID, state); 15676 } 15677 } 15678 } 15679 15680 /** 15681 * Hook allowing a view to generate a representation of its internal state 15682 * that can later be used to create a new instance with that same state. 15683 * This state should only contain information that is not persistent or can 15684 * not be reconstructed later. For example, you will never store your 15685 * current position on screen because that will be computed again when a 15686 * new instance of the view is placed in its view hierarchy. 15687 * <p> 15688 * Some examples of things you may store here: the current cursor position 15689 * in a text view (but usually not the text itself since that is stored in a 15690 * content provider or other persistent storage), the currently selected 15691 * item in a list view. 15692 * 15693 * @return Returns a Parcelable object containing the view's current dynamic 15694 * state, or null if there is nothing interesting to save. The 15695 * default implementation returns null. 15696 * @see #onRestoreInstanceState(android.os.Parcelable) 15697 * @see #saveHierarchyState(android.util.SparseArray) 15698 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15699 * @see #setSaveEnabled(boolean) 15700 */ 15701 @CallSuper 15702 protected Parcelable onSaveInstanceState() { 15703 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15704 if (mStartActivityRequestWho != null) { 15705 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15706 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15707 return state; 15708 } 15709 return BaseSavedState.EMPTY_STATE; 15710 } 15711 15712 /** 15713 * Restore this view hierarchy's frozen state from the given container. 15714 * 15715 * @param container The SparseArray which holds previously frozen states. 15716 * 15717 * @see #saveHierarchyState(android.util.SparseArray) 15718 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15719 * @see #onRestoreInstanceState(android.os.Parcelable) 15720 */ 15721 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15722 dispatchRestoreInstanceState(container); 15723 } 15724 15725 /** 15726 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15727 * state for this view and its children. May be overridden to modify how restoring 15728 * happens to a view's children; for example, some views may want to not store state 15729 * for their children. 15730 * 15731 * @param container The SparseArray which holds previously saved state. 15732 * 15733 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15734 * @see #restoreHierarchyState(android.util.SparseArray) 15735 * @see #onRestoreInstanceState(android.os.Parcelable) 15736 */ 15737 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15738 if (mID != NO_ID) { 15739 Parcelable state = container.get(mID); 15740 if (state != null) { 15741 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15742 // + ": " + state); 15743 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15744 onRestoreInstanceState(state); 15745 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15746 throw new IllegalStateException( 15747 "Derived class did not call super.onRestoreInstanceState()"); 15748 } 15749 } 15750 } 15751 } 15752 15753 /** 15754 * Hook allowing a view to re-apply a representation of its internal state that had previously 15755 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15756 * null state. 15757 * 15758 * @param state The frozen state that had previously been returned by 15759 * {@link #onSaveInstanceState}. 15760 * 15761 * @see #onSaveInstanceState() 15762 * @see #restoreHierarchyState(android.util.SparseArray) 15763 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15764 */ 15765 @CallSuper 15766 protected void onRestoreInstanceState(Parcelable state) { 15767 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15768 if (state != null && !(state instanceof AbsSavedState)) { 15769 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15770 + "received " + state.getClass().toString() + " instead. This usually happens " 15771 + "when two views of different type have the same id in the same hierarchy. " 15772 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15773 + "other views do not use the same id."); 15774 } 15775 if (state != null && state instanceof BaseSavedState) { 15776 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15777 } 15778 } 15779 15780 /** 15781 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15782 * 15783 * @return the drawing start time in milliseconds 15784 */ 15785 public long getDrawingTime() { 15786 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15787 } 15788 15789 /** 15790 * <p>Enables or disables the duplication of the parent's state into this view. When 15791 * duplication is enabled, this view gets its drawable state from its parent rather 15792 * than from its own internal properties.</p> 15793 * 15794 * <p>Note: in the current implementation, setting this property to true after the 15795 * view was added to a ViewGroup might have no effect at all. This property should 15796 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15797 * 15798 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15799 * property is enabled, an exception will be thrown.</p> 15800 * 15801 * <p>Note: if the child view uses and updates additional states which are unknown to the 15802 * parent, these states should not be affected by this method.</p> 15803 * 15804 * @param enabled True to enable duplication of the parent's drawable state, false 15805 * to disable it. 15806 * 15807 * @see #getDrawableState() 15808 * @see #isDuplicateParentStateEnabled() 15809 */ 15810 public void setDuplicateParentStateEnabled(boolean enabled) { 15811 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15812 } 15813 15814 /** 15815 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15816 * 15817 * @return True if this view's drawable state is duplicated from the parent, 15818 * false otherwise 15819 * 15820 * @see #getDrawableState() 15821 * @see #setDuplicateParentStateEnabled(boolean) 15822 */ 15823 public boolean isDuplicateParentStateEnabled() { 15824 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15825 } 15826 15827 /** 15828 * <p>Specifies the type of layer backing this view. The layer can be 15829 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15830 * {@link #LAYER_TYPE_HARDWARE}.</p> 15831 * 15832 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15833 * instance that controls how the layer is composed on screen. The following 15834 * properties of the paint are taken into account when composing the layer:</p> 15835 * <ul> 15836 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15837 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15838 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15839 * </ul> 15840 * 15841 * <p>If this view has an alpha value set to < 1.0 by calling 15842 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15843 * by this view's alpha value.</p> 15844 * 15845 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15846 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15847 * for more information on when and how to use layers.</p> 15848 * 15849 * @param layerType The type of layer to use with this view, must be one of 15850 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15851 * {@link #LAYER_TYPE_HARDWARE} 15852 * @param paint The paint used to compose the layer. This argument is optional 15853 * and can be null. It is ignored when the layer type is 15854 * {@link #LAYER_TYPE_NONE} 15855 * 15856 * @see #getLayerType() 15857 * @see #LAYER_TYPE_NONE 15858 * @see #LAYER_TYPE_SOFTWARE 15859 * @see #LAYER_TYPE_HARDWARE 15860 * @see #setAlpha(float) 15861 * 15862 * @attr ref android.R.styleable#View_layerType 15863 */ 15864 public void setLayerType(int layerType, @Nullable Paint paint) { 15865 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15866 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15867 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15868 } 15869 15870 boolean typeChanged = mRenderNode.setLayerType(layerType); 15871 15872 if (!typeChanged) { 15873 setLayerPaint(paint); 15874 return; 15875 } 15876 15877 if (layerType != LAYER_TYPE_SOFTWARE) { 15878 // Destroy any previous software drawing cache if present 15879 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 15880 // drawing cache created in View#draw when drawing to a SW canvas. 15881 destroyDrawingCache(); 15882 } 15883 15884 mLayerType = layerType; 15885 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15886 mRenderNode.setLayerPaint(mLayerPaint); 15887 15888 // draw() behaves differently if we are on a layer, so we need to 15889 // invalidate() here 15890 invalidateParentCaches(); 15891 invalidate(true); 15892 } 15893 15894 /** 15895 * Updates the {@link Paint} object used with the current layer (used only if the current 15896 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15897 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15898 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15899 * ensure that the view gets redrawn immediately. 15900 * 15901 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15902 * instance that controls how the layer is composed on screen. The following 15903 * properties of the paint are taken into account when composing the layer:</p> 15904 * <ul> 15905 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15906 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15907 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15908 * </ul> 15909 * 15910 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15911 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15912 * 15913 * @param paint The paint used to compose the layer. This argument is optional 15914 * and can be null. It is ignored when the layer type is 15915 * {@link #LAYER_TYPE_NONE} 15916 * 15917 * @see #setLayerType(int, android.graphics.Paint) 15918 */ 15919 public void setLayerPaint(@Nullable Paint paint) { 15920 int layerType = getLayerType(); 15921 if (layerType != LAYER_TYPE_NONE) { 15922 mLayerPaint = paint; 15923 if (layerType == LAYER_TYPE_HARDWARE) { 15924 if (mRenderNode.setLayerPaint(paint)) { 15925 invalidateViewProperty(false, false); 15926 } 15927 } else { 15928 invalidate(); 15929 } 15930 } 15931 } 15932 15933 /** 15934 * Indicates what type of layer is currently associated with this view. By default 15935 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15936 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15937 * for more information on the different types of layers. 15938 * 15939 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15940 * {@link #LAYER_TYPE_HARDWARE} 15941 * 15942 * @see #setLayerType(int, android.graphics.Paint) 15943 * @see #buildLayer() 15944 * @see #LAYER_TYPE_NONE 15945 * @see #LAYER_TYPE_SOFTWARE 15946 * @see #LAYER_TYPE_HARDWARE 15947 */ 15948 public int getLayerType() { 15949 return mLayerType; 15950 } 15951 15952 /** 15953 * Forces this view's layer to be created and this view to be rendered 15954 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15955 * invoking this method will have no effect. 15956 * 15957 * This method can for instance be used to render a view into its layer before 15958 * starting an animation. If this view is complex, rendering into the layer 15959 * before starting the animation will avoid skipping frames. 15960 * 15961 * @throws IllegalStateException If this view is not attached to a window 15962 * 15963 * @see #setLayerType(int, android.graphics.Paint) 15964 */ 15965 public void buildLayer() { 15966 if (mLayerType == LAYER_TYPE_NONE) return; 15967 15968 final AttachInfo attachInfo = mAttachInfo; 15969 if (attachInfo == null) { 15970 throw new IllegalStateException("This view must be attached to a window first"); 15971 } 15972 15973 if (getWidth() == 0 || getHeight() == 0) { 15974 return; 15975 } 15976 15977 switch (mLayerType) { 15978 case LAYER_TYPE_HARDWARE: 15979 updateDisplayListIfDirty(); 15980 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 15981 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 15982 } 15983 break; 15984 case LAYER_TYPE_SOFTWARE: 15985 buildDrawingCache(true); 15986 break; 15987 } 15988 } 15989 15990 /** 15991 * Destroys all hardware rendering resources. This method is invoked 15992 * when the system needs to reclaim resources. Upon execution of this 15993 * method, you should free any OpenGL resources created by the view. 15994 * 15995 * Note: you <strong>must</strong> call 15996 * <code>super.destroyHardwareResources()</code> when overriding 15997 * this method. 15998 * 15999 * @hide 16000 */ 16001 @CallSuper 16002 protected void destroyHardwareResources() { 16003 // Although the Layer will be destroyed by RenderNode, we want to release 16004 // the staging display list, which is also a signal to RenderNode that it's 16005 // safe to free its copy of the display list as it knows that we will 16006 // push an updated DisplayList if we try to draw again 16007 resetDisplayList(); 16008 } 16009 16010 /** 16011 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 16012 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 16013 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 16014 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 16015 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 16016 * null.</p> 16017 * 16018 * <p>Enabling the drawing cache is similar to 16019 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 16020 * acceleration is turned off. When hardware acceleration is turned on, enabling the 16021 * drawing cache has no effect on rendering because the system uses a different mechanism 16022 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 16023 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 16024 * for information on how to enable software and hardware layers.</p> 16025 * 16026 * <p>This API can be used to manually generate 16027 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 16028 * {@link #getDrawingCache()}.</p> 16029 * 16030 * @param enabled true to enable the drawing cache, false otherwise 16031 * 16032 * @see #isDrawingCacheEnabled() 16033 * @see #getDrawingCache() 16034 * @see #buildDrawingCache() 16035 * @see #setLayerType(int, android.graphics.Paint) 16036 */ 16037 public void setDrawingCacheEnabled(boolean enabled) { 16038 mCachingFailed = false; 16039 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 16040 } 16041 16042 /** 16043 * <p>Indicates whether the drawing cache is enabled for this view.</p> 16044 * 16045 * @return true if the drawing cache is enabled 16046 * 16047 * @see #setDrawingCacheEnabled(boolean) 16048 * @see #getDrawingCache() 16049 */ 16050 @ViewDebug.ExportedProperty(category = "drawing") 16051 public boolean isDrawingCacheEnabled() { 16052 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 16053 } 16054 16055 /** 16056 * Debugging utility which recursively outputs the dirty state of a view and its 16057 * descendants. 16058 * 16059 * @hide 16060 */ 16061 @SuppressWarnings({"UnusedDeclaration"}) 16062 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 16063 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 16064 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 16065 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 16066 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 16067 if (clear) { 16068 mPrivateFlags &= clearMask; 16069 } 16070 if (this instanceof ViewGroup) { 16071 ViewGroup parent = (ViewGroup) this; 16072 final int count = parent.getChildCount(); 16073 for (int i = 0; i < count; i++) { 16074 final View child = parent.getChildAt(i); 16075 child.outputDirtyFlags(indent + " ", clear, clearMask); 16076 } 16077 } 16078 } 16079 16080 /** 16081 * This method is used by ViewGroup to cause its children to restore or recreate their 16082 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 16083 * to recreate its own display list, which would happen if it went through the normal 16084 * draw/dispatchDraw mechanisms. 16085 * 16086 * @hide 16087 */ 16088 protected void dispatchGetDisplayList() {} 16089 16090 /** 16091 * A view that is not attached or hardware accelerated cannot create a display list. 16092 * This method checks these conditions and returns the appropriate result. 16093 * 16094 * @return true if view has the ability to create a display list, false otherwise. 16095 * 16096 * @hide 16097 */ 16098 public boolean canHaveDisplayList() { 16099 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 16100 } 16101 16102 /** 16103 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 16104 * @hide 16105 */ 16106 @NonNull 16107 public RenderNode updateDisplayListIfDirty() { 16108 final RenderNode renderNode = mRenderNode; 16109 if (!canHaveDisplayList()) { 16110 // can't populate RenderNode, don't try 16111 return renderNode; 16112 } 16113 16114 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 16115 || !renderNode.isValid() 16116 || (mRecreateDisplayList)) { 16117 // Don't need to recreate the display list, just need to tell our 16118 // children to restore/recreate theirs 16119 if (renderNode.isValid() 16120 && !mRecreateDisplayList) { 16121 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16122 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16123 dispatchGetDisplayList(); 16124 16125 return renderNode; // no work needed 16126 } 16127 16128 // If we got here, we're recreating it. Mark it as such to ensure that 16129 // we copy in child display lists into ours in drawChild() 16130 mRecreateDisplayList = true; 16131 16132 int width = mRight - mLeft; 16133 int height = mBottom - mTop; 16134 int layerType = getLayerType(); 16135 16136 final DisplayListCanvas canvas = renderNode.start(width, height); 16137 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16138 16139 try { 16140 if (layerType == LAYER_TYPE_SOFTWARE) { 16141 buildDrawingCache(true); 16142 Bitmap cache = getDrawingCache(true); 16143 if (cache != null) { 16144 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16145 } 16146 } else { 16147 computeScroll(); 16148 16149 canvas.translate(-mScrollX, -mScrollY); 16150 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16151 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16152 16153 // Fast path for layouts with no backgrounds 16154 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16155 dispatchDraw(canvas); 16156 if (mOverlay != null && !mOverlay.isEmpty()) { 16157 mOverlay.getOverlayView().draw(canvas); 16158 } 16159 if (debugDraw()) { 16160 debugDrawFocus(canvas); 16161 } 16162 } else { 16163 draw(canvas); 16164 } 16165 } 16166 } finally { 16167 renderNode.end(canvas); 16168 setDisplayListProperties(renderNode); 16169 } 16170 } else { 16171 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16172 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16173 } 16174 return renderNode; 16175 } 16176 16177 private void resetDisplayList() { 16178 if (mRenderNode.isValid()) { 16179 mRenderNode.discardDisplayList(); 16180 } 16181 16182 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16183 mBackgroundRenderNode.discardDisplayList(); 16184 } 16185 } 16186 16187 /** 16188 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16189 * 16190 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16191 * 16192 * @see #getDrawingCache(boolean) 16193 */ 16194 public Bitmap getDrawingCache() { 16195 return getDrawingCache(false); 16196 } 16197 16198 /** 16199 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16200 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16201 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16202 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16203 * request the drawing cache by calling this method and draw it on screen if the 16204 * returned bitmap is not null.</p> 16205 * 16206 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16207 * this method will create a bitmap of the same size as this view. Because this bitmap 16208 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16209 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16210 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16211 * size than the view. This implies that your application must be able to handle this 16212 * size.</p> 16213 * 16214 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16215 * the current density of the screen when the application is in compatibility 16216 * mode. 16217 * 16218 * @return A bitmap representing this view or null if cache is disabled. 16219 * 16220 * @see #setDrawingCacheEnabled(boolean) 16221 * @see #isDrawingCacheEnabled() 16222 * @see #buildDrawingCache(boolean) 16223 * @see #destroyDrawingCache() 16224 */ 16225 public Bitmap getDrawingCache(boolean autoScale) { 16226 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16227 return null; 16228 } 16229 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16230 buildDrawingCache(autoScale); 16231 } 16232 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16233 } 16234 16235 /** 16236 * <p>Frees the resources used by the drawing cache. If you call 16237 * {@link #buildDrawingCache()} manually without calling 16238 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16239 * should cleanup the cache with this method afterwards.</p> 16240 * 16241 * @see #setDrawingCacheEnabled(boolean) 16242 * @see #buildDrawingCache() 16243 * @see #getDrawingCache() 16244 */ 16245 public void destroyDrawingCache() { 16246 if (mDrawingCache != null) { 16247 mDrawingCache.recycle(); 16248 mDrawingCache = null; 16249 } 16250 if (mUnscaledDrawingCache != null) { 16251 mUnscaledDrawingCache.recycle(); 16252 mUnscaledDrawingCache = null; 16253 } 16254 } 16255 16256 /** 16257 * Setting a solid background color for the drawing cache's bitmaps will improve 16258 * performance and memory usage. Note, though that this should only be used if this 16259 * view will always be drawn on top of a solid color. 16260 * 16261 * @param color The background color to use for the drawing cache's bitmap 16262 * 16263 * @see #setDrawingCacheEnabled(boolean) 16264 * @see #buildDrawingCache() 16265 * @see #getDrawingCache() 16266 */ 16267 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16268 if (color != mDrawingCacheBackgroundColor) { 16269 mDrawingCacheBackgroundColor = color; 16270 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16271 } 16272 } 16273 16274 /** 16275 * @see #setDrawingCacheBackgroundColor(int) 16276 * 16277 * @return The background color to used for the drawing cache's bitmap 16278 */ 16279 @ColorInt 16280 public int getDrawingCacheBackgroundColor() { 16281 return mDrawingCacheBackgroundColor; 16282 } 16283 16284 /** 16285 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16286 * 16287 * @see #buildDrawingCache(boolean) 16288 */ 16289 public void buildDrawingCache() { 16290 buildDrawingCache(false); 16291 } 16292 16293 /** 16294 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16295 * 16296 * <p>If you call {@link #buildDrawingCache()} manually without calling 16297 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16298 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16299 * 16300 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16301 * this method will create a bitmap of the same size as this view. Because this bitmap 16302 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16303 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16304 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16305 * size than the view. This implies that your application must be able to handle this 16306 * size.</p> 16307 * 16308 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16309 * you do not need the drawing cache bitmap, calling this method will increase memory 16310 * usage and cause the view to be rendered in software once, thus negatively impacting 16311 * performance.</p> 16312 * 16313 * @see #getDrawingCache() 16314 * @see #destroyDrawingCache() 16315 */ 16316 public void buildDrawingCache(boolean autoScale) { 16317 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16318 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16319 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16320 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16321 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16322 } 16323 try { 16324 buildDrawingCacheImpl(autoScale); 16325 } finally { 16326 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16327 } 16328 } 16329 } 16330 16331 /** 16332 * private, internal implementation of buildDrawingCache, used to enable tracing 16333 */ 16334 private void buildDrawingCacheImpl(boolean autoScale) { 16335 mCachingFailed = false; 16336 16337 int width = mRight - mLeft; 16338 int height = mBottom - mTop; 16339 16340 final AttachInfo attachInfo = mAttachInfo; 16341 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16342 16343 if (autoScale && scalingRequired) { 16344 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16345 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16346 } 16347 16348 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16349 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16350 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16351 16352 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16353 final long drawingCacheSize = 16354 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16355 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16356 if (width > 0 && height > 0) { 16357 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16358 + " too large to fit into a software layer (or drawing cache), needs " 16359 + projectedBitmapSize + " bytes, only " 16360 + drawingCacheSize + " available"); 16361 } 16362 destroyDrawingCache(); 16363 mCachingFailed = true; 16364 return; 16365 } 16366 16367 boolean clear = true; 16368 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16369 16370 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16371 Bitmap.Config quality; 16372 if (!opaque) { 16373 // Never pick ARGB_4444 because it looks awful 16374 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16375 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16376 case DRAWING_CACHE_QUALITY_AUTO: 16377 case DRAWING_CACHE_QUALITY_LOW: 16378 case DRAWING_CACHE_QUALITY_HIGH: 16379 default: 16380 quality = Bitmap.Config.ARGB_8888; 16381 break; 16382 } 16383 } else { 16384 // Optimization for translucent windows 16385 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16386 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16387 } 16388 16389 // Try to cleanup memory 16390 if (bitmap != null) bitmap.recycle(); 16391 16392 try { 16393 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16394 width, height, quality); 16395 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16396 if (autoScale) { 16397 mDrawingCache = bitmap; 16398 } else { 16399 mUnscaledDrawingCache = bitmap; 16400 } 16401 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16402 } catch (OutOfMemoryError e) { 16403 // If there is not enough memory to create the bitmap cache, just 16404 // ignore the issue as bitmap caches are not required to draw the 16405 // view hierarchy 16406 if (autoScale) { 16407 mDrawingCache = null; 16408 } else { 16409 mUnscaledDrawingCache = null; 16410 } 16411 mCachingFailed = true; 16412 return; 16413 } 16414 16415 clear = drawingCacheBackgroundColor != 0; 16416 } 16417 16418 Canvas canvas; 16419 if (attachInfo != null) { 16420 canvas = attachInfo.mCanvas; 16421 if (canvas == null) { 16422 canvas = new Canvas(); 16423 } 16424 canvas.setBitmap(bitmap); 16425 // Temporarily clobber the cached Canvas in case one of our children 16426 // is also using a drawing cache. Without this, the children would 16427 // steal the canvas by attaching their own bitmap to it and bad, bad 16428 // thing would happen (invisible views, corrupted drawings, etc.) 16429 attachInfo.mCanvas = null; 16430 } else { 16431 // This case should hopefully never or seldom happen 16432 canvas = new Canvas(bitmap); 16433 } 16434 16435 if (clear) { 16436 bitmap.eraseColor(drawingCacheBackgroundColor); 16437 } 16438 16439 computeScroll(); 16440 final int restoreCount = canvas.save(); 16441 16442 if (autoScale && scalingRequired) { 16443 final float scale = attachInfo.mApplicationScale; 16444 canvas.scale(scale, scale); 16445 } 16446 16447 canvas.translate(-mScrollX, -mScrollY); 16448 16449 mPrivateFlags |= PFLAG_DRAWN; 16450 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16451 mLayerType != LAYER_TYPE_NONE) { 16452 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16453 } 16454 16455 // Fast path for layouts with no backgrounds 16456 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16457 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16458 dispatchDraw(canvas); 16459 if (mOverlay != null && !mOverlay.isEmpty()) { 16460 mOverlay.getOverlayView().draw(canvas); 16461 } 16462 } else { 16463 draw(canvas); 16464 } 16465 16466 canvas.restoreToCount(restoreCount); 16467 canvas.setBitmap(null); 16468 16469 if (attachInfo != null) { 16470 // Restore the cached Canvas for our siblings 16471 attachInfo.mCanvas = canvas; 16472 } 16473 } 16474 16475 /** 16476 * Create a snapshot of the view into a bitmap. We should probably make 16477 * some form of this public, but should think about the API. 16478 * 16479 * @hide 16480 */ 16481 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16482 int width = mRight - mLeft; 16483 int height = mBottom - mTop; 16484 16485 final AttachInfo attachInfo = mAttachInfo; 16486 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16487 width = (int) ((width * scale) + 0.5f); 16488 height = (int) ((height * scale) + 0.5f); 16489 16490 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16491 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16492 if (bitmap == null) { 16493 throw new OutOfMemoryError(); 16494 } 16495 16496 Resources resources = getResources(); 16497 if (resources != null) { 16498 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16499 } 16500 16501 Canvas canvas; 16502 if (attachInfo != null) { 16503 canvas = attachInfo.mCanvas; 16504 if (canvas == null) { 16505 canvas = new Canvas(); 16506 } 16507 canvas.setBitmap(bitmap); 16508 // Temporarily clobber the cached Canvas in case one of our children 16509 // is also using a drawing cache. Without this, the children would 16510 // steal the canvas by attaching their own bitmap to it and bad, bad 16511 // things would happen (invisible views, corrupted drawings, etc.) 16512 attachInfo.mCanvas = null; 16513 } else { 16514 // This case should hopefully never or seldom happen 16515 canvas = new Canvas(bitmap); 16516 } 16517 16518 if ((backgroundColor & 0xff000000) != 0) { 16519 bitmap.eraseColor(backgroundColor); 16520 } 16521 16522 computeScroll(); 16523 final int restoreCount = canvas.save(); 16524 canvas.scale(scale, scale); 16525 canvas.translate(-mScrollX, -mScrollY); 16526 16527 // Temporarily remove the dirty mask 16528 int flags = mPrivateFlags; 16529 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16530 16531 // Fast path for layouts with no backgrounds 16532 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16533 dispatchDraw(canvas); 16534 if (mOverlay != null && !mOverlay.isEmpty()) { 16535 mOverlay.getOverlayView().draw(canvas); 16536 } 16537 } else { 16538 draw(canvas); 16539 } 16540 16541 mPrivateFlags = flags; 16542 16543 canvas.restoreToCount(restoreCount); 16544 canvas.setBitmap(null); 16545 16546 if (attachInfo != null) { 16547 // Restore the cached Canvas for our siblings 16548 attachInfo.mCanvas = canvas; 16549 } 16550 16551 return bitmap; 16552 } 16553 16554 /** 16555 * Indicates whether this View is currently in edit mode. A View is usually 16556 * in edit mode when displayed within a developer tool. For instance, if 16557 * this View is being drawn by a visual user interface builder, this method 16558 * should return true. 16559 * 16560 * Subclasses should check the return value of this method to provide 16561 * different behaviors if their normal behavior might interfere with the 16562 * host environment. For instance: the class spawns a thread in its 16563 * constructor, the drawing code relies on device-specific features, etc. 16564 * 16565 * This method is usually checked in the drawing code of custom widgets. 16566 * 16567 * @return True if this View is in edit mode, false otherwise. 16568 */ 16569 public boolean isInEditMode() { 16570 return false; 16571 } 16572 16573 /** 16574 * If the View draws content inside its padding and enables fading edges, 16575 * it needs to support padding offsets. Padding offsets are added to the 16576 * fading edges to extend the length of the fade so that it covers pixels 16577 * drawn inside the padding. 16578 * 16579 * Subclasses of this class should override this method if they need 16580 * to draw content inside the padding. 16581 * 16582 * @return True if padding offset must be applied, false otherwise. 16583 * 16584 * @see #getLeftPaddingOffset() 16585 * @see #getRightPaddingOffset() 16586 * @see #getTopPaddingOffset() 16587 * @see #getBottomPaddingOffset() 16588 * 16589 * @since CURRENT 16590 */ 16591 protected boolean isPaddingOffsetRequired() { 16592 return false; 16593 } 16594 16595 /** 16596 * Amount by which to extend the left fading region. Called only when 16597 * {@link #isPaddingOffsetRequired()} returns true. 16598 * 16599 * @return The left padding offset in pixels. 16600 * 16601 * @see #isPaddingOffsetRequired() 16602 * 16603 * @since CURRENT 16604 */ 16605 protected int getLeftPaddingOffset() { 16606 return 0; 16607 } 16608 16609 /** 16610 * Amount by which to extend the right fading region. Called only when 16611 * {@link #isPaddingOffsetRequired()} returns true. 16612 * 16613 * @return The right padding offset in pixels. 16614 * 16615 * @see #isPaddingOffsetRequired() 16616 * 16617 * @since CURRENT 16618 */ 16619 protected int getRightPaddingOffset() { 16620 return 0; 16621 } 16622 16623 /** 16624 * Amount by which to extend the top fading region. Called only when 16625 * {@link #isPaddingOffsetRequired()} returns true. 16626 * 16627 * @return The top padding offset in pixels. 16628 * 16629 * @see #isPaddingOffsetRequired() 16630 * 16631 * @since CURRENT 16632 */ 16633 protected int getTopPaddingOffset() { 16634 return 0; 16635 } 16636 16637 /** 16638 * Amount by which to extend the bottom fading region. Called only when 16639 * {@link #isPaddingOffsetRequired()} returns true. 16640 * 16641 * @return The bottom padding offset in pixels. 16642 * 16643 * @see #isPaddingOffsetRequired() 16644 * 16645 * @since CURRENT 16646 */ 16647 protected int getBottomPaddingOffset() { 16648 return 0; 16649 } 16650 16651 /** 16652 * @hide 16653 * @param offsetRequired 16654 */ 16655 protected int getFadeTop(boolean offsetRequired) { 16656 int top = mPaddingTop; 16657 if (offsetRequired) top += getTopPaddingOffset(); 16658 return top; 16659 } 16660 16661 /** 16662 * @hide 16663 * @param offsetRequired 16664 */ 16665 protected int getFadeHeight(boolean offsetRequired) { 16666 int padding = mPaddingTop; 16667 if (offsetRequired) padding += getTopPaddingOffset(); 16668 return mBottom - mTop - mPaddingBottom - padding; 16669 } 16670 16671 /** 16672 * <p>Indicates whether this view is attached to a hardware accelerated 16673 * window or not.</p> 16674 * 16675 * <p>Even if this method returns true, it does not mean that every call 16676 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16677 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16678 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16679 * window is hardware accelerated, 16680 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16681 * return false, and this method will return true.</p> 16682 * 16683 * @return True if the view is attached to a window and the window is 16684 * hardware accelerated; false in any other case. 16685 */ 16686 @ViewDebug.ExportedProperty(category = "drawing") 16687 public boolean isHardwareAccelerated() { 16688 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16689 } 16690 16691 /** 16692 * Sets a rectangular area on this view to which the view will be clipped 16693 * when it is drawn. Setting the value to null will remove the clip bounds 16694 * and the view will draw normally, using its full bounds. 16695 * 16696 * @param clipBounds The rectangular area, in the local coordinates of 16697 * this view, to which future drawing operations will be clipped. 16698 */ 16699 public void setClipBounds(Rect clipBounds) { 16700 if (clipBounds == mClipBounds 16701 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16702 return; 16703 } 16704 if (clipBounds != null) { 16705 if (mClipBounds == null) { 16706 mClipBounds = new Rect(clipBounds); 16707 } else { 16708 mClipBounds.set(clipBounds); 16709 } 16710 } else { 16711 mClipBounds = null; 16712 } 16713 mRenderNode.setClipBounds(mClipBounds); 16714 invalidateViewProperty(false, false); 16715 } 16716 16717 /** 16718 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16719 * 16720 * @return A copy of the current clip bounds if clip bounds are set, 16721 * otherwise null. 16722 */ 16723 public Rect getClipBounds() { 16724 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16725 } 16726 16727 16728 /** 16729 * Populates an output rectangle with the clip bounds of the view, 16730 * returning {@code true} if successful or {@code false} if the view's 16731 * clip bounds are {@code null}. 16732 * 16733 * @param outRect rectangle in which to place the clip bounds of the view 16734 * @return {@code true} if successful or {@code false} if the view's 16735 * clip bounds are {@code null} 16736 */ 16737 public boolean getClipBounds(Rect outRect) { 16738 if (mClipBounds != null) { 16739 outRect.set(mClipBounds); 16740 return true; 16741 } 16742 return false; 16743 } 16744 16745 /** 16746 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16747 * case of an active Animation being run on the view. 16748 */ 16749 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16750 Animation a, boolean scalingRequired) { 16751 Transformation invalidationTransform; 16752 final int flags = parent.mGroupFlags; 16753 final boolean initialized = a.isInitialized(); 16754 if (!initialized) { 16755 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16756 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16757 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16758 onAnimationStart(); 16759 } 16760 16761 final Transformation t = parent.getChildTransformation(); 16762 boolean more = a.getTransformation(drawingTime, t, 1f); 16763 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16764 if (parent.mInvalidationTransformation == null) { 16765 parent.mInvalidationTransformation = new Transformation(); 16766 } 16767 invalidationTransform = parent.mInvalidationTransformation; 16768 a.getTransformation(drawingTime, invalidationTransform, 1f); 16769 } else { 16770 invalidationTransform = t; 16771 } 16772 16773 if (more) { 16774 if (!a.willChangeBounds()) { 16775 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16776 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16777 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16778 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16779 // The child need to draw an animation, potentially offscreen, so 16780 // make sure we do not cancel invalidate requests 16781 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16782 parent.invalidate(mLeft, mTop, mRight, mBottom); 16783 } 16784 } else { 16785 if (parent.mInvalidateRegion == null) { 16786 parent.mInvalidateRegion = new RectF(); 16787 } 16788 final RectF region = parent.mInvalidateRegion; 16789 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16790 invalidationTransform); 16791 16792 // The child need to draw an animation, potentially offscreen, so 16793 // make sure we do not cancel invalidate requests 16794 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16795 16796 final int left = mLeft + (int) region.left; 16797 final int top = mTop + (int) region.top; 16798 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16799 top + (int) (region.height() + .5f)); 16800 } 16801 } 16802 return more; 16803 } 16804 16805 /** 16806 * This method is called by getDisplayList() when a display list is recorded for a View. 16807 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16808 */ 16809 void setDisplayListProperties(RenderNode renderNode) { 16810 if (renderNode != null) { 16811 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16812 renderNode.setClipToBounds(mParent instanceof ViewGroup 16813 && ((ViewGroup) mParent).getClipChildren()); 16814 16815 float alpha = 1; 16816 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16817 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16818 ViewGroup parentVG = (ViewGroup) mParent; 16819 final Transformation t = parentVG.getChildTransformation(); 16820 if (parentVG.getChildStaticTransformation(this, t)) { 16821 final int transformType = t.getTransformationType(); 16822 if (transformType != Transformation.TYPE_IDENTITY) { 16823 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16824 alpha = t.getAlpha(); 16825 } 16826 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16827 renderNode.setStaticMatrix(t.getMatrix()); 16828 } 16829 } 16830 } 16831 } 16832 if (mTransformationInfo != null) { 16833 alpha *= getFinalAlpha(); 16834 if (alpha < 1) { 16835 final int multipliedAlpha = (int) (255 * alpha); 16836 if (onSetAlpha(multipliedAlpha)) { 16837 alpha = 1; 16838 } 16839 } 16840 renderNode.setAlpha(alpha); 16841 } else if (alpha < 1) { 16842 renderNode.setAlpha(alpha); 16843 } 16844 } 16845 } 16846 16847 /** 16848 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16849 * 16850 * This is where the View specializes rendering behavior based on layer type, 16851 * and hardware acceleration. 16852 */ 16853 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16854 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16855 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16856 * 16857 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16858 * HW accelerated, it can't handle drawing RenderNodes. 16859 */ 16860 boolean drawingWithRenderNode = mAttachInfo != null 16861 && mAttachInfo.mHardwareAccelerated 16862 && hardwareAcceleratedCanvas; 16863 16864 boolean more = false; 16865 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16866 final int parentFlags = parent.mGroupFlags; 16867 16868 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16869 parent.getChildTransformation().clear(); 16870 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16871 } 16872 16873 Transformation transformToApply = null; 16874 boolean concatMatrix = false; 16875 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16876 final Animation a = getAnimation(); 16877 if (a != null) { 16878 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16879 concatMatrix = a.willChangeTransformationMatrix(); 16880 if (concatMatrix) { 16881 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16882 } 16883 transformToApply = parent.getChildTransformation(); 16884 } else { 16885 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16886 // No longer animating: clear out old animation matrix 16887 mRenderNode.setAnimationMatrix(null); 16888 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16889 } 16890 if (!drawingWithRenderNode 16891 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16892 final Transformation t = parent.getChildTransformation(); 16893 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16894 if (hasTransform) { 16895 final int transformType = t.getTransformationType(); 16896 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16897 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16898 } 16899 } 16900 } 16901 16902 concatMatrix |= !childHasIdentityMatrix; 16903 16904 // Sets the flag as early as possible to allow draw() implementations 16905 // to call invalidate() successfully when doing animations 16906 mPrivateFlags |= PFLAG_DRAWN; 16907 16908 if (!concatMatrix && 16909 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16910 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16911 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16912 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16913 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16914 return more; 16915 } 16916 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16917 16918 if (hardwareAcceleratedCanvas) { 16919 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16920 // retain the flag's value temporarily in the mRecreateDisplayList flag 16921 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16922 mPrivateFlags &= ~PFLAG_INVALIDATED; 16923 } 16924 16925 RenderNode renderNode = null; 16926 Bitmap cache = null; 16927 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16928 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16929 if (layerType != LAYER_TYPE_NONE) { 16930 // If not drawing with RenderNode, treat HW layers as SW 16931 layerType = LAYER_TYPE_SOFTWARE; 16932 buildDrawingCache(true); 16933 } 16934 cache = getDrawingCache(true); 16935 } 16936 16937 if (drawingWithRenderNode) { 16938 // Delay getting the display list until animation-driven alpha values are 16939 // set up and possibly passed on to the view 16940 renderNode = updateDisplayListIfDirty(); 16941 if (!renderNode.isValid()) { 16942 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16943 // to getDisplayList(), the display list will be marked invalid and we should not 16944 // try to use it again. 16945 renderNode = null; 16946 drawingWithRenderNode = false; 16947 } 16948 } 16949 16950 int sx = 0; 16951 int sy = 0; 16952 if (!drawingWithRenderNode) { 16953 computeScroll(); 16954 sx = mScrollX; 16955 sy = mScrollY; 16956 } 16957 16958 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16959 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16960 16961 int restoreTo = -1; 16962 if (!drawingWithRenderNode || transformToApply != null) { 16963 restoreTo = canvas.save(); 16964 } 16965 if (offsetForScroll) { 16966 canvas.translate(mLeft - sx, mTop - sy); 16967 } else { 16968 if (!drawingWithRenderNode) { 16969 canvas.translate(mLeft, mTop); 16970 } 16971 if (scalingRequired) { 16972 if (drawingWithRenderNode) { 16973 // TODO: Might not need this if we put everything inside the DL 16974 restoreTo = canvas.save(); 16975 } 16976 // mAttachInfo cannot be null, otherwise scalingRequired == false 16977 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16978 canvas.scale(scale, scale); 16979 } 16980 } 16981 16982 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16983 if (transformToApply != null 16984 || alpha < 1 16985 || !hasIdentityMatrix() 16986 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16987 if (transformToApply != null || !childHasIdentityMatrix) { 16988 int transX = 0; 16989 int transY = 0; 16990 16991 if (offsetForScroll) { 16992 transX = -sx; 16993 transY = -sy; 16994 } 16995 16996 if (transformToApply != null) { 16997 if (concatMatrix) { 16998 if (drawingWithRenderNode) { 16999 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 17000 } else { 17001 // Undo the scroll translation, apply the transformation matrix, 17002 // then redo the scroll translate to get the correct result. 17003 canvas.translate(-transX, -transY); 17004 canvas.concat(transformToApply.getMatrix()); 17005 canvas.translate(transX, transY); 17006 } 17007 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17008 } 17009 17010 float transformAlpha = transformToApply.getAlpha(); 17011 if (transformAlpha < 1) { 17012 alpha *= transformAlpha; 17013 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17014 } 17015 } 17016 17017 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 17018 canvas.translate(-transX, -transY); 17019 canvas.concat(getMatrix()); 17020 canvas.translate(transX, transY); 17021 } 17022 } 17023 17024 // Deal with alpha if it is or used to be <1 17025 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 17026 if (alpha < 1) { 17027 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17028 } else { 17029 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17030 } 17031 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17032 if (!drawingWithDrawingCache) { 17033 final int multipliedAlpha = (int) (255 * alpha); 17034 if (!onSetAlpha(multipliedAlpha)) { 17035 if (drawingWithRenderNode) { 17036 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 17037 } else if (layerType == LAYER_TYPE_NONE) { 17038 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 17039 multipliedAlpha); 17040 } 17041 } else { 17042 // Alpha is handled by the child directly, clobber the layer's alpha 17043 mPrivateFlags |= PFLAG_ALPHA_SET; 17044 } 17045 } 17046 } 17047 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17048 onSetAlpha(255); 17049 mPrivateFlags &= ~PFLAG_ALPHA_SET; 17050 } 17051 17052 if (!drawingWithRenderNode) { 17053 // apply clips directly, since RenderNode won't do it for this draw 17054 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 17055 if (offsetForScroll) { 17056 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 17057 } else { 17058 if (!scalingRequired || cache == null) { 17059 canvas.clipRect(0, 0, getWidth(), getHeight()); 17060 } else { 17061 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 17062 } 17063 } 17064 } 17065 17066 if (mClipBounds != null) { 17067 // clip bounds ignore scroll 17068 canvas.clipRect(mClipBounds); 17069 } 17070 } 17071 17072 if (!drawingWithDrawingCache) { 17073 if (drawingWithRenderNode) { 17074 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17075 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17076 } else { 17077 // Fast path for layouts with no backgrounds 17078 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17079 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17080 dispatchDraw(canvas); 17081 } else { 17082 draw(canvas); 17083 } 17084 } 17085 } else if (cache != null) { 17086 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17087 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 17088 // no layer paint, use temporary paint to draw bitmap 17089 Paint cachePaint = parent.mCachePaint; 17090 if (cachePaint == null) { 17091 cachePaint = new Paint(); 17092 cachePaint.setDither(false); 17093 parent.mCachePaint = cachePaint; 17094 } 17095 cachePaint.setAlpha((int) (alpha * 255)); 17096 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 17097 } else { 17098 // use layer paint to draw the bitmap, merging the two alphas, but also restore 17099 int layerPaintAlpha = mLayerPaint.getAlpha(); 17100 if (alpha < 1) { 17101 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 17102 } 17103 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17104 if (alpha < 1) { 17105 mLayerPaint.setAlpha(layerPaintAlpha); 17106 } 17107 } 17108 } 17109 17110 if (restoreTo >= 0) { 17111 canvas.restoreToCount(restoreTo); 17112 } 17113 17114 if (a != null && !more) { 17115 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17116 onSetAlpha(255); 17117 } 17118 parent.finishAnimatingView(this, a); 17119 } 17120 17121 if (more && hardwareAcceleratedCanvas) { 17122 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17123 // alpha animations should cause the child to recreate its display list 17124 invalidate(true); 17125 } 17126 } 17127 17128 mRecreateDisplayList = false; 17129 17130 return more; 17131 } 17132 17133 static Paint getDebugPaint() { 17134 if (sDebugPaint == null) { 17135 sDebugPaint = new Paint(); 17136 sDebugPaint.setAntiAlias(false); 17137 } 17138 return sDebugPaint; 17139 } 17140 17141 final int dipsToPixels(int dips) { 17142 float scale = getContext().getResources().getDisplayMetrics().density; 17143 return (int) (dips * scale + 0.5f); 17144 } 17145 17146 final private void debugDrawFocus(Canvas canvas) { 17147 if (isFocused()) { 17148 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 17149 final int l = mScrollX; 17150 final int r = l + mRight - mLeft; 17151 final int t = mScrollY; 17152 final int b = t + mBottom - mTop; 17153 17154 final Paint paint = getDebugPaint(); 17155 paint.setColor(DEBUG_CORNERS_COLOR); 17156 17157 // Draw squares in corners. 17158 paint.setStyle(Paint.Style.FILL); 17159 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 17160 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 17161 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 17162 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 17163 17164 // Draw big X across the view. 17165 paint.setStyle(Paint.Style.STROKE); 17166 canvas.drawLine(l, t, r, b, paint); 17167 canvas.drawLine(l, b, r, t, paint); 17168 } 17169 } 17170 17171 /** 17172 * Manually render this view (and all of its children) to the given Canvas. 17173 * The view must have already done a full layout before this function is 17174 * called. When implementing a view, implement 17175 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17176 * If you do need to override this method, call the superclass version. 17177 * 17178 * @param canvas The Canvas to which the View is rendered. 17179 */ 17180 @CallSuper 17181 public void draw(Canvas canvas) { 17182 final int privateFlags = mPrivateFlags; 17183 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17184 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17185 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17186 17187 /* 17188 * Draw traversal performs several drawing steps which must be executed 17189 * in the appropriate order: 17190 * 17191 * 1. Draw the background 17192 * 2. If necessary, save the canvas' layers to prepare for fading 17193 * 3. Draw view's content 17194 * 4. Draw children 17195 * 5. If necessary, draw the fading edges and restore layers 17196 * 6. Draw decorations (scrollbars for instance) 17197 */ 17198 17199 // Step 1, draw the background, if needed 17200 int saveCount; 17201 17202 if (!dirtyOpaque) { 17203 drawBackground(canvas); 17204 } 17205 17206 // skip step 2 & 5 if possible (common case) 17207 final int viewFlags = mViewFlags; 17208 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17209 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17210 if (!verticalEdges && !horizontalEdges) { 17211 // Step 3, draw the content 17212 if (!dirtyOpaque) onDraw(canvas); 17213 17214 // Step 4, draw the children 17215 dispatchDraw(canvas); 17216 17217 // Overlay is part of the content and draws beneath Foreground 17218 if (mOverlay != null && !mOverlay.isEmpty()) { 17219 mOverlay.getOverlayView().dispatchDraw(canvas); 17220 } 17221 17222 // Step 6, draw decorations (foreground, scrollbars) 17223 onDrawForeground(canvas); 17224 17225 if (debugDraw()) { 17226 debugDrawFocus(canvas); 17227 } 17228 17229 // we're done... 17230 return; 17231 } 17232 17233 /* 17234 * Here we do the full fledged routine... 17235 * (this is an uncommon case where speed matters less, 17236 * this is why we repeat some of the tests that have been 17237 * done above) 17238 */ 17239 17240 boolean drawTop = false; 17241 boolean drawBottom = false; 17242 boolean drawLeft = false; 17243 boolean drawRight = false; 17244 17245 float topFadeStrength = 0.0f; 17246 float bottomFadeStrength = 0.0f; 17247 float leftFadeStrength = 0.0f; 17248 float rightFadeStrength = 0.0f; 17249 17250 // Step 2, save the canvas' layers 17251 int paddingLeft = mPaddingLeft; 17252 17253 final boolean offsetRequired = isPaddingOffsetRequired(); 17254 if (offsetRequired) { 17255 paddingLeft += getLeftPaddingOffset(); 17256 } 17257 17258 int left = mScrollX + paddingLeft; 17259 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17260 int top = mScrollY + getFadeTop(offsetRequired); 17261 int bottom = top + getFadeHeight(offsetRequired); 17262 17263 if (offsetRequired) { 17264 right += getRightPaddingOffset(); 17265 bottom += getBottomPaddingOffset(); 17266 } 17267 17268 final ScrollabilityCache scrollabilityCache = mScrollCache; 17269 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17270 int length = (int) fadeHeight; 17271 17272 // clip the fade length if top and bottom fades overlap 17273 // overlapping fades produce odd-looking artifacts 17274 if (verticalEdges && (top + length > bottom - length)) { 17275 length = (bottom - top) / 2; 17276 } 17277 17278 // also clip horizontal fades if necessary 17279 if (horizontalEdges && (left + length > right - length)) { 17280 length = (right - left) / 2; 17281 } 17282 17283 if (verticalEdges) { 17284 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17285 drawTop = topFadeStrength * fadeHeight > 1.0f; 17286 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17287 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17288 } 17289 17290 if (horizontalEdges) { 17291 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17292 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17293 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17294 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17295 } 17296 17297 saveCount = canvas.getSaveCount(); 17298 17299 int solidColor = getSolidColor(); 17300 if (solidColor == 0) { 17301 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17302 17303 if (drawTop) { 17304 canvas.saveLayer(left, top, right, top + length, null, flags); 17305 } 17306 17307 if (drawBottom) { 17308 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17309 } 17310 17311 if (drawLeft) { 17312 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17313 } 17314 17315 if (drawRight) { 17316 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17317 } 17318 } else { 17319 scrollabilityCache.setFadeColor(solidColor); 17320 } 17321 17322 // Step 3, draw the content 17323 if (!dirtyOpaque) onDraw(canvas); 17324 17325 // Step 4, draw the children 17326 dispatchDraw(canvas); 17327 17328 // Step 5, draw the fade effect and restore layers 17329 final Paint p = scrollabilityCache.paint; 17330 final Matrix matrix = scrollabilityCache.matrix; 17331 final Shader fade = scrollabilityCache.shader; 17332 17333 if (drawTop) { 17334 matrix.setScale(1, fadeHeight * topFadeStrength); 17335 matrix.postTranslate(left, top); 17336 fade.setLocalMatrix(matrix); 17337 p.setShader(fade); 17338 canvas.drawRect(left, top, right, top + length, p); 17339 } 17340 17341 if (drawBottom) { 17342 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17343 matrix.postRotate(180); 17344 matrix.postTranslate(left, bottom); 17345 fade.setLocalMatrix(matrix); 17346 p.setShader(fade); 17347 canvas.drawRect(left, bottom - length, right, bottom, p); 17348 } 17349 17350 if (drawLeft) { 17351 matrix.setScale(1, fadeHeight * leftFadeStrength); 17352 matrix.postRotate(-90); 17353 matrix.postTranslate(left, top); 17354 fade.setLocalMatrix(matrix); 17355 p.setShader(fade); 17356 canvas.drawRect(left, top, left + length, bottom, p); 17357 } 17358 17359 if (drawRight) { 17360 matrix.setScale(1, fadeHeight * rightFadeStrength); 17361 matrix.postRotate(90); 17362 matrix.postTranslate(right, top); 17363 fade.setLocalMatrix(matrix); 17364 p.setShader(fade); 17365 canvas.drawRect(right - length, top, right, bottom, p); 17366 } 17367 17368 canvas.restoreToCount(saveCount); 17369 17370 // Overlay is part of the content and draws beneath Foreground 17371 if (mOverlay != null && !mOverlay.isEmpty()) { 17372 mOverlay.getOverlayView().dispatchDraw(canvas); 17373 } 17374 17375 // Step 6, draw decorations (foreground, scrollbars) 17376 onDrawForeground(canvas); 17377 17378 if (debugDraw()) { 17379 debugDrawFocus(canvas); 17380 } 17381 } 17382 17383 /** 17384 * Draws the background onto the specified canvas. 17385 * 17386 * @param canvas Canvas on which to draw the background 17387 */ 17388 private void drawBackground(Canvas canvas) { 17389 final Drawable background = mBackground; 17390 if (background == null) { 17391 return; 17392 } 17393 17394 setBackgroundBounds(); 17395 17396 // Attempt to use a display list if requested. 17397 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17398 && mAttachInfo.mThreadedRenderer != null) { 17399 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17400 17401 final RenderNode renderNode = mBackgroundRenderNode; 17402 if (renderNode != null && renderNode.isValid()) { 17403 setBackgroundRenderNodeProperties(renderNode); 17404 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17405 return; 17406 } 17407 } 17408 17409 final int scrollX = mScrollX; 17410 final int scrollY = mScrollY; 17411 if ((scrollX | scrollY) == 0) { 17412 background.draw(canvas); 17413 } else { 17414 canvas.translate(scrollX, scrollY); 17415 background.draw(canvas); 17416 canvas.translate(-scrollX, -scrollY); 17417 } 17418 } 17419 17420 /** 17421 * Sets the correct background bounds and rebuilds the outline, if needed. 17422 * <p/> 17423 * This is called by LayoutLib. 17424 */ 17425 void setBackgroundBounds() { 17426 if (mBackgroundSizeChanged && mBackground != null) { 17427 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17428 mBackgroundSizeChanged = false; 17429 rebuildOutline(); 17430 } 17431 } 17432 17433 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17434 renderNode.setTranslationX(mScrollX); 17435 renderNode.setTranslationY(mScrollY); 17436 } 17437 17438 /** 17439 * Creates a new display list or updates the existing display list for the 17440 * specified Drawable. 17441 * 17442 * @param drawable Drawable for which to create a display list 17443 * @param renderNode Existing RenderNode, or {@code null} 17444 * @return A valid display list for the specified drawable 17445 */ 17446 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17447 if (renderNode == null) { 17448 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17449 } 17450 17451 final Rect bounds = drawable.getBounds(); 17452 final int width = bounds.width(); 17453 final int height = bounds.height(); 17454 final DisplayListCanvas canvas = renderNode.start(width, height); 17455 17456 // Reverse left/top translation done by drawable canvas, which will 17457 // instead be applied by rendernode's LTRB bounds below. This way, the 17458 // drawable's bounds match with its rendernode bounds and its content 17459 // will lie within those bounds in the rendernode tree. 17460 canvas.translate(-bounds.left, -bounds.top); 17461 17462 try { 17463 drawable.draw(canvas); 17464 } finally { 17465 renderNode.end(canvas); 17466 } 17467 17468 // Set up drawable properties that are view-independent. 17469 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17470 renderNode.setProjectBackwards(drawable.isProjected()); 17471 renderNode.setProjectionReceiver(true); 17472 renderNode.setClipToBounds(false); 17473 return renderNode; 17474 } 17475 17476 /** 17477 * Returns the overlay for this view, creating it if it does not yet exist. 17478 * Adding drawables to the overlay will cause them to be displayed whenever 17479 * the view itself is redrawn. Objects in the overlay should be actively 17480 * managed: remove them when they should not be displayed anymore. The 17481 * overlay will always have the same size as its host view. 17482 * 17483 * <p>Note: Overlays do not currently work correctly with {@link 17484 * SurfaceView} or {@link TextureView}; contents in overlays for these 17485 * types of views may not display correctly.</p> 17486 * 17487 * @return The ViewOverlay object for this view. 17488 * @see ViewOverlay 17489 */ 17490 public ViewOverlay getOverlay() { 17491 if (mOverlay == null) { 17492 mOverlay = new ViewOverlay(mContext, this); 17493 } 17494 return mOverlay; 17495 } 17496 17497 /** 17498 * Override this if your view is known to always be drawn on top of a solid color background, 17499 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17500 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17501 * should be set to 0xFF. 17502 * 17503 * @see #setVerticalFadingEdgeEnabled(boolean) 17504 * @see #setHorizontalFadingEdgeEnabled(boolean) 17505 * 17506 * @return The known solid color background for this view, or 0 if the color may vary 17507 */ 17508 @ViewDebug.ExportedProperty(category = "drawing") 17509 @ColorInt 17510 public int getSolidColor() { 17511 return 0; 17512 } 17513 17514 /** 17515 * Build a human readable string representation of the specified view flags. 17516 * 17517 * @param flags the view flags to convert to a string 17518 * @return a String representing the supplied flags 17519 */ 17520 private static String printFlags(int flags) { 17521 String output = ""; 17522 int numFlags = 0; 17523 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17524 output += "TAKES_FOCUS"; 17525 numFlags++; 17526 } 17527 17528 switch (flags & VISIBILITY_MASK) { 17529 case INVISIBLE: 17530 if (numFlags > 0) { 17531 output += " "; 17532 } 17533 output += "INVISIBLE"; 17534 // USELESS HERE numFlags++; 17535 break; 17536 case GONE: 17537 if (numFlags > 0) { 17538 output += " "; 17539 } 17540 output += "GONE"; 17541 // USELESS HERE numFlags++; 17542 break; 17543 default: 17544 break; 17545 } 17546 return output; 17547 } 17548 17549 /** 17550 * Build a human readable string representation of the specified private 17551 * view flags. 17552 * 17553 * @param privateFlags the private view flags to convert to a string 17554 * @return a String representing the supplied flags 17555 */ 17556 private static String printPrivateFlags(int privateFlags) { 17557 String output = ""; 17558 int numFlags = 0; 17559 17560 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17561 output += "WANTS_FOCUS"; 17562 numFlags++; 17563 } 17564 17565 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17566 if (numFlags > 0) { 17567 output += " "; 17568 } 17569 output += "FOCUSED"; 17570 numFlags++; 17571 } 17572 17573 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17574 if (numFlags > 0) { 17575 output += " "; 17576 } 17577 output += "SELECTED"; 17578 numFlags++; 17579 } 17580 17581 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17582 if (numFlags > 0) { 17583 output += " "; 17584 } 17585 output += "IS_ROOT_NAMESPACE"; 17586 numFlags++; 17587 } 17588 17589 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17590 if (numFlags > 0) { 17591 output += " "; 17592 } 17593 output += "HAS_BOUNDS"; 17594 numFlags++; 17595 } 17596 17597 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17598 if (numFlags > 0) { 17599 output += " "; 17600 } 17601 output += "DRAWN"; 17602 // USELESS HERE numFlags++; 17603 } 17604 return output; 17605 } 17606 17607 /** 17608 * <p>Indicates whether or not this view's layout will be requested during 17609 * the next hierarchy layout pass.</p> 17610 * 17611 * @return true if the layout will be forced during next layout pass 17612 */ 17613 public boolean isLayoutRequested() { 17614 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17615 } 17616 17617 /** 17618 * Return true if o is a ViewGroup that is laying out using optical bounds. 17619 * @hide 17620 */ 17621 public static boolean isLayoutModeOptical(Object o) { 17622 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17623 } 17624 17625 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17626 Insets parentInsets = mParent instanceof View ? 17627 ((View) mParent).getOpticalInsets() : Insets.NONE; 17628 Insets childInsets = getOpticalInsets(); 17629 return setFrame( 17630 left + parentInsets.left - childInsets.left, 17631 top + parentInsets.top - childInsets.top, 17632 right + parentInsets.left + childInsets.right, 17633 bottom + parentInsets.top + childInsets.bottom); 17634 } 17635 17636 /** 17637 * Assign a size and position to a view and all of its 17638 * descendants 17639 * 17640 * <p>This is the second phase of the layout mechanism. 17641 * (The first is measuring). In this phase, each parent calls 17642 * layout on all of its children to position them. 17643 * This is typically done using the child measurements 17644 * that were stored in the measure pass().</p> 17645 * 17646 * <p>Derived classes should not override this method. 17647 * Derived classes with children should override 17648 * onLayout. In that method, they should 17649 * call layout on each of their children.</p> 17650 * 17651 * @param l Left position, relative to parent 17652 * @param t Top position, relative to parent 17653 * @param r Right position, relative to parent 17654 * @param b Bottom position, relative to parent 17655 */ 17656 @SuppressWarnings({"unchecked"}) 17657 public void layout(int l, int t, int r, int b) { 17658 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17659 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17660 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17661 } 17662 17663 int oldL = mLeft; 17664 int oldT = mTop; 17665 int oldB = mBottom; 17666 int oldR = mRight; 17667 17668 boolean changed = isLayoutModeOptical(mParent) ? 17669 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17670 17671 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17672 onLayout(changed, l, t, r, b); 17673 17674 if (shouldDrawRoundScrollbar()) { 17675 if(mRoundScrollbarRenderer == null) { 17676 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 17677 } 17678 } else { 17679 mRoundScrollbarRenderer = null; 17680 } 17681 17682 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17683 17684 ListenerInfo li = mListenerInfo; 17685 if (li != null && li.mOnLayoutChangeListeners != null) { 17686 ArrayList<OnLayoutChangeListener> listenersCopy = 17687 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17688 int numListeners = listenersCopy.size(); 17689 for (int i = 0; i < numListeners; ++i) { 17690 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17691 } 17692 } 17693 } 17694 17695 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17696 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17697 } 17698 17699 /** 17700 * Called from layout when this view should 17701 * assign a size and position to each of its children. 17702 * 17703 * Derived classes with children should override 17704 * this method and call layout on each of 17705 * their children. 17706 * @param changed This is a new size or position for this view 17707 * @param left Left position, relative to parent 17708 * @param top Top position, relative to parent 17709 * @param right Right position, relative to parent 17710 * @param bottom Bottom position, relative to parent 17711 */ 17712 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17713 } 17714 17715 /** 17716 * Assign a size and position to this view. 17717 * 17718 * This is called from layout. 17719 * 17720 * @param left Left position, relative to parent 17721 * @param top Top position, relative to parent 17722 * @param right Right position, relative to parent 17723 * @param bottom Bottom position, relative to parent 17724 * @return true if the new size and position are different than the 17725 * previous ones 17726 * {@hide} 17727 */ 17728 protected boolean setFrame(int left, int top, int right, int bottom) { 17729 boolean changed = false; 17730 17731 if (DBG) { 17732 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17733 + right + "," + bottom + ")"); 17734 } 17735 17736 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17737 changed = true; 17738 17739 // Remember our drawn bit 17740 int drawn = mPrivateFlags & PFLAG_DRAWN; 17741 17742 int oldWidth = mRight - mLeft; 17743 int oldHeight = mBottom - mTop; 17744 int newWidth = right - left; 17745 int newHeight = bottom - top; 17746 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17747 17748 // Invalidate our old position 17749 invalidate(sizeChanged); 17750 17751 mLeft = left; 17752 mTop = top; 17753 mRight = right; 17754 mBottom = bottom; 17755 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17756 17757 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17758 17759 17760 if (sizeChanged) { 17761 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17762 } 17763 17764 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17765 // If we are visible, force the DRAWN bit to on so that 17766 // this invalidate will go through (at least to our parent). 17767 // This is because someone may have invalidated this view 17768 // before this call to setFrame came in, thereby clearing 17769 // the DRAWN bit. 17770 mPrivateFlags |= PFLAG_DRAWN; 17771 invalidate(sizeChanged); 17772 // parent display list may need to be recreated based on a change in the bounds 17773 // of any child 17774 invalidateParentCaches(); 17775 } 17776 17777 // Reset drawn bit to original value (invalidate turns it off) 17778 mPrivateFlags |= drawn; 17779 17780 mBackgroundSizeChanged = true; 17781 if (mForegroundInfo != null) { 17782 mForegroundInfo.mBoundsChanged = true; 17783 } 17784 17785 notifySubtreeAccessibilityStateChangedIfNeeded(); 17786 } 17787 return changed; 17788 } 17789 17790 /** 17791 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17792 * @hide 17793 */ 17794 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17795 setFrame(left, top, right, bottom); 17796 } 17797 17798 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17799 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17800 if (mOverlay != null) { 17801 mOverlay.getOverlayView().setRight(newWidth); 17802 mOverlay.getOverlayView().setBottom(newHeight); 17803 } 17804 rebuildOutline(); 17805 } 17806 17807 /** 17808 * Finalize inflating a view from XML. This is called as the last phase 17809 * of inflation, after all child views have been added. 17810 * 17811 * <p>Even if the subclass overrides onFinishInflate, they should always be 17812 * sure to call the super method, so that we get called. 17813 */ 17814 @CallSuper 17815 protected void onFinishInflate() { 17816 } 17817 17818 /** 17819 * Returns the resources associated with this view. 17820 * 17821 * @return Resources object. 17822 */ 17823 public Resources getResources() { 17824 return mResources; 17825 } 17826 17827 /** 17828 * Invalidates the specified Drawable. 17829 * 17830 * @param drawable the drawable to invalidate 17831 */ 17832 @Override 17833 public void invalidateDrawable(@NonNull Drawable drawable) { 17834 if (verifyDrawable(drawable)) { 17835 final Rect dirty = drawable.getDirtyBounds(); 17836 final int scrollX = mScrollX; 17837 final int scrollY = mScrollY; 17838 17839 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17840 dirty.right + scrollX, dirty.bottom + scrollY); 17841 rebuildOutline(); 17842 } 17843 } 17844 17845 /** 17846 * Schedules an action on a drawable to occur at a specified time. 17847 * 17848 * @param who the recipient of the action 17849 * @param what the action to run on the drawable 17850 * @param when the time at which the action must occur. Uses the 17851 * {@link SystemClock#uptimeMillis} timebase. 17852 */ 17853 @Override 17854 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17855 if (verifyDrawable(who) && what != null) { 17856 final long delay = when - SystemClock.uptimeMillis(); 17857 if (mAttachInfo != null) { 17858 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17859 Choreographer.CALLBACK_ANIMATION, what, who, 17860 Choreographer.subtractFrameDelay(delay)); 17861 } else { 17862 // Postpone the runnable until we know 17863 // on which thread it needs to run. 17864 getRunQueue().postDelayed(what, delay); 17865 } 17866 } 17867 } 17868 17869 /** 17870 * Cancels a scheduled action on a drawable. 17871 * 17872 * @param who the recipient of the action 17873 * @param what the action to cancel 17874 */ 17875 @Override 17876 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17877 if (verifyDrawable(who) && what != null) { 17878 if (mAttachInfo != null) { 17879 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17880 Choreographer.CALLBACK_ANIMATION, what, who); 17881 } 17882 getRunQueue().removeCallbacks(what); 17883 } 17884 } 17885 17886 /** 17887 * Unschedule any events associated with the given Drawable. This can be 17888 * used when selecting a new Drawable into a view, so that the previous 17889 * one is completely unscheduled. 17890 * 17891 * @param who The Drawable to unschedule. 17892 * 17893 * @see #drawableStateChanged 17894 */ 17895 public void unscheduleDrawable(Drawable who) { 17896 if (mAttachInfo != null && who != null) { 17897 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17898 Choreographer.CALLBACK_ANIMATION, null, who); 17899 } 17900 } 17901 17902 /** 17903 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17904 * that the View directionality can and will be resolved before its Drawables. 17905 * 17906 * Will call {@link View#onResolveDrawables} when resolution is done. 17907 * 17908 * @hide 17909 */ 17910 protected void resolveDrawables() { 17911 // Drawables resolution may need to happen before resolving the layout direction (which is 17912 // done only during the measure() call). 17913 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17914 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17915 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17916 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17917 // direction to be resolved as its resolved value will be the same as its raw value. 17918 if (!isLayoutDirectionResolved() && 17919 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17920 return; 17921 } 17922 17923 final int layoutDirection = isLayoutDirectionResolved() ? 17924 getLayoutDirection() : getRawLayoutDirection(); 17925 17926 if (mBackground != null) { 17927 mBackground.setLayoutDirection(layoutDirection); 17928 } 17929 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17930 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17931 } 17932 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17933 onResolveDrawables(layoutDirection); 17934 } 17935 17936 boolean areDrawablesResolved() { 17937 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17938 } 17939 17940 /** 17941 * Called when layout direction has been resolved. 17942 * 17943 * The default implementation does nothing. 17944 * 17945 * @param layoutDirection The resolved layout direction. 17946 * 17947 * @see #LAYOUT_DIRECTION_LTR 17948 * @see #LAYOUT_DIRECTION_RTL 17949 * 17950 * @hide 17951 */ 17952 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17953 } 17954 17955 /** 17956 * @hide 17957 */ 17958 protected void resetResolvedDrawables() { 17959 resetResolvedDrawablesInternal(); 17960 } 17961 17962 void resetResolvedDrawablesInternal() { 17963 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17964 } 17965 17966 /** 17967 * If your view subclass is displaying its own Drawable objects, it should 17968 * override this function and return true for any Drawable it is 17969 * displaying. This allows animations for those drawables to be 17970 * scheduled. 17971 * 17972 * <p>Be sure to call through to the super class when overriding this 17973 * function. 17974 * 17975 * @param who The Drawable to verify. Return true if it is one you are 17976 * displaying, else return the result of calling through to the 17977 * super class. 17978 * 17979 * @return boolean If true than the Drawable is being displayed in the 17980 * view; else false and it is not allowed to animate. 17981 * 17982 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17983 * @see #drawableStateChanged() 17984 */ 17985 @CallSuper 17986 protected boolean verifyDrawable(@NonNull Drawable who) { 17987 // Avoid verifying the scroll bar drawable so that we don't end up in 17988 // an invalidation loop. This effectively prevents the scroll bar 17989 // drawable from triggering invalidations and scheduling runnables. 17990 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17991 } 17992 17993 /** 17994 * This function is called whenever the state of the view changes in such 17995 * a way that it impacts the state of drawables being shown. 17996 * <p> 17997 * If the View has a StateListAnimator, it will also be called to run necessary state 17998 * change animations. 17999 * <p> 18000 * Be sure to call through to the superclass when overriding this function. 18001 * 18002 * @see Drawable#setState(int[]) 18003 */ 18004 @CallSuper 18005 protected void drawableStateChanged() { 18006 final int[] state = getDrawableState(); 18007 boolean changed = false; 18008 18009 final Drawable bg = mBackground; 18010 if (bg != null && bg.isStateful()) { 18011 changed |= bg.setState(state); 18012 } 18013 18014 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18015 if (fg != null && fg.isStateful()) { 18016 changed |= fg.setState(state); 18017 } 18018 18019 if (mScrollCache != null) { 18020 final Drawable scrollBar = mScrollCache.scrollBar; 18021 if (scrollBar != null && scrollBar.isStateful()) { 18022 changed |= scrollBar.setState(state) 18023 && mScrollCache.state != ScrollabilityCache.OFF; 18024 } 18025 } 18026 18027 if (mStateListAnimator != null) { 18028 mStateListAnimator.setState(state); 18029 } 18030 18031 if (changed) { 18032 invalidate(); 18033 } 18034 } 18035 18036 /** 18037 * This function is called whenever the view hotspot changes and needs to 18038 * be propagated to drawables or child views managed by the view. 18039 * <p> 18040 * Dispatching to child views is handled by 18041 * {@link #dispatchDrawableHotspotChanged(float, float)}. 18042 * <p> 18043 * Be sure to call through to the superclass when overriding this function. 18044 * 18045 * @param x hotspot x coordinate 18046 * @param y hotspot y coordinate 18047 */ 18048 @CallSuper 18049 public void drawableHotspotChanged(float x, float y) { 18050 if (mBackground != null) { 18051 mBackground.setHotspot(x, y); 18052 } 18053 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18054 mForegroundInfo.mDrawable.setHotspot(x, y); 18055 } 18056 18057 dispatchDrawableHotspotChanged(x, y); 18058 } 18059 18060 /** 18061 * Dispatches drawableHotspotChanged to all of this View's children. 18062 * 18063 * @param x hotspot x coordinate 18064 * @param y hotspot y coordinate 18065 * @see #drawableHotspotChanged(float, float) 18066 */ 18067 public void dispatchDrawableHotspotChanged(float x, float y) { 18068 } 18069 18070 /** 18071 * Call this to force a view to update its drawable state. This will cause 18072 * drawableStateChanged to be called on this view. Views that are interested 18073 * in the new state should call getDrawableState. 18074 * 18075 * @see #drawableStateChanged 18076 * @see #getDrawableState 18077 */ 18078 public void refreshDrawableState() { 18079 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 18080 drawableStateChanged(); 18081 18082 ViewParent parent = mParent; 18083 if (parent != null) { 18084 parent.childDrawableStateChanged(this); 18085 } 18086 } 18087 18088 /** 18089 * Return an array of resource IDs of the drawable states representing the 18090 * current state of the view. 18091 * 18092 * @return The current drawable state 18093 * 18094 * @see Drawable#setState(int[]) 18095 * @see #drawableStateChanged() 18096 * @see #onCreateDrawableState(int) 18097 */ 18098 public final int[] getDrawableState() { 18099 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 18100 return mDrawableState; 18101 } else { 18102 mDrawableState = onCreateDrawableState(0); 18103 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 18104 return mDrawableState; 18105 } 18106 } 18107 18108 /** 18109 * Generate the new {@link android.graphics.drawable.Drawable} state for 18110 * this view. This is called by the view 18111 * system when the cached Drawable state is determined to be invalid. To 18112 * retrieve the current state, you should use {@link #getDrawableState}. 18113 * 18114 * @param extraSpace if non-zero, this is the number of extra entries you 18115 * would like in the returned array in which you can place your own 18116 * states. 18117 * 18118 * @return Returns an array holding the current {@link Drawable} state of 18119 * the view. 18120 * 18121 * @see #mergeDrawableStates(int[], int[]) 18122 */ 18123 protected int[] onCreateDrawableState(int extraSpace) { 18124 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 18125 mParent instanceof View) { 18126 return ((View) mParent).onCreateDrawableState(extraSpace); 18127 } 18128 18129 int[] drawableState; 18130 18131 int privateFlags = mPrivateFlags; 18132 18133 int viewStateIndex = 0; 18134 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 18135 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 18136 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 18137 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 18138 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 18139 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 18140 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 18141 ThreadedRenderer.isAvailable()) { 18142 // This is set if HW acceleration is requested, even if the current 18143 // process doesn't allow it. This is just to allow app preview 18144 // windows to better match their app. 18145 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 18146 } 18147 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 18148 18149 final int privateFlags2 = mPrivateFlags2; 18150 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 18151 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 18152 } 18153 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 18154 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 18155 } 18156 18157 drawableState = StateSet.get(viewStateIndex); 18158 18159 //noinspection ConstantIfStatement 18160 if (false) { 18161 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18162 Log.i("View", toString() 18163 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18164 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18165 + " fo=" + hasFocus() 18166 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18167 + " wf=" + hasWindowFocus() 18168 + ": " + Arrays.toString(drawableState)); 18169 } 18170 18171 if (extraSpace == 0) { 18172 return drawableState; 18173 } 18174 18175 final int[] fullState; 18176 if (drawableState != null) { 18177 fullState = new int[drawableState.length + extraSpace]; 18178 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18179 } else { 18180 fullState = new int[extraSpace]; 18181 } 18182 18183 return fullState; 18184 } 18185 18186 /** 18187 * Merge your own state values in <var>additionalState</var> into the base 18188 * state values <var>baseState</var> that were returned by 18189 * {@link #onCreateDrawableState(int)}. 18190 * 18191 * @param baseState The base state values returned by 18192 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18193 * own additional state values. 18194 * 18195 * @param additionalState The additional state values you would like 18196 * added to <var>baseState</var>; this array is not modified. 18197 * 18198 * @return As a convenience, the <var>baseState</var> array you originally 18199 * passed into the function is returned. 18200 * 18201 * @see #onCreateDrawableState(int) 18202 */ 18203 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18204 final int N = baseState.length; 18205 int i = N - 1; 18206 while (i >= 0 && baseState[i] == 0) { 18207 i--; 18208 } 18209 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18210 return baseState; 18211 } 18212 18213 /** 18214 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18215 * on all Drawable objects associated with this view. 18216 * <p> 18217 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18218 * attached to this view. 18219 */ 18220 @CallSuper 18221 public void jumpDrawablesToCurrentState() { 18222 if (mBackground != null) { 18223 mBackground.jumpToCurrentState(); 18224 } 18225 if (mStateListAnimator != null) { 18226 mStateListAnimator.jumpToCurrentState(); 18227 } 18228 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18229 mForegroundInfo.mDrawable.jumpToCurrentState(); 18230 } 18231 } 18232 18233 /** 18234 * Sets the background color for this view. 18235 * @param color the color of the background 18236 */ 18237 @RemotableViewMethod 18238 public void setBackgroundColor(@ColorInt int color) { 18239 if (mBackground instanceof ColorDrawable) { 18240 ((ColorDrawable) mBackground.mutate()).setColor(color); 18241 computeOpaqueFlags(); 18242 mBackgroundResource = 0; 18243 } else { 18244 setBackground(new ColorDrawable(color)); 18245 } 18246 } 18247 18248 /** 18249 * Set the background to a given resource. The resource should refer to 18250 * a Drawable object or 0 to remove the background. 18251 * @param resid The identifier of the resource. 18252 * 18253 * @attr ref android.R.styleable#View_background 18254 */ 18255 @RemotableViewMethod 18256 public void setBackgroundResource(@DrawableRes int resid) { 18257 if (resid != 0 && resid == mBackgroundResource) { 18258 return; 18259 } 18260 18261 Drawable d = null; 18262 if (resid != 0) { 18263 d = mContext.getDrawable(resid); 18264 } 18265 setBackground(d); 18266 18267 mBackgroundResource = resid; 18268 } 18269 18270 /** 18271 * Set the background to a given Drawable, or remove the background. If the 18272 * background has padding, this View's padding is set to the background's 18273 * padding. However, when a background is removed, this View's padding isn't 18274 * touched. If setting the padding is desired, please use 18275 * {@link #setPadding(int, int, int, int)}. 18276 * 18277 * @param background The Drawable to use as the background, or null to remove the 18278 * background 18279 */ 18280 public void setBackground(Drawable background) { 18281 //noinspection deprecation 18282 setBackgroundDrawable(background); 18283 } 18284 18285 /** 18286 * @deprecated use {@link #setBackground(Drawable)} instead 18287 */ 18288 @Deprecated 18289 public void setBackgroundDrawable(Drawable background) { 18290 computeOpaqueFlags(); 18291 18292 if (background == mBackground) { 18293 return; 18294 } 18295 18296 boolean requestLayout = false; 18297 18298 mBackgroundResource = 0; 18299 18300 /* 18301 * Regardless of whether we're setting a new background or not, we want 18302 * to clear the previous drawable. setVisible first while we still have the callback set. 18303 */ 18304 if (mBackground != null) { 18305 if (isAttachedToWindow()) { 18306 mBackground.setVisible(false, false); 18307 } 18308 mBackground.setCallback(null); 18309 unscheduleDrawable(mBackground); 18310 } 18311 18312 if (background != null) { 18313 Rect padding = sThreadLocal.get(); 18314 if (padding == null) { 18315 padding = new Rect(); 18316 sThreadLocal.set(padding); 18317 } 18318 resetResolvedDrawablesInternal(); 18319 background.setLayoutDirection(getLayoutDirection()); 18320 if (background.getPadding(padding)) { 18321 resetResolvedPaddingInternal(); 18322 switch (background.getLayoutDirection()) { 18323 case LAYOUT_DIRECTION_RTL: 18324 mUserPaddingLeftInitial = padding.right; 18325 mUserPaddingRightInitial = padding.left; 18326 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18327 break; 18328 case LAYOUT_DIRECTION_LTR: 18329 default: 18330 mUserPaddingLeftInitial = padding.left; 18331 mUserPaddingRightInitial = padding.right; 18332 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18333 } 18334 mLeftPaddingDefined = false; 18335 mRightPaddingDefined = false; 18336 } 18337 18338 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18339 // if it has a different minimum size, we should layout again 18340 if (mBackground == null 18341 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18342 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18343 requestLayout = true; 18344 } 18345 18346 // Set mBackground before we set this as the callback and start making other 18347 // background drawable state change calls. In particular, the setVisible call below 18348 // can result in drawables attempting to start animations or otherwise invalidate, 18349 // which requires the view set as the callback (us) to recognize the drawable as 18350 // belonging to it as per verifyDrawable. 18351 mBackground = background; 18352 if (background.isStateful()) { 18353 background.setState(getDrawableState()); 18354 } 18355 if (isAttachedToWindow()) { 18356 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18357 } 18358 18359 applyBackgroundTint(); 18360 18361 // Set callback last, since the view may still be initializing. 18362 background.setCallback(this); 18363 18364 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18365 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18366 requestLayout = true; 18367 } 18368 } else { 18369 /* Remove the background */ 18370 mBackground = null; 18371 if ((mViewFlags & WILL_NOT_DRAW) != 0 18372 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18373 mPrivateFlags |= PFLAG_SKIP_DRAW; 18374 } 18375 18376 /* 18377 * When the background is set, we try to apply its padding to this 18378 * View. When the background is removed, we don't touch this View's 18379 * padding. This is noted in the Javadocs. Hence, we don't need to 18380 * requestLayout(), the invalidate() below is sufficient. 18381 */ 18382 18383 // The old background's minimum size could have affected this 18384 // View's layout, so let's requestLayout 18385 requestLayout = true; 18386 } 18387 18388 computeOpaqueFlags(); 18389 18390 if (requestLayout) { 18391 requestLayout(); 18392 } 18393 18394 mBackgroundSizeChanged = true; 18395 invalidate(true); 18396 invalidateOutline(); 18397 } 18398 18399 /** 18400 * Gets the background drawable 18401 * 18402 * @return The drawable used as the background for this view, if any. 18403 * 18404 * @see #setBackground(Drawable) 18405 * 18406 * @attr ref android.R.styleable#View_background 18407 */ 18408 public Drawable getBackground() { 18409 return mBackground; 18410 } 18411 18412 /** 18413 * Applies a tint to the background drawable. Does not modify the current tint 18414 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18415 * <p> 18416 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18417 * mutate the drawable and apply the specified tint and tint mode using 18418 * {@link Drawable#setTintList(ColorStateList)}. 18419 * 18420 * @param tint the tint to apply, may be {@code null} to clear tint 18421 * 18422 * @attr ref android.R.styleable#View_backgroundTint 18423 * @see #getBackgroundTintList() 18424 * @see Drawable#setTintList(ColorStateList) 18425 */ 18426 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18427 if (mBackgroundTint == null) { 18428 mBackgroundTint = new TintInfo(); 18429 } 18430 mBackgroundTint.mTintList = tint; 18431 mBackgroundTint.mHasTintList = true; 18432 18433 applyBackgroundTint(); 18434 } 18435 18436 /** 18437 * Return the tint applied to the background drawable, if specified. 18438 * 18439 * @return the tint applied to the background drawable 18440 * @attr ref android.R.styleable#View_backgroundTint 18441 * @see #setBackgroundTintList(ColorStateList) 18442 */ 18443 @Nullable 18444 public ColorStateList getBackgroundTintList() { 18445 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18446 } 18447 18448 /** 18449 * Specifies the blending mode used to apply the tint specified by 18450 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18451 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18452 * 18453 * @param tintMode the blending mode used to apply the tint, may be 18454 * {@code null} to clear tint 18455 * @attr ref android.R.styleable#View_backgroundTintMode 18456 * @see #getBackgroundTintMode() 18457 * @see Drawable#setTintMode(PorterDuff.Mode) 18458 */ 18459 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18460 if (mBackgroundTint == null) { 18461 mBackgroundTint = new TintInfo(); 18462 } 18463 mBackgroundTint.mTintMode = tintMode; 18464 mBackgroundTint.mHasTintMode = true; 18465 18466 applyBackgroundTint(); 18467 } 18468 18469 /** 18470 * Return the blending mode used to apply the tint to the background 18471 * drawable, if specified. 18472 * 18473 * @return the blending mode used to apply the tint to the background 18474 * drawable 18475 * @attr ref android.R.styleable#View_backgroundTintMode 18476 * @see #setBackgroundTintMode(PorterDuff.Mode) 18477 */ 18478 @Nullable 18479 public PorterDuff.Mode getBackgroundTintMode() { 18480 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18481 } 18482 18483 private void applyBackgroundTint() { 18484 if (mBackground != null && mBackgroundTint != null) { 18485 final TintInfo tintInfo = mBackgroundTint; 18486 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18487 mBackground = mBackground.mutate(); 18488 18489 if (tintInfo.mHasTintList) { 18490 mBackground.setTintList(tintInfo.mTintList); 18491 } 18492 18493 if (tintInfo.mHasTintMode) { 18494 mBackground.setTintMode(tintInfo.mTintMode); 18495 } 18496 18497 // The drawable (or one of its children) may not have been 18498 // stateful before applying the tint, so let's try again. 18499 if (mBackground.isStateful()) { 18500 mBackground.setState(getDrawableState()); 18501 } 18502 } 18503 } 18504 } 18505 18506 /** 18507 * Returns the drawable used as the foreground of this View. The 18508 * foreground drawable, if non-null, is always drawn on top of the view's content. 18509 * 18510 * @return a Drawable or null if no foreground was set 18511 * 18512 * @see #onDrawForeground(Canvas) 18513 */ 18514 public Drawable getForeground() { 18515 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18516 } 18517 18518 /** 18519 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18520 * 18521 * @param foreground the Drawable to be drawn on top of the children 18522 * 18523 * @attr ref android.R.styleable#View_foreground 18524 */ 18525 public void setForeground(Drawable foreground) { 18526 if (mForegroundInfo == null) { 18527 if (foreground == null) { 18528 // Nothing to do. 18529 return; 18530 } 18531 mForegroundInfo = new ForegroundInfo(); 18532 } 18533 18534 if (foreground == mForegroundInfo.mDrawable) { 18535 // Nothing to do 18536 return; 18537 } 18538 18539 if (mForegroundInfo.mDrawable != null) { 18540 if (isAttachedToWindow()) { 18541 mForegroundInfo.mDrawable.setVisible(false, false); 18542 } 18543 mForegroundInfo.mDrawable.setCallback(null); 18544 unscheduleDrawable(mForegroundInfo.mDrawable); 18545 } 18546 18547 mForegroundInfo.mDrawable = foreground; 18548 mForegroundInfo.mBoundsChanged = true; 18549 if (foreground != null) { 18550 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18551 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18552 } 18553 foreground.setLayoutDirection(getLayoutDirection()); 18554 if (foreground.isStateful()) { 18555 foreground.setState(getDrawableState()); 18556 } 18557 applyForegroundTint(); 18558 if (isAttachedToWindow()) { 18559 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18560 } 18561 // Set callback last, since the view may still be initializing. 18562 foreground.setCallback(this); 18563 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18564 mPrivateFlags |= PFLAG_SKIP_DRAW; 18565 } 18566 requestLayout(); 18567 invalidate(); 18568 } 18569 18570 /** 18571 * Magic bit used to support features of framework-internal window decor implementation details. 18572 * This used to live exclusively in FrameLayout. 18573 * 18574 * @return true if the foreground should draw inside the padding region or false 18575 * if it should draw inset by the view's padding 18576 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18577 */ 18578 public boolean isForegroundInsidePadding() { 18579 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18580 } 18581 18582 /** 18583 * Describes how the foreground is positioned. 18584 * 18585 * @return foreground gravity. 18586 * 18587 * @see #setForegroundGravity(int) 18588 * 18589 * @attr ref android.R.styleable#View_foregroundGravity 18590 */ 18591 public int getForegroundGravity() { 18592 return mForegroundInfo != null ? mForegroundInfo.mGravity 18593 : Gravity.START | Gravity.TOP; 18594 } 18595 18596 /** 18597 * Describes how the foreground is positioned. Defaults to START and TOP. 18598 * 18599 * @param gravity see {@link android.view.Gravity} 18600 * 18601 * @see #getForegroundGravity() 18602 * 18603 * @attr ref android.R.styleable#View_foregroundGravity 18604 */ 18605 public void setForegroundGravity(int gravity) { 18606 if (mForegroundInfo == null) { 18607 mForegroundInfo = new ForegroundInfo(); 18608 } 18609 18610 if (mForegroundInfo.mGravity != gravity) { 18611 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18612 gravity |= Gravity.START; 18613 } 18614 18615 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18616 gravity |= Gravity.TOP; 18617 } 18618 18619 mForegroundInfo.mGravity = gravity; 18620 requestLayout(); 18621 } 18622 } 18623 18624 /** 18625 * Applies a tint to the foreground drawable. Does not modify the current tint 18626 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18627 * <p> 18628 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18629 * mutate the drawable and apply the specified tint and tint mode using 18630 * {@link Drawable#setTintList(ColorStateList)}. 18631 * 18632 * @param tint the tint to apply, may be {@code null} to clear tint 18633 * 18634 * @attr ref android.R.styleable#View_foregroundTint 18635 * @see #getForegroundTintList() 18636 * @see Drawable#setTintList(ColorStateList) 18637 */ 18638 public void setForegroundTintList(@Nullable ColorStateList tint) { 18639 if (mForegroundInfo == null) { 18640 mForegroundInfo = new ForegroundInfo(); 18641 } 18642 if (mForegroundInfo.mTintInfo == null) { 18643 mForegroundInfo.mTintInfo = new TintInfo(); 18644 } 18645 mForegroundInfo.mTintInfo.mTintList = tint; 18646 mForegroundInfo.mTintInfo.mHasTintList = true; 18647 18648 applyForegroundTint(); 18649 } 18650 18651 /** 18652 * Return the tint applied to the foreground drawable, if specified. 18653 * 18654 * @return the tint applied to the foreground drawable 18655 * @attr ref android.R.styleable#View_foregroundTint 18656 * @see #setForegroundTintList(ColorStateList) 18657 */ 18658 @Nullable 18659 public ColorStateList getForegroundTintList() { 18660 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18661 ? mForegroundInfo.mTintInfo.mTintList : null; 18662 } 18663 18664 /** 18665 * Specifies the blending mode used to apply the tint specified by 18666 * {@link #setForegroundTintList(ColorStateList)}} to the background 18667 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18668 * 18669 * @param tintMode the blending mode used to apply the tint, may be 18670 * {@code null} to clear tint 18671 * @attr ref android.R.styleable#View_foregroundTintMode 18672 * @see #getForegroundTintMode() 18673 * @see Drawable#setTintMode(PorterDuff.Mode) 18674 */ 18675 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18676 if (mForegroundInfo == null) { 18677 mForegroundInfo = new ForegroundInfo(); 18678 } 18679 if (mForegroundInfo.mTintInfo == null) { 18680 mForegroundInfo.mTintInfo = new TintInfo(); 18681 } 18682 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18683 mForegroundInfo.mTintInfo.mHasTintMode = true; 18684 18685 applyForegroundTint(); 18686 } 18687 18688 /** 18689 * Return the blending mode used to apply the tint to the foreground 18690 * drawable, if specified. 18691 * 18692 * @return the blending mode used to apply the tint to the foreground 18693 * drawable 18694 * @attr ref android.R.styleable#View_foregroundTintMode 18695 * @see #setForegroundTintMode(PorterDuff.Mode) 18696 */ 18697 @Nullable 18698 public PorterDuff.Mode getForegroundTintMode() { 18699 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18700 ? mForegroundInfo.mTintInfo.mTintMode : null; 18701 } 18702 18703 private void applyForegroundTint() { 18704 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18705 && mForegroundInfo.mTintInfo != null) { 18706 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18707 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18708 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18709 18710 if (tintInfo.mHasTintList) { 18711 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18712 } 18713 18714 if (tintInfo.mHasTintMode) { 18715 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18716 } 18717 18718 // The drawable (or one of its children) may not have been 18719 // stateful before applying the tint, so let's try again. 18720 if (mForegroundInfo.mDrawable.isStateful()) { 18721 mForegroundInfo.mDrawable.setState(getDrawableState()); 18722 } 18723 } 18724 } 18725 } 18726 18727 /** 18728 * Draw any foreground content for this view. 18729 * 18730 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18731 * drawable or other view-specific decorations. The foreground is drawn on top of the 18732 * primary view content.</p> 18733 * 18734 * @param canvas canvas to draw into 18735 */ 18736 public void onDrawForeground(Canvas canvas) { 18737 onDrawScrollIndicators(canvas); 18738 onDrawScrollBars(canvas); 18739 18740 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18741 if (foreground != null) { 18742 if (mForegroundInfo.mBoundsChanged) { 18743 mForegroundInfo.mBoundsChanged = false; 18744 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18745 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18746 18747 if (mForegroundInfo.mInsidePadding) { 18748 selfBounds.set(0, 0, getWidth(), getHeight()); 18749 } else { 18750 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18751 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18752 } 18753 18754 final int ld = getLayoutDirection(); 18755 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18756 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18757 foreground.setBounds(overlayBounds); 18758 } 18759 18760 foreground.draw(canvas); 18761 } 18762 } 18763 18764 /** 18765 * Sets the padding. The view may add on the space required to display 18766 * the scrollbars, depending on the style and visibility of the scrollbars. 18767 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18768 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18769 * from the values set in this call. 18770 * 18771 * @attr ref android.R.styleable#View_padding 18772 * @attr ref android.R.styleable#View_paddingBottom 18773 * @attr ref android.R.styleable#View_paddingLeft 18774 * @attr ref android.R.styleable#View_paddingRight 18775 * @attr ref android.R.styleable#View_paddingTop 18776 * @param left the left padding in pixels 18777 * @param top the top padding in pixels 18778 * @param right the right padding in pixels 18779 * @param bottom the bottom padding in pixels 18780 */ 18781 public void setPadding(int left, int top, int right, int bottom) { 18782 resetResolvedPaddingInternal(); 18783 18784 mUserPaddingStart = UNDEFINED_PADDING; 18785 mUserPaddingEnd = UNDEFINED_PADDING; 18786 18787 mUserPaddingLeftInitial = left; 18788 mUserPaddingRightInitial = right; 18789 18790 mLeftPaddingDefined = true; 18791 mRightPaddingDefined = true; 18792 18793 internalSetPadding(left, top, right, bottom); 18794 } 18795 18796 /** 18797 * @hide 18798 */ 18799 protected void internalSetPadding(int left, int top, int right, int bottom) { 18800 mUserPaddingLeft = left; 18801 mUserPaddingRight = right; 18802 mUserPaddingBottom = bottom; 18803 18804 final int viewFlags = mViewFlags; 18805 boolean changed = false; 18806 18807 // Common case is there are no scroll bars. 18808 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18809 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18810 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18811 ? 0 : getVerticalScrollbarWidth(); 18812 switch (mVerticalScrollbarPosition) { 18813 case SCROLLBAR_POSITION_DEFAULT: 18814 if (isLayoutRtl()) { 18815 left += offset; 18816 } else { 18817 right += offset; 18818 } 18819 break; 18820 case SCROLLBAR_POSITION_RIGHT: 18821 right += offset; 18822 break; 18823 case SCROLLBAR_POSITION_LEFT: 18824 left += offset; 18825 break; 18826 } 18827 } 18828 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18829 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18830 ? 0 : getHorizontalScrollbarHeight(); 18831 } 18832 } 18833 18834 if (mPaddingLeft != left) { 18835 changed = true; 18836 mPaddingLeft = left; 18837 } 18838 if (mPaddingTop != top) { 18839 changed = true; 18840 mPaddingTop = top; 18841 } 18842 if (mPaddingRight != right) { 18843 changed = true; 18844 mPaddingRight = right; 18845 } 18846 if (mPaddingBottom != bottom) { 18847 changed = true; 18848 mPaddingBottom = bottom; 18849 } 18850 18851 if (changed) { 18852 requestLayout(); 18853 invalidateOutline(); 18854 } 18855 } 18856 18857 /** 18858 * Sets the relative padding. The view may add on the space required to display 18859 * the scrollbars, depending on the style and visibility of the scrollbars. 18860 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18861 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18862 * from the values set in this call. 18863 * 18864 * @attr ref android.R.styleable#View_padding 18865 * @attr ref android.R.styleable#View_paddingBottom 18866 * @attr ref android.R.styleable#View_paddingStart 18867 * @attr ref android.R.styleable#View_paddingEnd 18868 * @attr ref android.R.styleable#View_paddingTop 18869 * @param start the start padding in pixels 18870 * @param top the top padding in pixels 18871 * @param end the end padding in pixels 18872 * @param bottom the bottom padding in pixels 18873 */ 18874 public void setPaddingRelative(int start, int top, int end, int bottom) { 18875 resetResolvedPaddingInternal(); 18876 18877 mUserPaddingStart = start; 18878 mUserPaddingEnd = end; 18879 mLeftPaddingDefined = true; 18880 mRightPaddingDefined = true; 18881 18882 switch(getLayoutDirection()) { 18883 case LAYOUT_DIRECTION_RTL: 18884 mUserPaddingLeftInitial = end; 18885 mUserPaddingRightInitial = start; 18886 internalSetPadding(end, top, start, bottom); 18887 break; 18888 case LAYOUT_DIRECTION_LTR: 18889 default: 18890 mUserPaddingLeftInitial = start; 18891 mUserPaddingRightInitial = end; 18892 internalSetPadding(start, top, end, bottom); 18893 } 18894 } 18895 18896 /** 18897 * Returns the top padding of this view. 18898 * 18899 * @return the top padding in pixels 18900 */ 18901 public int getPaddingTop() { 18902 return mPaddingTop; 18903 } 18904 18905 /** 18906 * Returns the bottom padding of this view. If there are inset and enabled 18907 * scrollbars, this value may include the space required to display the 18908 * scrollbars as well. 18909 * 18910 * @return the bottom padding in pixels 18911 */ 18912 public int getPaddingBottom() { 18913 return mPaddingBottom; 18914 } 18915 18916 /** 18917 * Returns the left padding of this view. If there are inset and enabled 18918 * scrollbars, this value may include the space required to display the 18919 * scrollbars as well. 18920 * 18921 * @return the left padding in pixels 18922 */ 18923 public int getPaddingLeft() { 18924 if (!isPaddingResolved()) { 18925 resolvePadding(); 18926 } 18927 return mPaddingLeft; 18928 } 18929 18930 /** 18931 * Returns the start padding of this view depending on its resolved layout direction. 18932 * If there are inset and enabled scrollbars, this value may include the space 18933 * required to display the scrollbars as well. 18934 * 18935 * @return the start padding in pixels 18936 */ 18937 public int getPaddingStart() { 18938 if (!isPaddingResolved()) { 18939 resolvePadding(); 18940 } 18941 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18942 mPaddingRight : mPaddingLeft; 18943 } 18944 18945 /** 18946 * Returns the right padding of this view. If there are inset and enabled 18947 * scrollbars, this value may include the space required to display the 18948 * scrollbars as well. 18949 * 18950 * @return the right padding in pixels 18951 */ 18952 public int getPaddingRight() { 18953 if (!isPaddingResolved()) { 18954 resolvePadding(); 18955 } 18956 return mPaddingRight; 18957 } 18958 18959 /** 18960 * Returns the end padding of this view depending on its resolved layout direction. 18961 * If there are inset and enabled scrollbars, this value may include the space 18962 * required to display the scrollbars as well. 18963 * 18964 * @return the end padding in pixels 18965 */ 18966 public int getPaddingEnd() { 18967 if (!isPaddingResolved()) { 18968 resolvePadding(); 18969 } 18970 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18971 mPaddingLeft : mPaddingRight; 18972 } 18973 18974 /** 18975 * Return if the padding has been set through relative values 18976 * {@link #setPaddingRelative(int, int, int, int)} or through 18977 * @attr ref android.R.styleable#View_paddingStart or 18978 * @attr ref android.R.styleable#View_paddingEnd 18979 * 18980 * @return true if the padding is relative or false if it is not. 18981 */ 18982 public boolean isPaddingRelative() { 18983 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18984 } 18985 18986 Insets computeOpticalInsets() { 18987 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18988 } 18989 18990 /** 18991 * @hide 18992 */ 18993 public void resetPaddingToInitialValues() { 18994 if (isRtlCompatibilityMode()) { 18995 mPaddingLeft = mUserPaddingLeftInitial; 18996 mPaddingRight = mUserPaddingRightInitial; 18997 return; 18998 } 18999 if (isLayoutRtl()) { 19000 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 19001 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 19002 } else { 19003 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 19004 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 19005 } 19006 } 19007 19008 /** 19009 * @hide 19010 */ 19011 public Insets getOpticalInsets() { 19012 if (mLayoutInsets == null) { 19013 mLayoutInsets = computeOpticalInsets(); 19014 } 19015 return mLayoutInsets; 19016 } 19017 19018 /** 19019 * Set this view's optical insets. 19020 * 19021 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 19022 * property. Views that compute their own optical insets should call it as part of measurement. 19023 * This method does not request layout. If you are setting optical insets outside of 19024 * measure/layout itself you will want to call requestLayout() yourself. 19025 * </p> 19026 * @hide 19027 */ 19028 public void setOpticalInsets(Insets insets) { 19029 mLayoutInsets = insets; 19030 } 19031 19032 /** 19033 * Changes the selection state of this view. A view can be selected or not. 19034 * Note that selection is not the same as focus. Views are typically 19035 * selected in the context of an AdapterView like ListView or GridView; 19036 * the selected view is the view that is highlighted. 19037 * 19038 * @param selected true if the view must be selected, false otherwise 19039 */ 19040 public void setSelected(boolean selected) { 19041 //noinspection DoubleNegation 19042 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 19043 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 19044 if (!selected) resetPressedState(); 19045 invalidate(true); 19046 refreshDrawableState(); 19047 dispatchSetSelected(selected); 19048 if (selected) { 19049 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 19050 } else { 19051 notifyViewAccessibilityStateChangedIfNeeded( 19052 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 19053 } 19054 } 19055 } 19056 19057 /** 19058 * Dispatch setSelected to all of this View's children. 19059 * 19060 * @see #setSelected(boolean) 19061 * 19062 * @param selected The new selected state 19063 */ 19064 protected void dispatchSetSelected(boolean selected) { 19065 } 19066 19067 /** 19068 * Indicates the selection state of this view. 19069 * 19070 * @return true if the view is selected, false otherwise 19071 */ 19072 @ViewDebug.ExportedProperty 19073 public boolean isSelected() { 19074 return (mPrivateFlags & PFLAG_SELECTED) != 0; 19075 } 19076 19077 /** 19078 * Changes the activated state of this view. A view can be activated or not. 19079 * Note that activation is not the same as selection. Selection is 19080 * a transient property, representing the view (hierarchy) the user is 19081 * currently interacting with. Activation is a longer-term state that the 19082 * user can move views in and out of. For example, in a list view with 19083 * single or multiple selection enabled, the views in the current selection 19084 * set are activated. (Um, yeah, we are deeply sorry about the terminology 19085 * here.) The activated state is propagated down to children of the view it 19086 * is set on. 19087 * 19088 * @param activated true if the view must be activated, false otherwise 19089 */ 19090 public void setActivated(boolean activated) { 19091 //noinspection DoubleNegation 19092 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 19093 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 19094 invalidate(true); 19095 refreshDrawableState(); 19096 dispatchSetActivated(activated); 19097 } 19098 } 19099 19100 /** 19101 * Dispatch setActivated to all of this View's children. 19102 * 19103 * @see #setActivated(boolean) 19104 * 19105 * @param activated The new activated state 19106 */ 19107 protected void dispatchSetActivated(boolean activated) { 19108 } 19109 19110 /** 19111 * Indicates the activation state of this view. 19112 * 19113 * @return true if the view is activated, false otherwise 19114 */ 19115 @ViewDebug.ExportedProperty 19116 public boolean isActivated() { 19117 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 19118 } 19119 19120 /** 19121 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 19122 * observer can be used to get notifications when global events, like 19123 * layout, happen. 19124 * 19125 * The returned ViewTreeObserver observer is not guaranteed to remain 19126 * valid for the lifetime of this View. If the caller of this method keeps 19127 * a long-lived reference to ViewTreeObserver, it should always check for 19128 * the return value of {@link ViewTreeObserver#isAlive()}. 19129 * 19130 * @return The ViewTreeObserver for this view's hierarchy. 19131 */ 19132 public ViewTreeObserver getViewTreeObserver() { 19133 if (mAttachInfo != null) { 19134 return mAttachInfo.mTreeObserver; 19135 } 19136 if (mFloatingTreeObserver == null) { 19137 mFloatingTreeObserver = new ViewTreeObserver(mContext); 19138 } 19139 return mFloatingTreeObserver; 19140 } 19141 19142 /** 19143 * <p>Finds the topmost view in the current view hierarchy.</p> 19144 * 19145 * @return the topmost view containing this view 19146 */ 19147 public View getRootView() { 19148 if (mAttachInfo != null) { 19149 final View v = mAttachInfo.mRootView; 19150 if (v != null) { 19151 return v; 19152 } 19153 } 19154 19155 View parent = this; 19156 19157 while (parent.mParent != null && parent.mParent instanceof View) { 19158 parent = (View) parent.mParent; 19159 } 19160 19161 return parent; 19162 } 19163 19164 /** 19165 * Transforms a motion event from view-local coordinates to on-screen 19166 * coordinates. 19167 * 19168 * @param ev the view-local motion event 19169 * @return false if the transformation could not be applied 19170 * @hide 19171 */ 19172 public boolean toGlobalMotionEvent(MotionEvent ev) { 19173 final AttachInfo info = mAttachInfo; 19174 if (info == null) { 19175 return false; 19176 } 19177 19178 final Matrix m = info.mTmpMatrix; 19179 m.set(Matrix.IDENTITY_MATRIX); 19180 transformMatrixToGlobal(m); 19181 ev.transform(m); 19182 return true; 19183 } 19184 19185 /** 19186 * Transforms a motion event from on-screen coordinates to view-local 19187 * coordinates. 19188 * 19189 * @param ev the on-screen motion event 19190 * @return false if the transformation could not be applied 19191 * @hide 19192 */ 19193 public boolean toLocalMotionEvent(MotionEvent ev) { 19194 final AttachInfo info = mAttachInfo; 19195 if (info == null) { 19196 return false; 19197 } 19198 19199 final Matrix m = info.mTmpMatrix; 19200 m.set(Matrix.IDENTITY_MATRIX); 19201 transformMatrixToLocal(m); 19202 ev.transform(m); 19203 return true; 19204 } 19205 19206 /** 19207 * Modifies the input matrix such that it maps view-local coordinates to 19208 * on-screen coordinates. 19209 * 19210 * @param m input matrix to modify 19211 * @hide 19212 */ 19213 public void transformMatrixToGlobal(Matrix m) { 19214 final ViewParent parent = mParent; 19215 if (parent instanceof View) { 19216 final View vp = (View) parent; 19217 vp.transformMatrixToGlobal(m); 19218 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19219 } else if (parent instanceof ViewRootImpl) { 19220 final ViewRootImpl vr = (ViewRootImpl) parent; 19221 vr.transformMatrixToGlobal(m); 19222 m.preTranslate(0, -vr.mCurScrollY); 19223 } 19224 19225 m.preTranslate(mLeft, mTop); 19226 19227 if (!hasIdentityMatrix()) { 19228 m.preConcat(getMatrix()); 19229 } 19230 } 19231 19232 /** 19233 * Modifies the input matrix such that it maps on-screen coordinates to 19234 * view-local coordinates. 19235 * 19236 * @param m input matrix to modify 19237 * @hide 19238 */ 19239 public void transformMatrixToLocal(Matrix m) { 19240 final ViewParent parent = mParent; 19241 if (parent instanceof View) { 19242 final View vp = (View) parent; 19243 vp.transformMatrixToLocal(m); 19244 m.postTranslate(vp.mScrollX, vp.mScrollY); 19245 } else if (parent instanceof ViewRootImpl) { 19246 final ViewRootImpl vr = (ViewRootImpl) parent; 19247 vr.transformMatrixToLocal(m); 19248 m.postTranslate(0, vr.mCurScrollY); 19249 } 19250 19251 m.postTranslate(-mLeft, -mTop); 19252 19253 if (!hasIdentityMatrix()) { 19254 m.postConcat(getInverseMatrix()); 19255 } 19256 } 19257 19258 /** 19259 * @hide 19260 */ 19261 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19262 @ViewDebug.IntToString(from = 0, to = "x"), 19263 @ViewDebug.IntToString(from = 1, to = "y") 19264 }) 19265 public int[] getLocationOnScreen() { 19266 int[] location = new int[2]; 19267 getLocationOnScreen(location); 19268 return location; 19269 } 19270 19271 /** 19272 * <p>Computes the coordinates of this view on the screen. The argument 19273 * must be an array of two integers. After the method returns, the array 19274 * contains the x and y location in that order.</p> 19275 * 19276 * @param outLocation an array of two integers in which to hold the coordinates 19277 */ 19278 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19279 getLocationInWindow(outLocation); 19280 19281 final AttachInfo info = mAttachInfo; 19282 if (info != null) { 19283 outLocation[0] += info.mWindowLeft; 19284 outLocation[1] += info.mWindowTop; 19285 } 19286 } 19287 19288 /** 19289 * <p>Computes the coordinates of this view in its window. The argument 19290 * must be an array of two integers. After the method returns, the array 19291 * contains the x and y location in that order.</p> 19292 * 19293 * @param outLocation an array of two integers in which to hold the coordinates 19294 */ 19295 public void getLocationInWindow(@Size(2) int[] outLocation) { 19296 if (outLocation == null || outLocation.length < 2) { 19297 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19298 } 19299 19300 outLocation[0] = 0; 19301 outLocation[1] = 0; 19302 19303 transformFromViewToWindowSpace(outLocation); 19304 } 19305 19306 /** @hide */ 19307 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19308 if (inOutLocation == null || inOutLocation.length < 2) { 19309 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19310 } 19311 19312 if (mAttachInfo == null) { 19313 // When the view is not attached to a window, this method does not make sense 19314 inOutLocation[0] = inOutLocation[1] = 0; 19315 return; 19316 } 19317 19318 float position[] = mAttachInfo.mTmpTransformLocation; 19319 position[0] = inOutLocation[0]; 19320 position[1] = inOutLocation[1]; 19321 19322 if (!hasIdentityMatrix()) { 19323 getMatrix().mapPoints(position); 19324 } 19325 19326 position[0] += mLeft; 19327 position[1] += mTop; 19328 19329 ViewParent viewParent = mParent; 19330 while (viewParent instanceof View) { 19331 final View view = (View) viewParent; 19332 19333 position[0] -= view.mScrollX; 19334 position[1] -= view.mScrollY; 19335 19336 if (!view.hasIdentityMatrix()) { 19337 view.getMatrix().mapPoints(position); 19338 } 19339 19340 position[0] += view.mLeft; 19341 position[1] += view.mTop; 19342 19343 viewParent = view.mParent; 19344 } 19345 19346 if (viewParent instanceof ViewRootImpl) { 19347 // *cough* 19348 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19349 position[1] -= vr.mCurScrollY; 19350 } 19351 19352 inOutLocation[0] = Math.round(position[0]); 19353 inOutLocation[1] = Math.round(position[1]); 19354 } 19355 19356 /** 19357 * {@hide} 19358 * @param id the id of the view to be found 19359 * @return the view of the specified id, null if cannot be found 19360 */ 19361 protected View findViewTraversal(@IdRes int id) { 19362 if (id == mID) { 19363 return this; 19364 } 19365 return null; 19366 } 19367 19368 /** 19369 * {@hide} 19370 * @param tag the tag of the view to be found 19371 * @return the view of specified tag, null if cannot be found 19372 */ 19373 protected View findViewWithTagTraversal(Object tag) { 19374 if (tag != null && tag.equals(mTag)) { 19375 return this; 19376 } 19377 return null; 19378 } 19379 19380 /** 19381 * {@hide} 19382 * @param predicate The predicate to evaluate. 19383 * @param childToSkip If not null, ignores this child during the recursive traversal. 19384 * @return The first view that matches the predicate or null. 19385 */ 19386 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19387 if (predicate.apply(this)) { 19388 return this; 19389 } 19390 return null; 19391 } 19392 19393 /** 19394 * Look for a child view with the given id. If this view has the given 19395 * id, return this view. 19396 * 19397 * @param id The id to search for. 19398 * @return The view that has the given id in the hierarchy or null 19399 */ 19400 @Nullable 19401 public final View findViewById(@IdRes int id) { 19402 if (id < 0) { 19403 return null; 19404 } 19405 return findViewTraversal(id); 19406 } 19407 19408 /** 19409 * Finds a view by its unuque and stable accessibility id. 19410 * 19411 * @param accessibilityId The searched accessibility id. 19412 * @return The found view. 19413 */ 19414 final View findViewByAccessibilityId(int accessibilityId) { 19415 if (accessibilityId < 0) { 19416 return null; 19417 } 19418 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19419 if (view != null) { 19420 return view.includeForAccessibility() ? view : null; 19421 } 19422 return null; 19423 } 19424 19425 /** 19426 * Performs the traversal to find a view by its unuque and stable accessibility id. 19427 * 19428 * <strong>Note:</strong>This method does not stop at the root namespace 19429 * boundary since the user can touch the screen at an arbitrary location 19430 * potentially crossing the root namespace bounday which will send an 19431 * accessibility event to accessibility services and they should be able 19432 * to obtain the event source. Also accessibility ids are guaranteed to be 19433 * unique in the window. 19434 * 19435 * @param accessibilityId The accessibility id. 19436 * @return The found view. 19437 * 19438 * @hide 19439 */ 19440 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19441 if (getAccessibilityViewId() == accessibilityId) { 19442 return this; 19443 } 19444 return null; 19445 } 19446 19447 /** 19448 * Look for a child view with the given tag. If this view has the given 19449 * tag, return this view. 19450 * 19451 * @param tag The tag to search for, using "tag.equals(getTag())". 19452 * @return The View that has the given tag in the hierarchy or null 19453 */ 19454 public final View findViewWithTag(Object tag) { 19455 if (tag == null) { 19456 return null; 19457 } 19458 return findViewWithTagTraversal(tag); 19459 } 19460 19461 /** 19462 * {@hide} 19463 * Look for a child view that matches the specified predicate. 19464 * If this view matches the predicate, return this view. 19465 * 19466 * @param predicate The predicate to evaluate. 19467 * @return The first view that matches the predicate or null. 19468 */ 19469 public final View findViewByPredicate(Predicate<View> predicate) { 19470 return findViewByPredicateTraversal(predicate, null); 19471 } 19472 19473 /** 19474 * {@hide} 19475 * Look for a child view that matches the specified predicate, 19476 * starting with the specified view and its descendents and then 19477 * recusively searching the ancestors and siblings of that view 19478 * until this view is reached. 19479 * 19480 * This method is useful in cases where the predicate does not match 19481 * a single unique view (perhaps multiple views use the same id) 19482 * and we are trying to find the view that is "closest" in scope to the 19483 * starting view. 19484 * 19485 * @param start The view to start from. 19486 * @param predicate The predicate to evaluate. 19487 * @return The first view that matches the predicate or null. 19488 */ 19489 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19490 View childToSkip = null; 19491 for (;;) { 19492 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19493 if (view != null || start == this) { 19494 return view; 19495 } 19496 19497 ViewParent parent = start.getParent(); 19498 if (parent == null || !(parent instanceof View)) { 19499 return null; 19500 } 19501 19502 childToSkip = start; 19503 start = (View) parent; 19504 } 19505 } 19506 19507 /** 19508 * Sets the identifier for this view. The identifier does not have to be 19509 * unique in this view's hierarchy. The identifier should be a positive 19510 * number. 19511 * 19512 * @see #NO_ID 19513 * @see #getId() 19514 * @see #findViewById(int) 19515 * 19516 * @param id a number used to identify the view 19517 * 19518 * @attr ref android.R.styleable#View_id 19519 */ 19520 public void setId(@IdRes int id) { 19521 mID = id; 19522 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19523 mID = generateViewId(); 19524 } 19525 } 19526 19527 /** 19528 * {@hide} 19529 * 19530 * @param isRoot true if the view belongs to the root namespace, false 19531 * otherwise 19532 */ 19533 public void setIsRootNamespace(boolean isRoot) { 19534 if (isRoot) { 19535 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19536 } else { 19537 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19538 } 19539 } 19540 19541 /** 19542 * {@hide} 19543 * 19544 * @return true if the view belongs to the root namespace, false otherwise 19545 */ 19546 public boolean isRootNamespace() { 19547 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19548 } 19549 19550 /** 19551 * Returns this view's identifier. 19552 * 19553 * @return a positive integer used to identify the view or {@link #NO_ID} 19554 * if the view has no ID 19555 * 19556 * @see #setId(int) 19557 * @see #findViewById(int) 19558 * @attr ref android.R.styleable#View_id 19559 */ 19560 @IdRes 19561 @ViewDebug.CapturedViewProperty 19562 public int getId() { 19563 return mID; 19564 } 19565 19566 /** 19567 * Returns this view's tag. 19568 * 19569 * @return the Object stored in this view as a tag, or {@code null} if not 19570 * set 19571 * 19572 * @see #setTag(Object) 19573 * @see #getTag(int) 19574 */ 19575 @ViewDebug.ExportedProperty 19576 public Object getTag() { 19577 return mTag; 19578 } 19579 19580 /** 19581 * Sets the tag associated with this view. A tag can be used to mark 19582 * a view in its hierarchy and does not have to be unique within the 19583 * hierarchy. Tags can also be used to store data within a view without 19584 * resorting to another data structure. 19585 * 19586 * @param tag an Object to tag the view with 19587 * 19588 * @see #getTag() 19589 * @see #setTag(int, Object) 19590 */ 19591 public void setTag(final Object tag) { 19592 mTag = tag; 19593 } 19594 19595 /** 19596 * Returns the tag associated with this view and the specified key. 19597 * 19598 * @param key The key identifying the tag 19599 * 19600 * @return the Object stored in this view as a tag, or {@code null} if not 19601 * set 19602 * 19603 * @see #setTag(int, Object) 19604 * @see #getTag() 19605 */ 19606 public Object getTag(int key) { 19607 if (mKeyedTags != null) return mKeyedTags.get(key); 19608 return null; 19609 } 19610 19611 /** 19612 * Sets a tag associated with this view and a key. A tag can be used 19613 * to mark a view in its hierarchy and does not have to be unique within 19614 * the hierarchy. Tags can also be used to store data within a view 19615 * without resorting to another data structure. 19616 * 19617 * The specified key should be an id declared in the resources of the 19618 * application to ensure it is unique (see the <a 19619 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19620 * Keys identified as belonging to 19621 * the Android framework or not associated with any package will cause 19622 * an {@link IllegalArgumentException} to be thrown. 19623 * 19624 * @param key The key identifying the tag 19625 * @param tag An Object to tag the view with 19626 * 19627 * @throws IllegalArgumentException If they specified key is not valid 19628 * 19629 * @see #setTag(Object) 19630 * @see #getTag(int) 19631 */ 19632 public void setTag(int key, final Object tag) { 19633 // If the package id is 0x00 or 0x01, it's either an undefined package 19634 // or a framework id 19635 if ((key >>> 24) < 2) { 19636 throw new IllegalArgumentException("The key must be an application-specific " 19637 + "resource id."); 19638 } 19639 19640 setKeyedTag(key, tag); 19641 } 19642 19643 /** 19644 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19645 * framework id. 19646 * 19647 * @hide 19648 */ 19649 public void setTagInternal(int key, Object tag) { 19650 if ((key >>> 24) != 0x1) { 19651 throw new IllegalArgumentException("The key must be a framework-specific " 19652 + "resource id."); 19653 } 19654 19655 setKeyedTag(key, tag); 19656 } 19657 19658 private void setKeyedTag(int key, Object tag) { 19659 if (mKeyedTags == null) { 19660 mKeyedTags = new SparseArray<Object>(2); 19661 } 19662 19663 mKeyedTags.put(key, tag); 19664 } 19665 19666 /** 19667 * Prints information about this view in the log output, with the tag 19668 * {@link #VIEW_LOG_TAG}. 19669 * 19670 * @hide 19671 */ 19672 public void debug() { 19673 debug(0); 19674 } 19675 19676 /** 19677 * Prints information about this view in the log output, with the tag 19678 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19679 * indentation defined by the <code>depth</code>. 19680 * 19681 * @param depth the indentation level 19682 * 19683 * @hide 19684 */ 19685 protected void debug(int depth) { 19686 String output = debugIndent(depth - 1); 19687 19688 output += "+ " + this; 19689 int id = getId(); 19690 if (id != -1) { 19691 output += " (id=" + id + ")"; 19692 } 19693 Object tag = getTag(); 19694 if (tag != null) { 19695 output += " (tag=" + tag + ")"; 19696 } 19697 Log.d(VIEW_LOG_TAG, output); 19698 19699 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19700 output = debugIndent(depth) + " FOCUSED"; 19701 Log.d(VIEW_LOG_TAG, output); 19702 } 19703 19704 output = debugIndent(depth); 19705 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19706 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19707 + "} "; 19708 Log.d(VIEW_LOG_TAG, output); 19709 19710 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19711 || mPaddingBottom != 0) { 19712 output = debugIndent(depth); 19713 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19714 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19715 Log.d(VIEW_LOG_TAG, output); 19716 } 19717 19718 output = debugIndent(depth); 19719 output += "mMeasureWidth=" + mMeasuredWidth + 19720 " mMeasureHeight=" + mMeasuredHeight; 19721 Log.d(VIEW_LOG_TAG, output); 19722 19723 output = debugIndent(depth); 19724 if (mLayoutParams == null) { 19725 output += "BAD! no layout params"; 19726 } else { 19727 output = mLayoutParams.debug(output); 19728 } 19729 Log.d(VIEW_LOG_TAG, output); 19730 19731 output = debugIndent(depth); 19732 output += "flags={"; 19733 output += View.printFlags(mViewFlags); 19734 output += "}"; 19735 Log.d(VIEW_LOG_TAG, output); 19736 19737 output = debugIndent(depth); 19738 output += "privateFlags={"; 19739 output += View.printPrivateFlags(mPrivateFlags); 19740 output += "}"; 19741 Log.d(VIEW_LOG_TAG, output); 19742 } 19743 19744 /** 19745 * Creates a string of whitespaces used for indentation. 19746 * 19747 * @param depth the indentation level 19748 * @return a String containing (depth * 2 + 3) * 2 white spaces 19749 * 19750 * @hide 19751 */ 19752 protected static String debugIndent(int depth) { 19753 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19754 for (int i = 0; i < (depth * 2) + 3; i++) { 19755 spaces.append(' ').append(' '); 19756 } 19757 return spaces.toString(); 19758 } 19759 19760 /** 19761 * <p>Return the offset of the widget's text baseline from the widget's top 19762 * boundary. If this widget does not support baseline alignment, this 19763 * method returns -1. </p> 19764 * 19765 * @return the offset of the baseline within the widget's bounds or -1 19766 * if baseline alignment is not supported 19767 */ 19768 @ViewDebug.ExportedProperty(category = "layout") 19769 public int getBaseline() { 19770 return -1; 19771 } 19772 19773 /** 19774 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19775 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19776 * a layout pass. 19777 * 19778 * @return whether the view hierarchy is currently undergoing a layout pass 19779 */ 19780 public boolean isInLayout() { 19781 ViewRootImpl viewRoot = getViewRootImpl(); 19782 return (viewRoot != null && viewRoot.isInLayout()); 19783 } 19784 19785 /** 19786 * Call this when something has changed which has invalidated the 19787 * layout of this view. This will schedule a layout pass of the view 19788 * tree. This should not be called while the view hierarchy is currently in a layout 19789 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19790 * end of the current layout pass (and then layout will run again) or after the current 19791 * frame is drawn and the next layout occurs. 19792 * 19793 * <p>Subclasses which override this method should call the superclass method to 19794 * handle possible request-during-layout errors correctly.</p> 19795 */ 19796 @CallSuper 19797 public void requestLayout() { 19798 if (mMeasureCache != null) mMeasureCache.clear(); 19799 19800 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19801 // Only trigger request-during-layout logic if this is the view requesting it, 19802 // not the views in its parent hierarchy 19803 ViewRootImpl viewRoot = getViewRootImpl(); 19804 if (viewRoot != null && viewRoot.isInLayout()) { 19805 if (!viewRoot.requestLayoutDuringLayout(this)) { 19806 return; 19807 } 19808 } 19809 mAttachInfo.mViewRequestingLayout = this; 19810 } 19811 19812 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19813 mPrivateFlags |= PFLAG_INVALIDATED; 19814 19815 if (mParent != null && !mParent.isLayoutRequested()) { 19816 mParent.requestLayout(); 19817 } 19818 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19819 mAttachInfo.mViewRequestingLayout = null; 19820 } 19821 } 19822 19823 /** 19824 * Forces this view to be laid out during the next layout pass. 19825 * This method does not call requestLayout() or forceLayout() 19826 * on the parent. 19827 */ 19828 public void forceLayout() { 19829 if (mMeasureCache != null) mMeasureCache.clear(); 19830 19831 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19832 mPrivateFlags |= PFLAG_INVALIDATED; 19833 } 19834 19835 /** 19836 * <p> 19837 * This is called to find out how big a view should be. The parent 19838 * supplies constraint information in the width and height parameters. 19839 * </p> 19840 * 19841 * <p> 19842 * The actual measurement work of a view is performed in 19843 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19844 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19845 * </p> 19846 * 19847 * 19848 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19849 * parent 19850 * @param heightMeasureSpec Vertical space requirements as imposed by the 19851 * parent 19852 * 19853 * @see #onMeasure(int, int) 19854 */ 19855 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19856 boolean optical = isLayoutModeOptical(this); 19857 if (optical != isLayoutModeOptical(mParent)) { 19858 Insets insets = getOpticalInsets(); 19859 int oWidth = insets.left + insets.right; 19860 int oHeight = insets.top + insets.bottom; 19861 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19862 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19863 } 19864 19865 // Suppress sign extension for the low bytes 19866 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19867 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19868 19869 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19870 19871 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19872 // already measured as the correct size. In API 23 and below, this 19873 // extra pass is required to make LinearLayout re-distribute weight. 19874 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19875 || heightMeasureSpec != mOldHeightMeasureSpec; 19876 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19877 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19878 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19879 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19880 final boolean needsLayout = specChanged 19881 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19882 19883 if (forceLayout || needsLayout) { 19884 // first clears the measured dimension flag 19885 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19886 19887 resolveRtlPropertiesIfNeeded(); 19888 19889 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19890 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19891 // measure ourselves, this should set the measured dimension flag back 19892 onMeasure(widthMeasureSpec, heightMeasureSpec); 19893 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19894 } else { 19895 long value = mMeasureCache.valueAt(cacheIndex); 19896 // Casting a long to int drops the high 32 bits, no mask needed 19897 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19898 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19899 } 19900 19901 // flag not set, setMeasuredDimension() was not invoked, we raise 19902 // an exception to warn the developer 19903 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19904 throw new IllegalStateException("View with id " + getId() + ": " 19905 + getClass().getName() + "#onMeasure() did not set the" 19906 + " measured dimension by calling" 19907 + " setMeasuredDimension()"); 19908 } 19909 19910 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19911 } 19912 19913 mOldWidthMeasureSpec = widthMeasureSpec; 19914 mOldHeightMeasureSpec = heightMeasureSpec; 19915 19916 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19917 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19918 } 19919 19920 /** 19921 * <p> 19922 * Measure the view and its content to determine the measured width and the 19923 * measured height. This method is invoked by {@link #measure(int, int)} and 19924 * should be overridden by subclasses to provide accurate and efficient 19925 * measurement of their contents. 19926 * </p> 19927 * 19928 * <p> 19929 * <strong>CONTRACT:</strong> When overriding this method, you 19930 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19931 * measured width and height of this view. Failure to do so will trigger an 19932 * <code>IllegalStateException</code>, thrown by 19933 * {@link #measure(int, int)}. Calling the superclass' 19934 * {@link #onMeasure(int, int)} is a valid use. 19935 * </p> 19936 * 19937 * <p> 19938 * The base class implementation of measure defaults to the background size, 19939 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19940 * override {@link #onMeasure(int, int)} to provide better measurements of 19941 * their content. 19942 * </p> 19943 * 19944 * <p> 19945 * If this method is overridden, it is the subclass's responsibility to make 19946 * sure the measured height and width are at least the view's minimum height 19947 * and width ({@link #getSuggestedMinimumHeight()} and 19948 * {@link #getSuggestedMinimumWidth()}). 19949 * </p> 19950 * 19951 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19952 * The requirements are encoded with 19953 * {@link android.view.View.MeasureSpec}. 19954 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19955 * The requirements are encoded with 19956 * {@link android.view.View.MeasureSpec}. 19957 * 19958 * @see #getMeasuredWidth() 19959 * @see #getMeasuredHeight() 19960 * @see #setMeasuredDimension(int, int) 19961 * @see #getSuggestedMinimumHeight() 19962 * @see #getSuggestedMinimumWidth() 19963 * @see android.view.View.MeasureSpec#getMode(int) 19964 * @see android.view.View.MeasureSpec#getSize(int) 19965 */ 19966 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19967 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19968 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19969 } 19970 19971 /** 19972 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19973 * measured width and measured height. Failing to do so will trigger an 19974 * exception at measurement time.</p> 19975 * 19976 * @param measuredWidth The measured width of this view. May be a complex 19977 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19978 * {@link #MEASURED_STATE_TOO_SMALL}. 19979 * @param measuredHeight The measured height of this view. May be a complex 19980 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19981 * {@link #MEASURED_STATE_TOO_SMALL}. 19982 */ 19983 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19984 boolean optical = isLayoutModeOptical(this); 19985 if (optical != isLayoutModeOptical(mParent)) { 19986 Insets insets = getOpticalInsets(); 19987 int opticalWidth = insets.left + insets.right; 19988 int opticalHeight = insets.top + insets.bottom; 19989 19990 measuredWidth += optical ? opticalWidth : -opticalWidth; 19991 measuredHeight += optical ? opticalHeight : -opticalHeight; 19992 } 19993 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19994 } 19995 19996 /** 19997 * Sets the measured dimension without extra processing for things like optical bounds. 19998 * Useful for reapplying consistent values that have already been cooked with adjustments 19999 * for optical bounds, etc. such as those from the measurement cache. 20000 * 20001 * @param measuredWidth The measured width of this view. May be a complex 20002 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20003 * {@link #MEASURED_STATE_TOO_SMALL}. 20004 * @param measuredHeight The measured height of this view. May be a complex 20005 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20006 * {@link #MEASURED_STATE_TOO_SMALL}. 20007 */ 20008 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 20009 mMeasuredWidth = measuredWidth; 20010 mMeasuredHeight = measuredHeight; 20011 20012 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 20013 } 20014 20015 /** 20016 * Merge two states as returned by {@link #getMeasuredState()}. 20017 * @param curState The current state as returned from a view or the result 20018 * of combining multiple views. 20019 * @param newState The new view state to combine. 20020 * @return Returns a new integer reflecting the combination of the two 20021 * states. 20022 */ 20023 public static int combineMeasuredStates(int curState, int newState) { 20024 return curState | newState; 20025 } 20026 20027 /** 20028 * Version of {@link #resolveSizeAndState(int, int, int)} 20029 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 20030 */ 20031 public static int resolveSize(int size, int measureSpec) { 20032 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 20033 } 20034 20035 /** 20036 * Utility to reconcile a desired size and state, with constraints imposed 20037 * by a MeasureSpec. Will take the desired size, unless a different size 20038 * is imposed by the constraints. The returned value is a compound integer, 20039 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 20040 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 20041 * resulting size is smaller than the size the view wants to be. 20042 * 20043 * @param size How big the view wants to be. 20044 * @param measureSpec Constraints imposed by the parent. 20045 * @param childMeasuredState Size information bit mask for the view's 20046 * children. 20047 * @return Size information bit mask as defined by 20048 * {@link #MEASURED_SIZE_MASK} and 20049 * {@link #MEASURED_STATE_TOO_SMALL}. 20050 */ 20051 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 20052 final int specMode = MeasureSpec.getMode(measureSpec); 20053 final int specSize = MeasureSpec.getSize(measureSpec); 20054 final int result; 20055 switch (specMode) { 20056 case MeasureSpec.AT_MOST: 20057 if (specSize < size) { 20058 result = specSize | MEASURED_STATE_TOO_SMALL; 20059 } else { 20060 result = size; 20061 } 20062 break; 20063 case MeasureSpec.EXACTLY: 20064 result = specSize; 20065 break; 20066 case MeasureSpec.UNSPECIFIED: 20067 default: 20068 result = size; 20069 } 20070 return result | (childMeasuredState & MEASURED_STATE_MASK); 20071 } 20072 20073 /** 20074 * Utility to return a default size. Uses the supplied size if the 20075 * MeasureSpec imposed no constraints. Will get larger if allowed 20076 * by the MeasureSpec. 20077 * 20078 * @param size Default size for this view 20079 * @param measureSpec Constraints imposed by the parent 20080 * @return The size this view should be. 20081 */ 20082 public static int getDefaultSize(int size, int measureSpec) { 20083 int result = size; 20084 int specMode = MeasureSpec.getMode(measureSpec); 20085 int specSize = MeasureSpec.getSize(measureSpec); 20086 20087 switch (specMode) { 20088 case MeasureSpec.UNSPECIFIED: 20089 result = size; 20090 break; 20091 case MeasureSpec.AT_MOST: 20092 case MeasureSpec.EXACTLY: 20093 result = specSize; 20094 break; 20095 } 20096 return result; 20097 } 20098 20099 /** 20100 * Returns the suggested minimum height that the view should use. This 20101 * returns the maximum of the view's minimum height 20102 * and the background's minimum height 20103 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 20104 * <p> 20105 * When being used in {@link #onMeasure(int, int)}, the caller should still 20106 * ensure the returned height is within the requirements of the parent. 20107 * 20108 * @return The suggested minimum height of the view. 20109 */ 20110 protected int getSuggestedMinimumHeight() { 20111 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 20112 20113 } 20114 20115 /** 20116 * Returns the suggested minimum width that the view should use. This 20117 * returns the maximum of the view's minimum width 20118 * and the background's minimum width 20119 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 20120 * <p> 20121 * When being used in {@link #onMeasure(int, int)}, the caller should still 20122 * ensure the returned width is within the requirements of the parent. 20123 * 20124 * @return The suggested minimum width of the view. 20125 */ 20126 protected int getSuggestedMinimumWidth() { 20127 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 20128 } 20129 20130 /** 20131 * Returns the minimum height of the view. 20132 * 20133 * @return the minimum height the view will try to be, in pixels 20134 * 20135 * @see #setMinimumHeight(int) 20136 * 20137 * @attr ref android.R.styleable#View_minHeight 20138 */ 20139 public int getMinimumHeight() { 20140 return mMinHeight; 20141 } 20142 20143 /** 20144 * Sets the minimum height of the view. It is not guaranteed the view will 20145 * be able to achieve this minimum height (for example, if its parent layout 20146 * constrains it with less available height). 20147 * 20148 * @param minHeight The minimum height the view will try to be, in pixels 20149 * 20150 * @see #getMinimumHeight() 20151 * 20152 * @attr ref android.R.styleable#View_minHeight 20153 */ 20154 @RemotableViewMethod 20155 public void setMinimumHeight(int minHeight) { 20156 mMinHeight = minHeight; 20157 requestLayout(); 20158 } 20159 20160 /** 20161 * Returns the minimum width of the view. 20162 * 20163 * @return the minimum width the view will try to be, in pixels 20164 * 20165 * @see #setMinimumWidth(int) 20166 * 20167 * @attr ref android.R.styleable#View_minWidth 20168 */ 20169 public int getMinimumWidth() { 20170 return mMinWidth; 20171 } 20172 20173 /** 20174 * Sets the minimum width of the view. It is not guaranteed the view will 20175 * be able to achieve this minimum width (for example, if its parent layout 20176 * constrains it with less available width). 20177 * 20178 * @param minWidth The minimum width the view will try to be, in pixels 20179 * 20180 * @see #getMinimumWidth() 20181 * 20182 * @attr ref android.R.styleable#View_minWidth 20183 */ 20184 public void setMinimumWidth(int minWidth) { 20185 mMinWidth = minWidth; 20186 requestLayout(); 20187 20188 } 20189 20190 /** 20191 * Get the animation currently associated with this view. 20192 * 20193 * @return The animation that is currently playing or 20194 * scheduled to play for this view. 20195 */ 20196 public Animation getAnimation() { 20197 return mCurrentAnimation; 20198 } 20199 20200 /** 20201 * Start the specified animation now. 20202 * 20203 * @param animation the animation to start now 20204 */ 20205 public void startAnimation(Animation animation) { 20206 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20207 setAnimation(animation); 20208 invalidateParentCaches(); 20209 invalidate(true); 20210 } 20211 20212 /** 20213 * Cancels any animations for this view. 20214 */ 20215 public void clearAnimation() { 20216 if (mCurrentAnimation != null) { 20217 mCurrentAnimation.detach(); 20218 } 20219 mCurrentAnimation = null; 20220 invalidateParentIfNeeded(); 20221 } 20222 20223 /** 20224 * Sets the next animation to play for this view. 20225 * If you want the animation to play immediately, use 20226 * {@link #startAnimation(android.view.animation.Animation)} instead. 20227 * This method provides allows fine-grained 20228 * control over the start time and invalidation, but you 20229 * must make sure that 1) the animation has a start time set, and 20230 * 2) the view's parent (which controls animations on its children) 20231 * will be invalidated when the animation is supposed to 20232 * start. 20233 * 20234 * @param animation The next animation, or null. 20235 */ 20236 public void setAnimation(Animation animation) { 20237 mCurrentAnimation = animation; 20238 20239 if (animation != null) { 20240 // If the screen is off assume the animation start time is now instead of 20241 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20242 // would cause the animation to start when the screen turns back on 20243 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20244 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20245 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20246 } 20247 animation.reset(); 20248 } 20249 } 20250 20251 /** 20252 * Invoked by a parent ViewGroup to notify the start of the animation 20253 * currently associated with this view. If you override this method, 20254 * always call super.onAnimationStart(); 20255 * 20256 * @see #setAnimation(android.view.animation.Animation) 20257 * @see #getAnimation() 20258 */ 20259 @CallSuper 20260 protected void onAnimationStart() { 20261 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20262 } 20263 20264 /** 20265 * Invoked by a parent ViewGroup to notify the end of the animation 20266 * currently associated with this view. If you override this method, 20267 * always call super.onAnimationEnd(); 20268 * 20269 * @see #setAnimation(android.view.animation.Animation) 20270 * @see #getAnimation() 20271 */ 20272 @CallSuper 20273 protected void onAnimationEnd() { 20274 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20275 } 20276 20277 /** 20278 * Invoked if there is a Transform that involves alpha. Subclass that can 20279 * draw themselves with the specified alpha should return true, and then 20280 * respect that alpha when their onDraw() is called. If this returns false 20281 * then the view may be redirected to draw into an offscreen buffer to 20282 * fulfill the request, which will look fine, but may be slower than if the 20283 * subclass handles it internally. The default implementation returns false. 20284 * 20285 * @param alpha The alpha (0..255) to apply to the view's drawing 20286 * @return true if the view can draw with the specified alpha. 20287 */ 20288 protected boolean onSetAlpha(int alpha) { 20289 return false; 20290 } 20291 20292 /** 20293 * This is used by the RootView to perform an optimization when 20294 * the view hierarchy contains one or several SurfaceView. 20295 * SurfaceView is always considered transparent, but its children are not, 20296 * therefore all View objects remove themselves from the global transparent 20297 * region (passed as a parameter to this function). 20298 * 20299 * @param region The transparent region for this ViewAncestor (window). 20300 * 20301 * @return Returns true if the effective visibility of the view at this 20302 * point is opaque, regardless of the transparent region; returns false 20303 * if it is possible for underlying windows to be seen behind the view. 20304 * 20305 * {@hide} 20306 */ 20307 public boolean gatherTransparentRegion(Region region) { 20308 final AttachInfo attachInfo = mAttachInfo; 20309 if (region != null && attachInfo != null) { 20310 final int pflags = mPrivateFlags; 20311 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20312 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20313 // remove it from the transparent region. 20314 final int[] location = attachInfo.mTransparentLocation; 20315 getLocationInWindow(location); 20316 // When a view has Z value, then it will be better to leave some area below the view 20317 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 20318 // the bottom part needs more offset than the left, top and right parts due to the 20319 // spot light effects. 20320 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 20321 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 20322 location[0] + mRight - mLeft + shadowOffset, 20323 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 20324 } else { 20325 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20326 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20327 // the background drawable's non-transparent parts from this transparent region. 20328 applyDrawableToTransparentRegion(mBackground, region); 20329 } 20330 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20331 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20332 // Similarly, we remove the foreground drawable's non-transparent parts. 20333 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20334 } 20335 } 20336 } 20337 return true; 20338 } 20339 20340 /** 20341 * Play a sound effect for this view. 20342 * 20343 * <p>The framework will play sound effects for some built in actions, such as 20344 * clicking, but you may wish to play these effects in your widget, 20345 * for instance, for internal navigation. 20346 * 20347 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20348 * {@link #isSoundEffectsEnabled()} is true. 20349 * 20350 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20351 */ 20352 public void playSoundEffect(int soundConstant) { 20353 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20354 return; 20355 } 20356 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20357 } 20358 20359 /** 20360 * BZZZTT!!1! 20361 * 20362 * <p>Provide haptic feedback to the user for this view. 20363 * 20364 * <p>The framework will provide haptic feedback for some built in actions, 20365 * such as long presses, but you may wish to provide feedback for your 20366 * own widget. 20367 * 20368 * <p>The feedback will only be performed if 20369 * {@link #isHapticFeedbackEnabled()} is true. 20370 * 20371 * @param feedbackConstant One of the constants defined in 20372 * {@link HapticFeedbackConstants} 20373 */ 20374 public boolean performHapticFeedback(int feedbackConstant) { 20375 return performHapticFeedback(feedbackConstant, 0); 20376 } 20377 20378 /** 20379 * BZZZTT!!1! 20380 * 20381 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20382 * 20383 * @param feedbackConstant One of the constants defined in 20384 * {@link HapticFeedbackConstants} 20385 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20386 */ 20387 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20388 if (mAttachInfo == null) { 20389 return false; 20390 } 20391 //noinspection SimplifiableIfStatement 20392 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20393 && !isHapticFeedbackEnabled()) { 20394 return false; 20395 } 20396 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20397 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20398 } 20399 20400 /** 20401 * Request that the visibility of the status bar or other screen/window 20402 * decorations be changed. 20403 * 20404 * <p>This method is used to put the over device UI into temporary modes 20405 * where the user's attention is focused more on the application content, 20406 * by dimming or hiding surrounding system affordances. This is typically 20407 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20408 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20409 * to be placed behind the action bar (and with these flags other system 20410 * affordances) so that smooth transitions between hiding and showing them 20411 * can be done. 20412 * 20413 * <p>Two representative examples of the use of system UI visibility is 20414 * implementing a content browsing application (like a magazine reader) 20415 * and a video playing application. 20416 * 20417 * <p>The first code shows a typical implementation of a View in a content 20418 * browsing application. In this implementation, the application goes 20419 * into a content-oriented mode by hiding the status bar and action bar, 20420 * and putting the navigation elements into lights out mode. The user can 20421 * then interact with content while in this mode. Such an application should 20422 * provide an easy way for the user to toggle out of the mode (such as to 20423 * check information in the status bar or access notifications). In the 20424 * implementation here, this is done simply by tapping on the content. 20425 * 20426 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20427 * content} 20428 * 20429 * <p>This second code sample shows a typical implementation of a View 20430 * in a video playing application. In this situation, while the video is 20431 * playing the application would like to go into a complete full-screen mode, 20432 * to use as much of the display as possible for the video. When in this state 20433 * the user can not interact with the application; the system intercepts 20434 * touching on the screen to pop the UI out of full screen mode. See 20435 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20436 * 20437 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20438 * content} 20439 * 20440 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20441 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20442 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20443 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20444 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20445 */ 20446 public void setSystemUiVisibility(int visibility) { 20447 if (visibility != mSystemUiVisibility) { 20448 mSystemUiVisibility = visibility; 20449 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20450 mParent.recomputeViewAttributes(this); 20451 } 20452 } 20453 } 20454 20455 /** 20456 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20457 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20458 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20459 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20460 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20461 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20462 */ 20463 public int getSystemUiVisibility() { 20464 return mSystemUiVisibility; 20465 } 20466 20467 /** 20468 * Returns the current system UI visibility that is currently set for 20469 * the entire window. This is the combination of the 20470 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20471 * views in the window. 20472 */ 20473 public int getWindowSystemUiVisibility() { 20474 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20475 } 20476 20477 /** 20478 * Override to find out when the window's requested system UI visibility 20479 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20480 * This is different from the callbacks received through 20481 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20482 * in that this is only telling you about the local request of the window, 20483 * not the actual values applied by the system. 20484 */ 20485 public void onWindowSystemUiVisibilityChanged(int visible) { 20486 } 20487 20488 /** 20489 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20490 * the view hierarchy. 20491 */ 20492 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20493 onWindowSystemUiVisibilityChanged(visible); 20494 } 20495 20496 /** 20497 * Set a listener to receive callbacks when the visibility of the system bar changes. 20498 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20499 */ 20500 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20501 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20502 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20503 mParent.recomputeViewAttributes(this); 20504 } 20505 } 20506 20507 /** 20508 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20509 * the view hierarchy. 20510 */ 20511 public void dispatchSystemUiVisibilityChanged(int visibility) { 20512 ListenerInfo li = mListenerInfo; 20513 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20514 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20515 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20516 } 20517 } 20518 20519 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20520 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20521 if (val != mSystemUiVisibility) { 20522 setSystemUiVisibility(val); 20523 return true; 20524 } 20525 return false; 20526 } 20527 20528 /** @hide */ 20529 public void setDisabledSystemUiVisibility(int flags) { 20530 if (mAttachInfo != null) { 20531 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20532 mAttachInfo.mDisabledSystemUiVisibility = flags; 20533 if (mParent != null) { 20534 mParent.recomputeViewAttributes(this); 20535 } 20536 } 20537 } 20538 } 20539 20540 /** 20541 * Creates an image that the system displays during the drag and drop 20542 * operation. This is called a "drag shadow". The default implementation 20543 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20544 * appearance as the given View. The default also positions the center of the drag shadow 20545 * directly under the touch point. If no View is provided (the constructor with no parameters 20546 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20547 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20548 * default is an invisible drag shadow. 20549 * <p> 20550 * You are not required to use the View you provide to the constructor as the basis of the 20551 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20552 * anything you want as the drag shadow. 20553 * </p> 20554 * <p> 20555 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20556 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20557 * size and position of the drag shadow. It uses this data to construct a 20558 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20559 * so that your application can draw the shadow image in the Canvas. 20560 * </p> 20561 * 20562 * <div class="special reference"> 20563 * <h3>Developer Guides</h3> 20564 * <p>For a guide to implementing drag and drop features, read the 20565 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20566 * </div> 20567 */ 20568 public static class DragShadowBuilder { 20569 private final WeakReference<View> mView; 20570 20571 /** 20572 * Constructs a shadow image builder based on a View. By default, the resulting drag 20573 * shadow will have the same appearance and dimensions as the View, with the touch point 20574 * over the center of the View. 20575 * @param view A View. Any View in scope can be used. 20576 */ 20577 public DragShadowBuilder(View view) { 20578 mView = new WeakReference<View>(view); 20579 } 20580 20581 /** 20582 * Construct a shadow builder object with no associated View. This 20583 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20584 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20585 * to supply the drag shadow's dimensions and appearance without 20586 * reference to any View object. If they are not overridden, then the result is an 20587 * invisible drag shadow. 20588 */ 20589 public DragShadowBuilder() { 20590 mView = new WeakReference<View>(null); 20591 } 20592 20593 /** 20594 * Returns the View object that had been passed to the 20595 * {@link #View.DragShadowBuilder(View)} 20596 * constructor. If that View parameter was {@code null} or if the 20597 * {@link #View.DragShadowBuilder()} 20598 * constructor was used to instantiate the builder object, this method will return 20599 * null. 20600 * 20601 * @return The View object associate with this builder object. 20602 */ 20603 @SuppressWarnings({"JavadocReference"}) 20604 final public View getView() { 20605 return mView.get(); 20606 } 20607 20608 /** 20609 * Provides the metrics for the shadow image. These include the dimensions of 20610 * the shadow image, and the point within that shadow that should 20611 * be centered under the touch location while dragging. 20612 * <p> 20613 * The default implementation sets the dimensions of the shadow to be the 20614 * same as the dimensions of the View itself and centers the shadow under 20615 * the touch point. 20616 * </p> 20617 * 20618 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20619 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20620 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20621 * image. 20622 * 20623 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20624 * shadow image that should be underneath the touch point during the drag and drop 20625 * operation. Your application must set {@link android.graphics.Point#x} to the 20626 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20627 */ 20628 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20629 final View view = mView.get(); 20630 if (view != null) { 20631 outShadowSize.set(view.getWidth(), view.getHeight()); 20632 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20633 } else { 20634 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20635 } 20636 } 20637 20638 /** 20639 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20640 * based on the dimensions it received from the 20641 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20642 * 20643 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20644 */ 20645 public void onDrawShadow(Canvas canvas) { 20646 final View view = mView.get(); 20647 if (view != null) { 20648 view.draw(canvas); 20649 } else { 20650 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20651 } 20652 } 20653 } 20654 20655 /** 20656 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20657 * startDragAndDrop()} for newer platform versions. 20658 */ 20659 @Deprecated 20660 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20661 Object myLocalState, int flags) { 20662 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20663 } 20664 20665 /** 20666 * Starts a drag and drop operation. When your application calls this method, it passes a 20667 * {@link android.view.View.DragShadowBuilder} object to the system. The 20668 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20669 * to get metrics for the drag shadow, and then calls the object's 20670 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20671 * <p> 20672 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20673 * drag events to all the View objects in your application that are currently visible. It does 20674 * this either by calling the View object's drag listener (an implementation of 20675 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20676 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20677 * Both are passed a {@link android.view.DragEvent} object that has a 20678 * {@link android.view.DragEvent#getAction()} value of 20679 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20680 * </p> 20681 * <p> 20682 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20683 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20684 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20685 * to the View the user selected for dragging. 20686 * </p> 20687 * @param data A {@link android.content.ClipData} object pointing to the data to be 20688 * transferred by the drag and drop operation. 20689 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20690 * drag shadow. 20691 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20692 * drop operation. When dispatching drag events to views in the same activity this object 20693 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 20694 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 20695 * will return null). 20696 * <p> 20697 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20698 * to the target Views. For example, it can contain flags that differentiate between a 20699 * a copy operation and a move operation. 20700 * </p> 20701 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 20702 * flags, or any combination of the following: 20703 * <ul> 20704 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 20705 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 20706 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 20707 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 20708 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 20709 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 20710 * </ul> 20711 * @return {@code true} if the method completes successfully, or 20712 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20713 * do a drag, and so no drag operation is in progress. 20714 */ 20715 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20716 Object myLocalState, int flags) { 20717 if (ViewDebug.DEBUG_DRAG) { 20718 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20719 } 20720 if (mAttachInfo == null) { 20721 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 20722 return false; 20723 } 20724 20725 if (data != null) { 20726 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 20727 } 20728 20729 boolean okay = false; 20730 20731 Point shadowSize = new Point(); 20732 Point shadowTouchPoint = new Point(); 20733 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20734 20735 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20736 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20737 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20738 } 20739 20740 if (ViewDebug.DEBUG_DRAG) { 20741 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20742 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20743 } 20744 if (mAttachInfo.mDragSurface != null) { 20745 mAttachInfo.mDragSurface.release(); 20746 } 20747 mAttachInfo.mDragSurface = new Surface(); 20748 try { 20749 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20750 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20751 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20752 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20753 if (mAttachInfo.mDragToken != null) { 20754 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20755 try { 20756 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20757 shadowBuilder.onDrawShadow(canvas); 20758 } finally { 20759 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20760 } 20761 20762 final ViewRootImpl root = getViewRootImpl(); 20763 20764 // Cache the local state object for delivery with DragEvents 20765 root.setLocalDragState(myLocalState); 20766 20767 // repurpose 'shadowSize' for the last touch point 20768 root.getLastTouchPoint(shadowSize); 20769 20770 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20771 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20772 shadowTouchPoint.x, shadowTouchPoint.y, data); 20773 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20774 } 20775 } catch (Exception e) { 20776 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20777 mAttachInfo.mDragSurface.destroy(); 20778 mAttachInfo.mDragSurface = null; 20779 } 20780 20781 return okay; 20782 } 20783 20784 /** 20785 * Cancels an ongoing drag and drop operation. 20786 * <p> 20787 * A {@link android.view.DragEvent} object with 20788 * {@link android.view.DragEvent#getAction()} value of 20789 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20790 * {@link android.view.DragEvent#getResult()} value of {@code false} 20791 * will be sent to every 20792 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20793 * even if they are not currently visible. 20794 * </p> 20795 * <p> 20796 * This method can be called on any View in the same window as the View on which 20797 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20798 * was called. 20799 * </p> 20800 */ 20801 public final void cancelDragAndDrop() { 20802 if (ViewDebug.DEBUG_DRAG) { 20803 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20804 } 20805 if (mAttachInfo == null) { 20806 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 20807 return; 20808 } 20809 if (mAttachInfo.mDragToken != null) { 20810 try { 20811 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20812 } catch (Exception e) { 20813 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20814 } 20815 mAttachInfo.mDragToken = null; 20816 } else { 20817 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20818 } 20819 } 20820 20821 /** 20822 * Updates the drag shadow for the ongoing drag and drop operation. 20823 * 20824 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20825 * new drag shadow. 20826 */ 20827 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20828 if (ViewDebug.DEBUG_DRAG) { 20829 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20830 } 20831 if (mAttachInfo == null) { 20832 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 20833 return; 20834 } 20835 if (mAttachInfo.mDragToken != null) { 20836 try { 20837 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20838 try { 20839 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20840 shadowBuilder.onDrawShadow(canvas); 20841 } finally { 20842 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20843 } 20844 } catch (Exception e) { 20845 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20846 } 20847 } else { 20848 Log.e(VIEW_LOG_TAG, "No active drag"); 20849 } 20850 } 20851 20852 /** 20853 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20854 * between {startX, startY} and the new cursor positon. 20855 * @param startX horizontal coordinate where the move started. 20856 * @param startY vertical coordinate where the move started. 20857 * @return whether moving was started successfully. 20858 * @hide 20859 */ 20860 public final boolean startMovingTask(float startX, float startY) { 20861 if (ViewDebug.DEBUG_POSITIONING) { 20862 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20863 } 20864 try { 20865 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20866 } catch (RemoteException e) { 20867 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20868 } 20869 return false; 20870 } 20871 20872 /** 20873 * Handles drag events sent by the system following a call to 20874 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20875 * startDragAndDrop()}. 20876 *<p> 20877 * When the system calls this method, it passes a 20878 * {@link android.view.DragEvent} object. A call to 20879 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20880 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20881 * operation. 20882 * @param event The {@link android.view.DragEvent} sent by the system. 20883 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20884 * in DragEvent, indicating the type of drag event represented by this object. 20885 * @return {@code true} if the method was successful, otherwise {@code false}. 20886 * <p> 20887 * The method should return {@code true} in response to an action type of 20888 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20889 * operation. 20890 * </p> 20891 * <p> 20892 * The method should also return {@code true} in response to an action type of 20893 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20894 * {@code false} if it didn't. 20895 * </p> 20896 * <p> 20897 * For all other events, the return value is ignored. 20898 * </p> 20899 */ 20900 public boolean onDragEvent(DragEvent event) { 20901 return false; 20902 } 20903 20904 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 20905 boolean dispatchDragEnterExitInPreN(DragEvent event) { 20906 return callDragEventHandler(event); 20907 } 20908 20909 /** 20910 * Detects if this View is enabled and has a drag event listener. 20911 * If both are true, then it calls the drag event listener with the 20912 * {@link android.view.DragEvent} it received. If the drag event listener returns 20913 * {@code true}, then dispatchDragEvent() returns {@code true}. 20914 * <p> 20915 * For all other cases, the method calls the 20916 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20917 * method and returns its result. 20918 * </p> 20919 * <p> 20920 * This ensures that a drag event is always consumed, even if the View does not have a drag 20921 * event listener. However, if the View has a listener and the listener returns true, then 20922 * onDragEvent() is not called. 20923 * </p> 20924 */ 20925 public boolean dispatchDragEvent(DragEvent event) { 20926 event.mEventHandlerWasCalled = true; 20927 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 20928 event.mAction == DragEvent.ACTION_DROP) { 20929 // About to deliver an event with coordinates to this view. Notify that now this view 20930 // has drag focus. This will send exit/enter events as needed. 20931 getViewRootImpl().setDragFocus(this, event); 20932 } 20933 return callDragEventHandler(event); 20934 } 20935 20936 final boolean callDragEventHandler(DragEvent event) { 20937 final boolean result; 20938 20939 ListenerInfo li = mListenerInfo; 20940 //noinspection SimplifiableIfStatement 20941 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20942 && li.mOnDragListener.onDrag(this, event)) { 20943 result = true; 20944 } else { 20945 result = onDragEvent(event); 20946 } 20947 20948 switch (event.mAction) { 20949 case DragEvent.ACTION_DRAG_ENTERED: { 20950 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 20951 refreshDrawableState(); 20952 } break; 20953 case DragEvent.ACTION_DRAG_EXITED: { 20954 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 20955 refreshDrawableState(); 20956 } break; 20957 case DragEvent.ACTION_DRAG_ENDED: { 20958 mPrivateFlags2 &= ~View.DRAG_MASK; 20959 refreshDrawableState(); 20960 } break; 20961 } 20962 20963 return result; 20964 } 20965 20966 boolean canAcceptDrag() { 20967 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20968 } 20969 20970 /** 20971 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20972 * it is ever exposed at all. 20973 * @hide 20974 */ 20975 public void onCloseSystemDialogs(String reason) { 20976 } 20977 20978 /** 20979 * Given a Drawable whose bounds have been set to draw into this view, 20980 * update a Region being computed for 20981 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20982 * that any non-transparent parts of the Drawable are removed from the 20983 * given transparent region. 20984 * 20985 * @param dr The Drawable whose transparency is to be applied to the region. 20986 * @param region A Region holding the current transparency information, 20987 * where any parts of the region that are set are considered to be 20988 * transparent. On return, this region will be modified to have the 20989 * transparency information reduced by the corresponding parts of the 20990 * Drawable that are not transparent. 20991 * {@hide} 20992 */ 20993 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20994 if (DBG) { 20995 Log.i("View", "Getting transparent region for: " + this); 20996 } 20997 final Region r = dr.getTransparentRegion(); 20998 final Rect db = dr.getBounds(); 20999 final AttachInfo attachInfo = mAttachInfo; 21000 if (r != null && attachInfo != null) { 21001 final int w = getRight()-getLeft(); 21002 final int h = getBottom()-getTop(); 21003 if (db.left > 0) { 21004 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 21005 r.op(0, 0, db.left, h, Region.Op.UNION); 21006 } 21007 if (db.right < w) { 21008 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 21009 r.op(db.right, 0, w, h, Region.Op.UNION); 21010 } 21011 if (db.top > 0) { 21012 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 21013 r.op(0, 0, w, db.top, Region.Op.UNION); 21014 } 21015 if (db.bottom < h) { 21016 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 21017 r.op(0, db.bottom, w, h, Region.Op.UNION); 21018 } 21019 final int[] location = attachInfo.mTransparentLocation; 21020 getLocationInWindow(location); 21021 r.translate(location[0], location[1]); 21022 region.op(r, Region.Op.INTERSECT); 21023 } else { 21024 region.op(db, Region.Op.DIFFERENCE); 21025 } 21026 } 21027 21028 private void checkForLongClick(int delayOffset, float x, float y) { 21029 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 21030 mHasPerformedLongPress = false; 21031 21032 if (mPendingCheckForLongPress == null) { 21033 mPendingCheckForLongPress = new CheckForLongPress(); 21034 } 21035 mPendingCheckForLongPress.setAnchor(x, y); 21036 mPendingCheckForLongPress.rememberWindowAttachCount(); 21037 postDelayed(mPendingCheckForLongPress, 21038 ViewConfiguration.getLongPressTimeout() - delayOffset); 21039 } 21040 } 21041 21042 /** 21043 * Inflate a view from an XML resource. This convenience method wraps the {@link 21044 * LayoutInflater} class, which provides a full range of options for view inflation. 21045 * 21046 * @param context The Context object for your activity or application. 21047 * @param resource The resource ID to inflate 21048 * @param root A view group that will be the parent. Used to properly inflate the 21049 * layout_* parameters. 21050 * @see LayoutInflater 21051 */ 21052 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 21053 LayoutInflater factory = LayoutInflater.from(context); 21054 return factory.inflate(resource, root); 21055 } 21056 21057 /** 21058 * Scroll the view with standard behavior for scrolling beyond the normal 21059 * content boundaries. Views that call this method should override 21060 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 21061 * results of an over-scroll operation. 21062 * 21063 * Views can use this method to handle any touch or fling-based scrolling. 21064 * 21065 * @param deltaX Change in X in pixels 21066 * @param deltaY Change in Y in pixels 21067 * @param scrollX Current X scroll value in pixels before applying deltaX 21068 * @param scrollY Current Y scroll value in pixels before applying deltaY 21069 * @param scrollRangeX Maximum content scroll range along the X axis 21070 * @param scrollRangeY Maximum content scroll range along the Y axis 21071 * @param maxOverScrollX Number of pixels to overscroll by in either direction 21072 * along the X axis. 21073 * @param maxOverScrollY Number of pixels to overscroll by in either direction 21074 * along the Y axis. 21075 * @param isTouchEvent true if this scroll operation is the result of a touch event. 21076 * @return true if scrolling was clamped to an over-scroll boundary along either 21077 * axis, false otherwise. 21078 */ 21079 @SuppressWarnings({"UnusedParameters"}) 21080 protected boolean overScrollBy(int deltaX, int deltaY, 21081 int scrollX, int scrollY, 21082 int scrollRangeX, int scrollRangeY, 21083 int maxOverScrollX, int maxOverScrollY, 21084 boolean isTouchEvent) { 21085 final int overScrollMode = mOverScrollMode; 21086 final boolean canScrollHorizontal = 21087 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 21088 final boolean canScrollVertical = 21089 computeVerticalScrollRange() > computeVerticalScrollExtent(); 21090 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 21091 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 21092 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 21093 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 21094 21095 int newScrollX = scrollX + deltaX; 21096 if (!overScrollHorizontal) { 21097 maxOverScrollX = 0; 21098 } 21099 21100 int newScrollY = scrollY + deltaY; 21101 if (!overScrollVertical) { 21102 maxOverScrollY = 0; 21103 } 21104 21105 // Clamp values if at the limits and record 21106 final int left = -maxOverScrollX; 21107 final int right = maxOverScrollX + scrollRangeX; 21108 final int top = -maxOverScrollY; 21109 final int bottom = maxOverScrollY + scrollRangeY; 21110 21111 boolean clampedX = false; 21112 if (newScrollX > right) { 21113 newScrollX = right; 21114 clampedX = true; 21115 } else if (newScrollX < left) { 21116 newScrollX = left; 21117 clampedX = true; 21118 } 21119 21120 boolean clampedY = false; 21121 if (newScrollY > bottom) { 21122 newScrollY = bottom; 21123 clampedY = true; 21124 } else if (newScrollY < top) { 21125 newScrollY = top; 21126 clampedY = true; 21127 } 21128 21129 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 21130 21131 return clampedX || clampedY; 21132 } 21133 21134 /** 21135 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 21136 * respond to the results of an over-scroll operation. 21137 * 21138 * @param scrollX New X scroll value in pixels 21139 * @param scrollY New Y scroll value in pixels 21140 * @param clampedX True if scrollX was clamped to an over-scroll boundary 21141 * @param clampedY True if scrollY was clamped to an over-scroll boundary 21142 */ 21143 protected void onOverScrolled(int scrollX, int scrollY, 21144 boolean clampedX, boolean clampedY) { 21145 // Intentionally empty. 21146 } 21147 21148 /** 21149 * Returns the over-scroll mode for this view. The result will be 21150 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21151 * (allow over-scrolling only if the view content is larger than the container), 21152 * or {@link #OVER_SCROLL_NEVER}. 21153 * 21154 * @return This view's over-scroll mode. 21155 */ 21156 public int getOverScrollMode() { 21157 return mOverScrollMode; 21158 } 21159 21160 /** 21161 * Set the over-scroll mode for this view. Valid over-scroll modes are 21162 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21163 * (allow over-scrolling only if the view content is larger than the container), 21164 * or {@link #OVER_SCROLL_NEVER}. 21165 * 21166 * Setting the over-scroll mode of a view will have an effect only if the 21167 * view is capable of scrolling. 21168 * 21169 * @param overScrollMode The new over-scroll mode for this view. 21170 */ 21171 public void setOverScrollMode(int overScrollMode) { 21172 if (overScrollMode != OVER_SCROLL_ALWAYS && 21173 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 21174 overScrollMode != OVER_SCROLL_NEVER) { 21175 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 21176 } 21177 mOverScrollMode = overScrollMode; 21178 } 21179 21180 /** 21181 * Enable or disable nested scrolling for this view. 21182 * 21183 * <p>If this property is set to true the view will be permitted to initiate nested 21184 * scrolling operations with a compatible parent view in the current hierarchy. If this 21185 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 21186 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 21187 * the nested scroll.</p> 21188 * 21189 * @param enabled true to enable nested scrolling, false to disable 21190 * 21191 * @see #isNestedScrollingEnabled() 21192 */ 21193 public void setNestedScrollingEnabled(boolean enabled) { 21194 if (enabled) { 21195 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 21196 } else { 21197 stopNestedScroll(); 21198 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 21199 } 21200 } 21201 21202 /** 21203 * Returns true if nested scrolling is enabled for this view. 21204 * 21205 * <p>If nested scrolling is enabled and this View class implementation supports it, 21206 * this view will act as a nested scrolling child view when applicable, forwarding data 21207 * about the scroll operation in progress to a compatible and cooperating nested scrolling 21208 * parent.</p> 21209 * 21210 * @return true if nested scrolling is enabled 21211 * 21212 * @see #setNestedScrollingEnabled(boolean) 21213 */ 21214 public boolean isNestedScrollingEnabled() { 21215 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 21216 PFLAG3_NESTED_SCROLLING_ENABLED; 21217 } 21218 21219 /** 21220 * Begin a nestable scroll operation along the given axes. 21221 * 21222 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 21223 * 21224 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 21225 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 21226 * In the case of touch scrolling the nested scroll will be terminated automatically in 21227 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 21228 * In the event of programmatic scrolling the caller must explicitly call 21229 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 21230 * 21231 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21232 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21233 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21234 * 21235 * <p>At each incremental step of the scroll the caller should invoke 21236 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21237 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21238 * parent at least partially consumed the scroll and the caller should adjust the amount it 21239 * scrolls by.</p> 21240 * 21241 * <p>After applying the remainder of the scroll delta the caller should invoke 21242 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21243 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21244 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21245 * </p> 21246 * 21247 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21248 * {@link #SCROLL_AXIS_VERTICAL}. 21249 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21250 * the current gesture. 21251 * 21252 * @see #stopNestedScroll() 21253 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21254 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21255 */ 21256 public boolean startNestedScroll(int axes) { 21257 if (hasNestedScrollingParent()) { 21258 // Already in progress 21259 return true; 21260 } 21261 if (isNestedScrollingEnabled()) { 21262 ViewParent p = getParent(); 21263 View child = this; 21264 while (p != null) { 21265 try { 21266 if (p.onStartNestedScroll(child, this, axes)) { 21267 mNestedScrollingParent = p; 21268 p.onNestedScrollAccepted(child, this, axes); 21269 return true; 21270 } 21271 } catch (AbstractMethodError e) { 21272 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21273 "method onStartNestedScroll", e); 21274 // Allow the search upward to continue 21275 } 21276 if (p instanceof View) { 21277 child = (View) p; 21278 } 21279 p = p.getParent(); 21280 } 21281 } 21282 return false; 21283 } 21284 21285 /** 21286 * Stop a nested scroll in progress. 21287 * 21288 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21289 * 21290 * @see #startNestedScroll(int) 21291 */ 21292 public void stopNestedScroll() { 21293 if (mNestedScrollingParent != null) { 21294 mNestedScrollingParent.onStopNestedScroll(this); 21295 mNestedScrollingParent = null; 21296 } 21297 } 21298 21299 /** 21300 * Returns true if this view has a nested scrolling parent. 21301 * 21302 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21303 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21304 * 21305 * @return whether this view has a nested scrolling parent 21306 */ 21307 public boolean hasNestedScrollingParent() { 21308 return mNestedScrollingParent != null; 21309 } 21310 21311 /** 21312 * Dispatch one step of a nested scroll in progress. 21313 * 21314 * <p>Implementations of views that support nested scrolling should call this to report 21315 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21316 * is not currently in progress or nested scrolling is not 21317 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21318 * 21319 * <p>Compatible View implementations should also call 21320 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21321 * consuming a component of the scroll event themselves.</p> 21322 * 21323 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21324 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21325 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21326 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21327 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21328 * in local view coordinates of this view from before this operation 21329 * to after it completes. View implementations may use this to adjust 21330 * expected input coordinate tracking. 21331 * @return true if the event was dispatched, false if it could not be dispatched. 21332 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21333 */ 21334 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21335 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21336 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21337 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21338 int startX = 0; 21339 int startY = 0; 21340 if (offsetInWindow != null) { 21341 getLocationInWindow(offsetInWindow); 21342 startX = offsetInWindow[0]; 21343 startY = offsetInWindow[1]; 21344 } 21345 21346 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21347 dxUnconsumed, dyUnconsumed); 21348 21349 if (offsetInWindow != null) { 21350 getLocationInWindow(offsetInWindow); 21351 offsetInWindow[0] -= startX; 21352 offsetInWindow[1] -= startY; 21353 } 21354 return true; 21355 } else if (offsetInWindow != null) { 21356 // No motion, no dispatch. Keep offsetInWindow up to date. 21357 offsetInWindow[0] = 0; 21358 offsetInWindow[1] = 0; 21359 } 21360 } 21361 return false; 21362 } 21363 21364 /** 21365 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21366 * 21367 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21368 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21369 * scrolling operation to consume some or all of the scroll operation before the child view 21370 * consumes it.</p> 21371 * 21372 * @param dx Horizontal scroll distance in pixels 21373 * @param dy Vertical scroll distance in pixels 21374 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21375 * and consumed[1] the consumed dy. 21376 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21377 * in local view coordinates of this view from before this operation 21378 * to after it completes. View implementations may use this to adjust 21379 * expected input coordinate tracking. 21380 * @return true if the parent consumed some or all of the scroll delta 21381 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21382 */ 21383 public boolean dispatchNestedPreScroll(int dx, int dy, 21384 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21385 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21386 if (dx != 0 || dy != 0) { 21387 int startX = 0; 21388 int startY = 0; 21389 if (offsetInWindow != null) { 21390 getLocationInWindow(offsetInWindow); 21391 startX = offsetInWindow[0]; 21392 startY = offsetInWindow[1]; 21393 } 21394 21395 if (consumed == null) { 21396 if (mTempNestedScrollConsumed == null) { 21397 mTempNestedScrollConsumed = new int[2]; 21398 } 21399 consumed = mTempNestedScrollConsumed; 21400 } 21401 consumed[0] = 0; 21402 consumed[1] = 0; 21403 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21404 21405 if (offsetInWindow != null) { 21406 getLocationInWindow(offsetInWindow); 21407 offsetInWindow[0] -= startX; 21408 offsetInWindow[1] -= startY; 21409 } 21410 return consumed[0] != 0 || consumed[1] != 0; 21411 } else if (offsetInWindow != null) { 21412 offsetInWindow[0] = 0; 21413 offsetInWindow[1] = 0; 21414 } 21415 } 21416 return false; 21417 } 21418 21419 /** 21420 * Dispatch a fling to a nested scrolling parent. 21421 * 21422 * <p>This method should be used to indicate that a nested scrolling child has detected 21423 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21424 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21425 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21426 * along a scrollable axis.</p> 21427 * 21428 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21429 * its own content, it can use this method to delegate the fling to its nested scrolling 21430 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21431 * 21432 * @param velocityX Horizontal fling velocity in pixels per second 21433 * @param velocityY Vertical fling velocity in pixels per second 21434 * @param consumed true if the child consumed the fling, false otherwise 21435 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21436 */ 21437 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21438 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21439 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21440 } 21441 return false; 21442 } 21443 21444 /** 21445 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21446 * 21447 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21448 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21449 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21450 * before the child view consumes it. If this method returns <code>true</code>, a nested 21451 * parent view consumed the fling and this view should not scroll as a result.</p> 21452 * 21453 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21454 * the fling at a time. If a parent view consumed the fling this method will return false. 21455 * Custom view implementations should account for this in two ways:</p> 21456 * 21457 * <ul> 21458 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21459 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21460 * position regardless.</li> 21461 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21462 * even to settle back to a valid idle position.</li> 21463 * </ul> 21464 * 21465 * <p>Views should also not offer fling velocities to nested parent views along an axis 21466 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21467 * should not offer a horizontal fling velocity to its parents since scrolling along that 21468 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21469 * 21470 * @param velocityX Horizontal fling velocity in pixels per second 21471 * @param velocityY Vertical fling velocity in pixels per second 21472 * @return true if a nested scrolling parent consumed the fling 21473 */ 21474 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21475 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21476 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21477 } 21478 return false; 21479 } 21480 21481 /** 21482 * Gets a scale factor that determines the distance the view should scroll 21483 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21484 * @return The vertical scroll scale factor. 21485 * @hide 21486 */ 21487 protected float getVerticalScrollFactor() { 21488 if (mVerticalScrollFactor == 0) { 21489 TypedValue outValue = new TypedValue(); 21490 if (!mContext.getTheme().resolveAttribute( 21491 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21492 throw new IllegalStateException( 21493 "Expected theme to define listPreferredItemHeight."); 21494 } 21495 mVerticalScrollFactor = outValue.getDimension( 21496 mContext.getResources().getDisplayMetrics()); 21497 } 21498 return mVerticalScrollFactor; 21499 } 21500 21501 /** 21502 * Gets a scale factor that determines the distance the view should scroll 21503 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21504 * @return The horizontal scroll scale factor. 21505 * @hide 21506 */ 21507 protected float getHorizontalScrollFactor() { 21508 // TODO: Should use something else. 21509 return getVerticalScrollFactor(); 21510 } 21511 21512 /** 21513 * Return the value specifying the text direction or policy that was set with 21514 * {@link #setTextDirection(int)}. 21515 * 21516 * @return the defined text direction. It can be one of: 21517 * 21518 * {@link #TEXT_DIRECTION_INHERIT}, 21519 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21520 * {@link #TEXT_DIRECTION_ANY_RTL}, 21521 * {@link #TEXT_DIRECTION_LTR}, 21522 * {@link #TEXT_DIRECTION_RTL}, 21523 * {@link #TEXT_DIRECTION_LOCALE}, 21524 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21525 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21526 * 21527 * @attr ref android.R.styleable#View_textDirection 21528 * 21529 * @hide 21530 */ 21531 @ViewDebug.ExportedProperty(category = "text", mapping = { 21532 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21533 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21534 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21535 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21536 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21537 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21538 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21539 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21540 }) 21541 public int getRawTextDirection() { 21542 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21543 } 21544 21545 /** 21546 * Set the text direction. 21547 * 21548 * @param textDirection the direction to set. Should be one of: 21549 * 21550 * {@link #TEXT_DIRECTION_INHERIT}, 21551 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21552 * {@link #TEXT_DIRECTION_ANY_RTL}, 21553 * {@link #TEXT_DIRECTION_LTR}, 21554 * {@link #TEXT_DIRECTION_RTL}, 21555 * {@link #TEXT_DIRECTION_LOCALE} 21556 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21557 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21558 * 21559 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21560 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21561 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21562 * 21563 * @attr ref android.R.styleable#View_textDirection 21564 */ 21565 public void setTextDirection(int textDirection) { 21566 if (getRawTextDirection() != textDirection) { 21567 // Reset the current text direction and the resolved one 21568 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21569 resetResolvedTextDirection(); 21570 // Set the new text direction 21571 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21572 // Do resolution 21573 resolveTextDirection(); 21574 // Notify change 21575 onRtlPropertiesChanged(getLayoutDirection()); 21576 // Refresh 21577 requestLayout(); 21578 invalidate(true); 21579 } 21580 } 21581 21582 /** 21583 * Return the resolved text direction. 21584 * 21585 * @return the resolved text direction. Returns one of: 21586 * 21587 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21588 * {@link #TEXT_DIRECTION_ANY_RTL}, 21589 * {@link #TEXT_DIRECTION_LTR}, 21590 * {@link #TEXT_DIRECTION_RTL}, 21591 * {@link #TEXT_DIRECTION_LOCALE}, 21592 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21593 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21594 * 21595 * @attr ref android.R.styleable#View_textDirection 21596 */ 21597 @ViewDebug.ExportedProperty(category = "text", mapping = { 21598 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21599 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21600 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21601 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21602 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21603 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21604 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21605 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21606 }) 21607 public int getTextDirection() { 21608 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21609 } 21610 21611 /** 21612 * Resolve the text direction. 21613 * 21614 * @return true if resolution has been done, false otherwise. 21615 * 21616 * @hide 21617 */ 21618 public boolean resolveTextDirection() { 21619 // Reset any previous text direction resolution 21620 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21621 21622 if (hasRtlSupport()) { 21623 // Set resolved text direction flag depending on text direction flag 21624 final int textDirection = getRawTextDirection(); 21625 switch(textDirection) { 21626 case TEXT_DIRECTION_INHERIT: 21627 if (!canResolveTextDirection()) { 21628 // We cannot do the resolution if there is no parent, so use the default one 21629 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21630 // Resolution will need to happen again later 21631 return false; 21632 } 21633 21634 // Parent has not yet resolved, so we still return the default 21635 try { 21636 if (!mParent.isTextDirectionResolved()) { 21637 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21638 // Resolution will need to happen again later 21639 return false; 21640 } 21641 } catch (AbstractMethodError e) { 21642 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21643 " does not fully implement ViewParent", e); 21644 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21645 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21646 return true; 21647 } 21648 21649 // Set current resolved direction to the same value as the parent's one 21650 int parentResolvedDirection; 21651 try { 21652 parentResolvedDirection = mParent.getTextDirection(); 21653 } catch (AbstractMethodError e) { 21654 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21655 " does not fully implement ViewParent", e); 21656 parentResolvedDirection = TEXT_DIRECTION_LTR; 21657 } 21658 switch (parentResolvedDirection) { 21659 case TEXT_DIRECTION_FIRST_STRONG: 21660 case TEXT_DIRECTION_ANY_RTL: 21661 case TEXT_DIRECTION_LTR: 21662 case TEXT_DIRECTION_RTL: 21663 case TEXT_DIRECTION_LOCALE: 21664 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21665 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21666 mPrivateFlags2 |= 21667 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21668 break; 21669 default: 21670 // Default resolved direction is "first strong" heuristic 21671 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21672 } 21673 break; 21674 case TEXT_DIRECTION_FIRST_STRONG: 21675 case TEXT_DIRECTION_ANY_RTL: 21676 case TEXT_DIRECTION_LTR: 21677 case TEXT_DIRECTION_RTL: 21678 case TEXT_DIRECTION_LOCALE: 21679 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21680 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21681 // Resolved direction is the same as text direction 21682 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21683 break; 21684 default: 21685 // Default resolved direction is "first strong" heuristic 21686 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21687 } 21688 } else { 21689 // Default resolved direction is "first strong" heuristic 21690 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21691 } 21692 21693 // Set to resolved 21694 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21695 return true; 21696 } 21697 21698 /** 21699 * Check if text direction resolution can be done. 21700 * 21701 * @return true if text direction resolution can be done otherwise return false. 21702 */ 21703 public boolean canResolveTextDirection() { 21704 switch (getRawTextDirection()) { 21705 case TEXT_DIRECTION_INHERIT: 21706 if (mParent != null) { 21707 try { 21708 return mParent.canResolveTextDirection(); 21709 } catch (AbstractMethodError e) { 21710 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21711 " does not fully implement ViewParent", e); 21712 } 21713 } 21714 return false; 21715 21716 default: 21717 return true; 21718 } 21719 } 21720 21721 /** 21722 * Reset resolved text direction. Text direction will be resolved during a call to 21723 * {@link #onMeasure(int, int)}. 21724 * 21725 * @hide 21726 */ 21727 public void resetResolvedTextDirection() { 21728 // Reset any previous text direction resolution 21729 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21730 // Set to default value 21731 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21732 } 21733 21734 /** 21735 * @return true if text direction is inherited. 21736 * 21737 * @hide 21738 */ 21739 public boolean isTextDirectionInherited() { 21740 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21741 } 21742 21743 /** 21744 * @return true if text direction is resolved. 21745 */ 21746 public boolean isTextDirectionResolved() { 21747 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21748 } 21749 21750 /** 21751 * Return the value specifying the text alignment or policy that was set with 21752 * {@link #setTextAlignment(int)}. 21753 * 21754 * @return the defined text alignment. It can be one of: 21755 * 21756 * {@link #TEXT_ALIGNMENT_INHERIT}, 21757 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21758 * {@link #TEXT_ALIGNMENT_CENTER}, 21759 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21760 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21761 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21762 * {@link #TEXT_ALIGNMENT_VIEW_END} 21763 * 21764 * @attr ref android.R.styleable#View_textAlignment 21765 * 21766 * @hide 21767 */ 21768 @ViewDebug.ExportedProperty(category = "text", mapping = { 21769 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21770 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21771 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21772 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21773 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21774 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21775 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21776 }) 21777 @TextAlignment 21778 public int getRawTextAlignment() { 21779 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21780 } 21781 21782 /** 21783 * Set the text alignment. 21784 * 21785 * @param textAlignment The text alignment to set. Should be one of 21786 * 21787 * {@link #TEXT_ALIGNMENT_INHERIT}, 21788 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21789 * {@link #TEXT_ALIGNMENT_CENTER}, 21790 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21791 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21792 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21793 * {@link #TEXT_ALIGNMENT_VIEW_END} 21794 * 21795 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21796 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21797 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21798 * 21799 * @attr ref android.R.styleable#View_textAlignment 21800 */ 21801 public void setTextAlignment(@TextAlignment int textAlignment) { 21802 if (textAlignment != getRawTextAlignment()) { 21803 // Reset the current and resolved text alignment 21804 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21805 resetResolvedTextAlignment(); 21806 // Set the new text alignment 21807 mPrivateFlags2 |= 21808 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21809 // Do resolution 21810 resolveTextAlignment(); 21811 // Notify change 21812 onRtlPropertiesChanged(getLayoutDirection()); 21813 // Refresh 21814 requestLayout(); 21815 invalidate(true); 21816 } 21817 } 21818 21819 /** 21820 * Return the resolved text alignment. 21821 * 21822 * @return the resolved text alignment. Returns one of: 21823 * 21824 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21825 * {@link #TEXT_ALIGNMENT_CENTER}, 21826 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21827 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21828 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21829 * {@link #TEXT_ALIGNMENT_VIEW_END} 21830 * 21831 * @attr ref android.R.styleable#View_textAlignment 21832 */ 21833 @ViewDebug.ExportedProperty(category = "text", mapping = { 21834 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21835 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21836 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21837 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21838 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21839 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21840 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21841 }) 21842 @TextAlignment 21843 public int getTextAlignment() { 21844 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21845 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21846 } 21847 21848 /** 21849 * Resolve the text alignment. 21850 * 21851 * @return true if resolution has been done, false otherwise. 21852 * 21853 * @hide 21854 */ 21855 public boolean resolveTextAlignment() { 21856 // Reset any previous text alignment resolution 21857 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21858 21859 if (hasRtlSupport()) { 21860 // Set resolved text alignment flag depending on text alignment flag 21861 final int textAlignment = getRawTextAlignment(); 21862 switch (textAlignment) { 21863 case TEXT_ALIGNMENT_INHERIT: 21864 // Check if we can resolve the text alignment 21865 if (!canResolveTextAlignment()) { 21866 // We cannot do the resolution if there is no parent so use the default 21867 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21868 // Resolution will need to happen again later 21869 return false; 21870 } 21871 21872 // Parent has not yet resolved, so we still return the default 21873 try { 21874 if (!mParent.isTextAlignmentResolved()) { 21875 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21876 // Resolution will need to happen again later 21877 return false; 21878 } 21879 } catch (AbstractMethodError e) { 21880 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21881 " does not fully implement ViewParent", e); 21882 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21883 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21884 return true; 21885 } 21886 21887 int parentResolvedTextAlignment; 21888 try { 21889 parentResolvedTextAlignment = mParent.getTextAlignment(); 21890 } catch (AbstractMethodError e) { 21891 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21892 " does not fully implement ViewParent", e); 21893 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21894 } 21895 switch (parentResolvedTextAlignment) { 21896 case TEXT_ALIGNMENT_GRAVITY: 21897 case TEXT_ALIGNMENT_TEXT_START: 21898 case TEXT_ALIGNMENT_TEXT_END: 21899 case TEXT_ALIGNMENT_CENTER: 21900 case TEXT_ALIGNMENT_VIEW_START: 21901 case TEXT_ALIGNMENT_VIEW_END: 21902 // Resolved text alignment is the same as the parent resolved 21903 // text alignment 21904 mPrivateFlags2 |= 21905 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21906 break; 21907 default: 21908 // Use default resolved text alignment 21909 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21910 } 21911 break; 21912 case TEXT_ALIGNMENT_GRAVITY: 21913 case TEXT_ALIGNMENT_TEXT_START: 21914 case TEXT_ALIGNMENT_TEXT_END: 21915 case TEXT_ALIGNMENT_CENTER: 21916 case TEXT_ALIGNMENT_VIEW_START: 21917 case TEXT_ALIGNMENT_VIEW_END: 21918 // Resolved text alignment is the same as text alignment 21919 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21920 break; 21921 default: 21922 // Use default resolved text alignment 21923 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21924 } 21925 } else { 21926 // Use default resolved text alignment 21927 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21928 } 21929 21930 // Set the resolved 21931 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21932 return true; 21933 } 21934 21935 /** 21936 * Check if text alignment resolution can be done. 21937 * 21938 * @return true if text alignment resolution can be done otherwise return false. 21939 */ 21940 public boolean canResolveTextAlignment() { 21941 switch (getRawTextAlignment()) { 21942 case TEXT_DIRECTION_INHERIT: 21943 if (mParent != null) { 21944 try { 21945 return mParent.canResolveTextAlignment(); 21946 } catch (AbstractMethodError e) { 21947 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21948 " does not fully implement ViewParent", e); 21949 } 21950 } 21951 return false; 21952 21953 default: 21954 return true; 21955 } 21956 } 21957 21958 /** 21959 * Reset resolved text alignment. Text alignment will be resolved during a call to 21960 * {@link #onMeasure(int, int)}. 21961 * 21962 * @hide 21963 */ 21964 public void resetResolvedTextAlignment() { 21965 // Reset any previous text alignment resolution 21966 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21967 // Set to default 21968 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21969 } 21970 21971 /** 21972 * @return true if text alignment is inherited. 21973 * 21974 * @hide 21975 */ 21976 public boolean isTextAlignmentInherited() { 21977 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21978 } 21979 21980 /** 21981 * @return true if text alignment is resolved. 21982 */ 21983 public boolean isTextAlignmentResolved() { 21984 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21985 } 21986 21987 /** 21988 * Generate a value suitable for use in {@link #setId(int)}. 21989 * This value will not collide with ID values generated at build time by aapt for R.id. 21990 * 21991 * @return a generated ID value 21992 */ 21993 public static int generateViewId() { 21994 for (;;) { 21995 final int result = sNextGeneratedId.get(); 21996 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21997 int newValue = result + 1; 21998 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21999 if (sNextGeneratedId.compareAndSet(result, newValue)) { 22000 return result; 22001 } 22002 } 22003 } 22004 22005 /** 22006 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 22007 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 22008 * a normal View or a ViewGroup with 22009 * {@link android.view.ViewGroup#isTransitionGroup()} true. 22010 * @hide 22011 */ 22012 public void captureTransitioningViews(List<View> transitioningViews) { 22013 if (getVisibility() == View.VISIBLE) { 22014 transitioningViews.add(this); 22015 } 22016 } 22017 22018 /** 22019 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 22020 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 22021 * @hide 22022 */ 22023 public void findNamedViews(Map<String, View> namedElements) { 22024 if (getVisibility() == VISIBLE || mGhostView != null) { 22025 String transitionName = getTransitionName(); 22026 if (transitionName != null) { 22027 namedElements.put(transitionName, this); 22028 } 22029 } 22030 } 22031 22032 /** 22033 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 22034 * The default implementation does not care the location or event types, but some subclasses 22035 * may use it (such as WebViews). 22036 * @param event The MotionEvent from a mouse 22037 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 22038 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 22039 * @see PointerIcon 22040 */ 22041 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 22042 final float x = event.getX(pointerIndex); 22043 final float y = event.getY(pointerIndex); 22044 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 22045 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 22046 } 22047 return mPointerIcon; 22048 } 22049 22050 /** 22051 * Set the pointer icon for the current view. 22052 * Passing {@code null} will restore the pointer icon to its default value. 22053 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 22054 */ 22055 public void setPointerIcon(PointerIcon pointerIcon) { 22056 mPointerIcon = pointerIcon; 22057 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 22058 return; 22059 } 22060 try { 22061 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 22062 } catch (RemoteException e) { 22063 } 22064 } 22065 22066 /** 22067 * Gets the pointer icon for the current view. 22068 */ 22069 public PointerIcon getPointerIcon() { 22070 return mPointerIcon; 22071 } 22072 22073 // 22074 // Properties 22075 // 22076 /** 22077 * A Property wrapper around the <code>alpha</code> functionality handled by the 22078 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 22079 */ 22080 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 22081 @Override 22082 public void setValue(View object, float value) { 22083 object.setAlpha(value); 22084 } 22085 22086 @Override 22087 public Float get(View object) { 22088 return object.getAlpha(); 22089 } 22090 }; 22091 22092 /** 22093 * A Property wrapper around the <code>translationX</code> functionality handled by the 22094 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 22095 */ 22096 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 22097 @Override 22098 public void setValue(View object, float value) { 22099 object.setTranslationX(value); 22100 } 22101 22102 @Override 22103 public Float get(View object) { 22104 return object.getTranslationX(); 22105 } 22106 }; 22107 22108 /** 22109 * A Property wrapper around the <code>translationY</code> functionality handled by the 22110 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 22111 */ 22112 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 22113 @Override 22114 public void setValue(View object, float value) { 22115 object.setTranslationY(value); 22116 } 22117 22118 @Override 22119 public Float get(View object) { 22120 return object.getTranslationY(); 22121 } 22122 }; 22123 22124 /** 22125 * A Property wrapper around the <code>translationZ</code> functionality handled by the 22126 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 22127 */ 22128 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 22129 @Override 22130 public void setValue(View object, float value) { 22131 object.setTranslationZ(value); 22132 } 22133 22134 @Override 22135 public Float get(View object) { 22136 return object.getTranslationZ(); 22137 } 22138 }; 22139 22140 /** 22141 * A Property wrapper around the <code>x</code> functionality handled by the 22142 * {@link View#setX(float)} and {@link View#getX()} methods. 22143 */ 22144 public static final Property<View, Float> X = new FloatProperty<View>("x") { 22145 @Override 22146 public void setValue(View object, float value) { 22147 object.setX(value); 22148 } 22149 22150 @Override 22151 public Float get(View object) { 22152 return object.getX(); 22153 } 22154 }; 22155 22156 /** 22157 * A Property wrapper around the <code>y</code> functionality handled by the 22158 * {@link View#setY(float)} and {@link View#getY()} methods. 22159 */ 22160 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 22161 @Override 22162 public void setValue(View object, float value) { 22163 object.setY(value); 22164 } 22165 22166 @Override 22167 public Float get(View object) { 22168 return object.getY(); 22169 } 22170 }; 22171 22172 /** 22173 * A Property wrapper around the <code>z</code> functionality handled by the 22174 * {@link View#setZ(float)} and {@link View#getZ()} methods. 22175 */ 22176 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 22177 @Override 22178 public void setValue(View object, float value) { 22179 object.setZ(value); 22180 } 22181 22182 @Override 22183 public Float get(View object) { 22184 return object.getZ(); 22185 } 22186 }; 22187 22188 /** 22189 * A Property wrapper around the <code>rotation</code> functionality handled by the 22190 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22191 */ 22192 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22193 @Override 22194 public void setValue(View object, float value) { 22195 object.setRotation(value); 22196 } 22197 22198 @Override 22199 public Float get(View object) { 22200 return object.getRotation(); 22201 } 22202 }; 22203 22204 /** 22205 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22206 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22207 */ 22208 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22209 @Override 22210 public void setValue(View object, float value) { 22211 object.setRotationX(value); 22212 } 22213 22214 @Override 22215 public Float get(View object) { 22216 return object.getRotationX(); 22217 } 22218 }; 22219 22220 /** 22221 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22222 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22223 */ 22224 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22225 @Override 22226 public void setValue(View object, float value) { 22227 object.setRotationY(value); 22228 } 22229 22230 @Override 22231 public Float get(View object) { 22232 return object.getRotationY(); 22233 } 22234 }; 22235 22236 /** 22237 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22238 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22239 */ 22240 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22241 @Override 22242 public void setValue(View object, float value) { 22243 object.setScaleX(value); 22244 } 22245 22246 @Override 22247 public Float get(View object) { 22248 return object.getScaleX(); 22249 } 22250 }; 22251 22252 /** 22253 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22254 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22255 */ 22256 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22257 @Override 22258 public void setValue(View object, float value) { 22259 object.setScaleY(value); 22260 } 22261 22262 @Override 22263 public Float get(View object) { 22264 return object.getScaleY(); 22265 } 22266 }; 22267 22268 /** 22269 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22270 * Each MeasureSpec represents a requirement for either the width or the height. 22271 * A MeasureSpec is comprised of a size and a mode. There are three possible 22272 * modes: 22273 * <dl> 22274 * <dt>UNSPECIFIED</dt> 22275 * <dd> 22276 * The parent has not imposed any constraint on the child. It can be whatever size 22277 * it wants. 22278 * </dd> 22279 * 22280 * <dt>EXACTLY</dt> 22281 * <dd> 22282 * The parent has determined an exact size for the child. The child is going to be 22283 * given those bounds regardless of how big it wants to be. 22284 * </dd> 22285 * 22286 * <dt>AT_MOST</dt> 22287 * <dd> 22288 * The child can be as large as it wants up to the specified size. 22289 * </dd> 22290 * </dl> 22291 * 22292 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22293 * is provided to pack and unpack the <size, mode> tuple into the int. 22294 */ 22295 public static class MeasureSpec { 22296 private static final int MODE_SHIFT = 30; 22297 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22298 22299 /** @hide */ 22300 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22301 @Retention(RetentionPolicy.SOURCE) 22302 public @interface MeasureSpecMode {} 22303 22304 /** 22305 * Measure specification mode: The parent has not imposed any constraint 22306 * on the child. It can be whatever size it wants. 22307 */ 22308 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22309 22310 /** 22311 * Measure specification mode: The parent has determined an exact size 22312 * for the child. The child is going to be given those bounds regardless 22313 * of how big it wants to be. 22314 */ 22315 public static final int EXACTLY = 1 << MODE_SHIFT; 22316 22317 /** 22318 * Measure specification mode: The child can be as large as it wants up 22319 * to the specified size. 22320 */ 22321 public static final int AT_MOST = 2 << MODE_SHIFT; 22322 22323 /** 22324 * Creates a measure specification based on the supplied size and mode. 22325 * 22326 * The mode must always be one of the following: 22327 * <ul> 22328 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22329 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22330 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22331 * </ul> 22332 * 22333 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22334 * implementation was such that the order of arguments did not matter 22335 * and overflow in either value could impact the resulting MeasureSpec. 22336 * {@link android.widget.RelativeLayout} was affected by this bug. 22337 * Apps targeting API levels greater than 17 will get the fixed, more strict 22338 * behavior.</p> 22339 * 22340 * @param size the size of the measure specification 22341 * @param mode the mode of the measure specification 22342 * @return the measure specification based on size and mode 22343 */ 22344 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22345 @MeasureSpecMode int mode) { 22346 if (sUseBrokenMakeMeasureSpec) { 22347 return size + mode; 22348 } else { 22349 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22350 } 22351 } 22352 22353 /** 22354 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22355 * will automatically get a size of 0. Older apps expect this. 22356 * 22357 * @hide internal use only for compatibility with system widgets and older apps 22358 */ 22359 public static int makeSafeMeasureSpec(int size, int mode) { 22360 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22361 return 0; 22362 } 22363 return makeMeasureSpec(size, mode); 22364 } 22365 22366 /** 22367 * Extracts the mode from the supplied measure specification. 22368 * 22369 * @param measureSpec the measure specification to extract the mode from 22370 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22371 * {@link android.view.View.MeasureSpec#AT_MOST} or 22372 * {@link android.view.View.MeasureSpec#EXACTLY} 22373 */ 22374 @MeasureSpecMode 22375 public static int getMode(int measureSpec) { 22376 //noinspection ResourceType 22377 return (measureSpec & MODE_MASK); 22378 } 22379 22380 /** 22381 * Extracts the size from the supplied measure specification. 22382 * 22383 * @param measureSpec the measure specification to extract the size from 22384 * @return the size in pixels defined in the supplied measure specification 22385 */ 22386 public static int getSize(int measureSpec) { 22387 return (measureSpec & ~MODE_MASK); 22388 } 22389 22390 static int adjust(int measureSpec, int delta) { 22391 final int mode = getMode(measureSpec); 22392 int size = getSize(measureSpec); 22393 if (mode == UNSPECIFIED) { 22394 // No need to adjust size for UNSPECIFIED mode. 22395 return makeMeasureSpec(size, UNSPECIFIED); 22396 } 22397 size += delta; 22398 if (size < 0) { 22399 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22400 ") spec: " + toString(measureSpec) + " delta: " + delta); 22401 size = 0; 22402 } 22403 return makeMeasureSpec(size, mode); 22404 } 22405 22406 /** 22407 * Returns a String representation of the specified measure 22408 * specification. 22409 * 22410 * @param measureSpec the measure specification to convert to a String 22411 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22412 */ 22413 public static String toString(int measureSpec) { 22414 int mode = getMode(measureSpec); 22415 int size = getSize(measureSpec); 22416 22417 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22418 22419 if (mode == UNSPECIFIED) 22420 sb.append("UNSPECIFIED "); 22421 else if (mode == EXACTLY) 22422 sb.append("EXACTLY "); 22423 else if (mode == AT_MOST) 22424 sb.append("AT_MOST "); 22425 else 22426 sb.append(mode).append(" "); 22427 22428 sb.append(size); 22429 return sb.toString(); 22430 } 22431 } 22432 22433 private final class CheckForLongPress implements Runnable { 22434 private int mOriginalWindowAttachCount; 22435 private float mX; 22436 private float mY; 22437 22438 @Override 22439 public void run() { 22440 if (isPressed() && (mParent != null) 22441 && mOriginalWindowAttachCount == mWindowAttachCount) { 22442 if (performLongClick(mX, mY)) { 22443 mHasPerformedLongPress = true; 22444 } 22445 } 22446 } 22447 22448 public void setAnchor(float x, float y) { 22449 mX = x; 22450 mY = y; 22451 } 22452 22453 public void rememberWindowAttachCount() { 22454 mOriginalWindowAttachCount = mWindowAttachCount; 22455 } 22456 } 22457 22458 private final class CheckForTap implements Runnable { 22459 public float x; 22460 public float y; 22461 22462 @Override 22463 public void run() { 22464 mPrivateFlags &= ~PFLAG_PREPRESSED; 22465 setPressed(true, x, y); 22466 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22467 } 22468 } 22469 22470 private final class PerformClick implements Runnable { 22471 @Override 22472 public void run() { 22473 performClick(); 22474 } 22475 } 22476 22477 /** 22478 * This method returns a ViewPropertyAnimator object, which can be used to animate 22479 * specific properties on this View. 22480 * 22481 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22482 */ 22483 public ViewPropertyAnimator animate() { 22484 if (mAnimator == null) { 22485 mAnimator = new ViewPropertyAnimator(this); 22486 } 22487 return mAnimator; 22488 } 22489 22490 /** 22491 * Sets the name of the View to be used to identify Views in Transitions. 22492 * Names should be unique in the View hierarchy. 22493 * 22494 * @param transitionName The name of the View to uniquely identify it for Transitions. 22495 */ 22496 public final void setTransitionName(String transitionName) { 22497 mTransitionName = transitionName; 22498 } 22499 22500 /** 22501 * Returns the name of the View to be used to identify Views in Transitions. 22502 * Names should be unique in the View hierarchy. 22503 * 22504 * <p>This returns null if the View has not been given a name.</p> 22505 * 22506 * @return The name used of the View to be used to identify Views in Transitions or null 22507 * if no name has been given. 22508 */ 22509 @ViewDebug.ExportedProperty 22510 public String getTransitionName() { 22511 return mTransitionName; 22512 } 22513 22514 /** 22515 * @hide 22516 */ 22517 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22518 // Do nothing. 22519 } 22520 22521 /** 22522 * Interface definition for a callback to be invoked when a hardware key event is 22523 * dispatched to this view. The callback will be invoked before the key event is 22524 * given to the view. This is only useful for hardware keyboards; a software input 22525 * method has no obligation to trigger this listener. 22526 */ 22527 public interface OnKeyListener { 22528 /** 22529 * Called when a hardware key is dispatched to a view. This allows listeners to 22530 * get a chance to respond before the target view. 22531 * <p>Key presses in software keyboards will generally NOT trigger this method, 22532 * although some may elect to do so in some situations. Do not assume a 22533 * software input method has to be key-based; even if it is, it may use key presses 22534 * in a different way than you expect, so there is no way to reliably catch soft 22535 * input key presses. 22536 * 22537 * @param v The view the key has been dispatched to. 22538 * @param keyCode The code for the physical key that was pressed 22539 * @param event The KeyEvent object containing full information about 22540 * the event. 22541 * @return True if the listener has consumed the event, false otherwise. 22542 */ 22543 boolean onKey(View v, int keyCode, KeyEvent event); 22544 } 22545 22546 /** 22547 * Interface definition for a callback to be invoked when a touch event is 22548 * dispatched to this view. The callback will be invoked before the touch 22549 * event is given to the view. 22550 */ 22551 public interface OnTouchListener { 22552 /** 22553 * Called when a touch event is dispatched to a view. This allows listeners to 22554 * get a chance to respond before the target view. 22555 * 22556 * @param v The view the touch event has been dispatched to. 22557 * @param event The MotionEvent object containing full information about 22558 * the event. 22559 * @return True if the listener has consumed the event, false otherwise. 22560 */ 22561 boolean onTouch(View v, MotionEvent event); 22562 } 22563 22564 /** 22565 * Interface definition for a callback to be invoked when a hover event is 22566 * dispatched to this view. The callback will be invoked before the hover 22567 * event is given to the view. 22568 */ 22569 public interface OnHoverListener { 22570 /** 22571 * Called when a hover event is dispatched to a view. This allows listeners to 22572 * get a chance to respond before the target view. 22573 * 22574 * @param v The view the hover event has been dispatched to. 22575 * @param event The MotionEvent object containing full information about 22576 * the event. 22577 * @return True if the listener has consumed the event, false otherwise. 22578 */ 22579 boolean onHover(View v, MotionEvent event); 22580 } 22581 22582 /** 22583 * Interface definition for a callback to be invoked when a generic motion event is 22584 * dispatched to this view. The callback will be invoked before the generic motion 22585 * event is given to the view. 22586 */ 22587 public interface OnGenericMotionListener { 22588 /** 22589 * Called when a generic motion event is dispatched to a view. This allows listeners to 22590 * get a chance to respond before the target view. 22591 * 22592 * @param v The view the generic motion event has been dispatched to. 22593 * @param event The MotionEvent object containing full information about 22594 * the event. 22595 * @return True if the listener has consumed the event, false otherwise. 22596 */ 22597 boolean onGenericMotion(View v, MotionEvent event); 22598 } 22599 22600 /** 22601 * Interface definition for a callback to be invoked when a view has been clicked and held. 22602 */ 22603 public interface OnLongClickListener { 22604 /** 22605 * Called when a view has been clicked and held. 22606 * 22607 * @param v The view that was clicked and held. 22608 * 22609 * @return true if the callback consumed the long click, false otherwise. 22610 */ 22611 boolean onLongClick(View v); 22612 } 22613 22614 /** 22615 * Interface definition for a callback to be invoked when a drag is being dispatched 22616 * to this view. The callback will be invoked before the hosting view's own 22617 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22618 * onDrag(event) behavior, it should return 'false' from this callback. 22619 * 22620 * <div class="special reference"> 22621 * <h3>Developer Guides</h3> 22622 * <p>For a guide to implementing drag and drop features, read the 22623 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22624 * </div> 22625 */ 22626 public interface OnDragListener { 22627 /** 22628 * Called when a drag event is dispatched to a view. This allows listeners 22629 * to get a chance to override base View behavior. 22630 * 22631 * @param v The View that received the drag event. 22632 * @param event The {@link android.view.DragEvent} object for the drag event. 22633 * @return {@code true} if the drag event was handled successfully, or {@code false} 22634 * if the drag event was not handled. Note that {@code false} will trigger the View 22635 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22636 */ 22637 boolean onDrag(View v, DragEvent event); 22638 } 22639 22640 /** 22641 * Interface definition for a callback to be invoked when the focus state of 22642 * a view changed. 22643 */ 22644 public interface OnFocusChangeListener { 22645 /** 22646 * Called when the focus state of a view has changed. 22647 * 22648 * @param v The view whose state has changed. 22649 * @param hasFocus The new focus state of v. 22650 */ 22651 void onFocusChange(View v, boolean hasFocus); 22652 } 22653 22654 /** 22655 * Interface definition for a callback to be invoked when a view is clicked. 22656 */ 22657 public interface OnClickListener { 22658 /** 22659 * Called when a view has been clicked. 22660 * 22661 * @param v The view that was clicked. 22662 */ 22663 void onClick(View v); 22664 } 22665 22666 /** 22667 * Interface definition for a callback to be invoked when a view is context clicked. 22668 */ 22669 public interface OnContextClickListener { 22670 /** 22671 * Called when a view is context clicked. 22672 * 22673 * @param v The view that has been context clicked. 22674 * @return true if the callback consumed the context click, false otherwise. 22675 */ 22676 boolean onContextClick(View v); 22677 } 22678 22679 /** 22680 * Interface definition for a callback to be invoked when the context menu 22681 * for this view is being built. 22682 */ 22683 public interface OnCreateContextMenuListener { 22684 /** 22685 * Called when the context menu for this view is being built. It is not 22686 * safe to hold onto the menu after this method returns. 22687 * 22688 * @param menu The context menu that is being built 22689 * @param v The view for which the context menu is being built 22690 * @param menuInfo Extra information about the item for which the 22691 * context menu should be shown. This information will vary 22692 * depending on the class of v. 22693 */ 22694 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22695 } 22696 22697 /** 22698 * Interface definition for a callback to be invoked when the status bar changes 22699 * visibility. This reports <strong>global</strong> changes to the system UI 22700 * state, not what the application is requesting. 22701 * 22702 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22703 */ 22704 public interface OnSystemUiVisibilityChangeListener { 22705 /** 22706 * Called when the status bar changes visibility because of a call to 22707 * {@link View#setSystemUiVisibility(int)}. 22708 * 22709 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22710 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22711 * This tells you the <strong>global</strong> state of these UI visibility 22712 * flags, not what your app is currently applying. 22713 */ 22714 public void onSystemUiVisibilityChange(int visibility); 22715 } 22716 22717 /** 22718 * Interface definition for a callback to be invoked when this view is attached 22719 * or detached from its window. 22720 */ 22721 public interface OnAttachStateChangeListener { 22722 /** 22723 * Called when the view is attached to a window. 22724 * @param v The view that was attached 22725 */ 22726 public void onViewAttachedToWindow(View v); 22727 /** 22728 * Called when the view is detached from a window. 22729 * @param v The view that was detached 22730 */ 22731 public void onViewDetachedFromWindow(View v); 22732 } 22733 22734 /** 22735 * Listener for applying window insets on a view in a custom way. 22736 * 22737 * <p>Apps may choose to implement this interface if they want to apply custom policy 22738 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22739 * is set, its 22740 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22741 * method will be called instead of the View's own 22742 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22743 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22744 * the View's normal behavior as part of its own.</p> 22745 */ 22746 public interface OnApplyWindowInsetsListener { 22747 /** 22748 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22749 * on a View, this listener method will be called instead of the view's own 22750 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22751 * 22752 * @param v The view applying window insets 22753 * @param insets The insets to apply 22754 * @return The insets supplied, minus any insets that were consumed 22755 */ 22756 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22757 } 22758 22759 private final class UnsetPressedState implements Runnable { 22760 @Override 22761 public void run() { 22762 setPressed(false); 22763 } 22764 } 22765 22766 /** 22767 * Base class for derived classes that want to save and restore their own 22768 * state in {@link android.view.View#onSaveInstanceState()}. 22769 */ 22770 public static class BaseSavedState extends AbsSavedState { 22771 String mStartActivityRequestWhoSaved; 22772 22773 /** 22774 * Constructor used when reading from a parcel. Reads the state of the superclass. 22775 * 22776 * @param source parcel to read from 22777 */ 22778 public BaseSavedState(Parcel source) { 22779 this(source, null); 22780 } 22781 22782 /** 22783 * Constructor used when reading from a parcel using a given class loader. 22784 * Reads the state of the superclass. 22785 * 22786 * @param source parcel to read from 22787 * @param loader ClassLoader to use for reading 22788 */ 22789 public BaseSavedState(Parcel source, ClassLoader loader) { 22790 super(source, loader); 22791 mStartActivityRequestWhoSaved = source.readString(); 22792 } 22793 22794 /** 22795 * Constructor called by derived classes when creating their SavedState objects 22796 * 22797 * @param superState The state of the superclass of this view 22798 */ 22799 public BaseSavedState(Parcelable superState) { 22800 super(superState); 22801 } 22802 22803 @Override 22804 public void writeToParcel(Parcel out, int flags) { 22805 super.writeToParcel(out, flags); 22806 out.writeString(mStartActivityRequestWhoSaved); 22807 } 22808 22809 public static final Parcelable.Creator<BaseSavedState> CREATOR 22810 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 22811 @Override 22812 public BaseSavedState createFromParcel(Parcel in) { 22813 return new BaseSavedState(in); 22814 } 22815 22816 @Override 22817 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 22818 return new BaseSavedState(in, loader); 22819 } 22820 22821 @Override 22822 public BaseSavedState[] newArray(int size) { 22823 return new BaseSavedState[size]; 22824 } 22825 }; 22826 } 22827 22828 /** 22829 * A set of information given to a view when it is attached to its parent 22830 * window. 22831 */ 22832 final static class AttachInfo { 22833 interface Callbacks { 22834 void playSoundEffect(int effectId); 22835 boolean performHapticFeedback(int effectId, boolean always); 22836 } 22837 22838 /** 22839 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22840 * to a Handler. This class contains the target (View) to invalidate and 22841 * the coordinates of the dirty rectangle. 22842 * 22843 * For performance purposes, this class also implements a pool of up to 22844 * POOL_LIMIT objects that get reused. This reduces memory allocations 22845 * whenever possible. 22846 */ 22847 static class InvalidateInfo { 22848 private static final int POOL_LIMIT = 10; 22849 22850 private static final SynchronizedPool<InvalidateInfo> sPool = 22851 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22852 22853 View target; 22854 22855 int left; 22856 int top; 22857 int right; 22858 int bottom; 22859 22860 public static InvalidateInfo obtain() { 22861 InvalidateInfo instance = sPool.acquire(); 22862 return (instance != null) ? instance : new InvalidateInfo(); 22863 } 22864 22865 public void recycle() { 22866 target = null; 22867 sPool.release(this); 22868 } 22869 } 22870 22871 final IWindowSession mSession; 22872 22873 final IWindow mWindow; 22874 22875 final IBinder mWindowToken; 22876 22877 final Display mDisplay; 22878 22879 final Callbacks mRootCallbacks; 22880 22881 IWindowId mIWindowId; 22882 WindowId mWindowId; 22883 22884 /** 22885 * The top view of the hierarchy. 22886 */ 22887 View mRootView; 22888 22889 IBinder mPanelParentWindowToken; 22890 22891 boolean mHardwareAccelerated; 22892 boolean mHardwareAccelerationRequested; 22893 ThreadedRenderer mThreadedRenderer; 22894 List<RenderNode> mPendingAnimatingRenderNodes; 22895 22896 /** 22897 * The state of the display to which the window is attached, as reported 22898 * by {@link Display#getState()}. Note that the display state constants 22899 * declared by {@link Display} do not exactly line up with the screen state 22900 * constants declared by {@link View} (there are more display states than 22901 * screen states). 22902 */ 22903 int mDisplayState = Display.STATE_UNKNOWN; 22904 22905 /** 22906 * Scale factor used by the compatibility mode 22907 */ 22908 float mApplicationScale; 22909 22910 /** 22911 * Indicates whether the application is in compatibility mode 22912 */ 22913 boolean mScalingRequired; 22914 22915 /** 22916 * Left position of this view's window 22917 */ 22918 int mWindowLeft; 22919 22920 /** 22921 * Top position of this view's window 22922 */ 22923 int mWindowTop; 22924 22925 /** 22926 * Indicates whether views need to use 32-bit drawing caches 22927 */ 22928 boolean mUse32BitDrawingCache; 22929 22930 /** 22931 * For windows that are full-screen but using insets to layout inside 22932 * of the screen areas, these are the current insets to appear inside 22933 * the overscan area of the display. 22934 */ 22935 final Rect mOverscanInsets = new Rect(); 22936 22937 /** 22938 * For windows that are full-screen but using insets to layout inside 22939 * of the screen decorations, these are the current insets for the 22940 * content of the window. 22941 */ 22942 final Rect mContentInsets = new Rect(); 22943 22944 /** 22945 * For windows that are full-screen but using insets to layout inside 22946 * of the screen decorations, these are the current insets for the 22947 * actual visible parts of the window. 22948 */ 22949 final Rect mVisibleInsets = new Rect(); 22950 22951 /** 22952 * For windows that are full-screen but using insets to layout inside 22953 * of the screen decorations, these are the current insets for the 22954 * stable system windows. 22955 */ 22956 final Rect mStableInsets = new Rect(); 22957 22958 /** 22959 * For windows that include areas that are not covered by real surface these are the outsets 22960 * for real surface. 22961 */ 22962 final Rect mOutsets = new Rect(); 22963 22964 /** 22965 * In multi-window we force show the navigation bar. Because we don't want that the surface 22966 * size changes in this mode, we instead have a flag whether the navigation bar size should 22967 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22968 */ 22969 boolean mAlwaysConsumeNavBar; 22970 22971 /** 22972 * The internal insets given by this window. This value is 22973 * supplied by the client (through 22974 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22975 * be given to the window manager when changed to be used in laying 22976 * out windows behind it. 22977 */ 22978 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22979 = new ViewTreeObserver.InternalInsetsInfo(); 22980 22981 /** 22982 * Set to true when mGivenInternalInsets is non-empty. 22983 */ 22984 boolean mHasNonEmptyGivenInternalInsets; 22985 22986 /** 22987 * All views in the window's hierarchy that serve as scroll containers, 22988 * used to determine if the window can be resized or must be panned 22989 * to adjust for a soft input area. 22990 */ 22991 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22992 22993 final KeyEvent.DispatcherState mKeyDispatchState 22994 = new KeyEvent.DispatcherState(); 22995 22996 /** 22997 * Indicates whether the view's window currently has the focus. 22998 */ 22999 boolean mHasWindowFocus; 23000 23001 /** 23002 * The current visibility of the window. 23003 */ 23004 int mWindowVisibility; 23005 23006 /** 23007 * Indicates the time at which drawing started to occur. 23008 */ 23009 long mDrawingTime; 23010 23011 /** 23012 * Indicates whether or not ignoring the DIRTY_MASK flags. 23013 */ 23014 boolean mIgnoreDirtyState; 23015 23016 /** 23017 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 23018 * to avoid clearing that flag prematurely. 23019 */ 23020 boolean mSetIgnoreDirtyState = false; 23021 23022 /** 23023 * Indicates whether the view's window is currently in touch mode. 23024 */ 23025 boolean mInTouchMode; 23026 23027 /** 23028 * Indicates whether the view has requested unbuffered input dispatching for the current 23029 * event stream. 23030 */ 23031 boolean mUnbufferedDispatchRequested; 23032 23033 /** 23034 * Indicates that ViewAncestor should trigger a global layout change 23035 * the next time it performs a traversal 23036 */ 23037 boolean mRecomputeGlobalAttributes; 23038 23039 /** 23040 * Always report new attributes at next traversal. 23041 */ 23042 boolean mForceReportNewAttributes; 23043 23044 /** 23045 * Set during a traveral if any views want to keep the screen on. 23046 */ 23047 boolean mKeepScreenOn; 23048 23049 /** 23050 * Set during a traveral if the light center needs to be updated. 23051 */ 23052 boolean mNeedsUpdateLightCenter; 23053 23054 /** 23055 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 23056 */ 23057 int mSystemUiVisibility; 23058 23059 /** 23060 * Hack to force certain system UI visibility flags to be cleared. 23061 */ 23062 int mDisabledSystemUiVisibility; 23063 23064 /** 23065 * Last global system UI visibility reported by the window manager. 23066 */ 23067 int mGlobalSystemUiVisibility = -1; 23068 23069 /** 23070 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 23071 * attached. 23072 */ 23073 boolean mHasSystemUiListeners; 23074 23075 /** 23076 * Set if the window has requested to extend into the overscan region 23077 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 23078 */ 23079 boolean mOverscanRequested; 23080 23081 /** 23082 * Set if the visibility of any views has changed. 23083 */ 23084 boolean mViewVisibilityChanged; 23085 23086 /** 23087 * Set to true if a view has been scrolled. 23088 */ 23089 boolean mViewScrollChanged; 23090 23091 /** 23092 * Set to true if high contrast mode enabled 23093 */ 23094 boolean mHighContrastText; 23095 23096 /** 23097 * Set to true if a pointer event is currently being handled. 23098 */ 23099 boolean mHandlingPointerEvent; 23100 23101 /** 23102 * Global to the view hierarchy used as a temporary for dealing with 23103 * x/y points in the transparent region computations. 23104 */ 23105 final int[] mTransparentLocation = new int[2]; 23106 23107 /** 23108 * Global to the view hierarchy used as a temporary for dealing with 23109 * x/y points in the ViewGroup.invalidateChild implementation. 23110 */ 23111 final int[] mInvalidateChildLocation = new int[2]; 23112 23113 /** 23114 * Global to the view hierarchy used as a temporary for dealing with 23115 * computing absolute on-screen location. 23116 */ 23117 final int[] mTmpLocation = new int[2]; 23118 23119 /** 23120 * Global to the view hierarchy used as a temporary for dealing with 23121 * x/y location when view is transformed. 23122 */ 23123 final float[] mTmpTransformLocation = new float[2]; 23124 23125 /** 23126 * The view tree observer used to dispatch global events like 23127 * layout, pre-draw, touch mode change, etc. 23128 */ 23129 final ViewTreeObserver mTreeObserver; 23130 23131 /** 23132 * A Canvas used by the view hierarchy to perform bitmap caching. 23133 */ 23134 Canvas mCanvas; 23135 23136 /** 23137 * The view root impl. 23138 */ 23139 final ViewRootImpl mViewRootImpl; 23140 23141 /** 23142 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 23143 * handler can be used to pump events in the UI events queue. 23144 */ 23145 final Handler mHandler; 23146 23147 /** 23148 * Temporary for use in computing invalidate rectangles while 23149 * calling up the hierarchy. 23150 */ 23151 final Rect mTmpInvalRect = new Rect(); 23152 23153 /** 23154 * Temporary for use in computing hit areas with transformed views 23155 */ 23156 final RectF mTmpTransformRect = new RectF(); 23157 23158 /** 23159 * Temporary for use in computing hit areas with transformed views 23160 */ 23161 final RectF mTmpTransformRect1 = new RectF(); 23162 23163 /** 23164 * Temporary list of rectanges. 23165 */ 23166 final List<RectF> mTmpRectList = new ArrayList<>(); 23167 23168 /** 23169 * Temporary for use in transforming invalidation rect 23170 */ 23171 final Matrix mTmpMatrix = new Matrix(); 23172 23173 /** 23174 * Temporary for use in transforming invalidation rect 23175 */ 23176 final Transformation mTmpTransformation = new Transformation(); 23177 23178 /** 23179 * Temporary for use in querying outlines from OutlineProviders 23180 */ 23181 final Outline mTmpOutline = new Outline(); 23182 23183 /** 23184 * Temporary list for use in collecting focusable descendents of a view. 23185 */ 23186 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 23187 23188 /** 23189 * The id of the window for accessibility purposes. 23190 */ 23191 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 23192 23193 /** 23194 * Flags related to accessibility processing. 23195 * 23196 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23197 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23198 */ 23199 int mAccessibilityFetchFlags; 23200 23201 /** 23202 * The drawable for highlighting accessibility focus. 23203 */ 23204 Drawable mAccessibilityFocusDrawable; 23205 23206 /** 23207 * Show where the margins, bounds and layout bounds are for each view. 23208 */ 23209 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23210 23211 /** 23212 * Point used to compute visible regions. 23213 */ 23214 final Point mPoint = new Point(); 23215 23216 /** 23217 * Used to track which View originated a requestLayout() call, used when 23218 * requestLayout() is called during layout. 23219 */ 23220 View mViewRequestingLayout; 23221 23222 /** 23223 * Used to track views that need (at least) a partial relayout at their current size 23224 * during the next traversal. 23225 */ 23226 List<View> mPartialLayoutViews = new ArrayList<>(); 23227 23228 /** 23229 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23230 * modification. Lazily assigned during ViewRootImpl layout. 23231 */ 23232 List<View> mEmptyPartialLayoutViews; 23233 23234 /** 23235 * Used to track the identity of the current drag operation. 23236 */ 23237 IBinder mDragToken; 23238 23239 /** 23240 * The drag shadow surface for the current drag operation. 23241 */ 23242 public Surface mDragSurface; 23243 23244 /** 23245 * Creates a new set of attachment information with the specified 23246 * events handler and thread. 23247 * 23248 * @param handler the events handler the view must use 23249 */ 23250 AttachInfo(IWindowSession session, IWindow window, Display display, 23251 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 23252 Context context) { 23253 mSession = session; 23254 mWindow = window; 23255 mWindowToken = window.asBinder(); 23256 mDisplay = display; 23257 mViewRootImpl = viewRootImpl; 23258 mHandler = handler; 23259 mRootCallbacks = effectPlayer; 23260 mTreeObserver = new ViewTreeObserver(context); 23261 } 23262 } 23263 23264 /** 23265 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23266 * is supported. This avoids keeping too many unused fields in most 23267 * instances of View.</p> 23268 */ 23269 private static class ScrollabilityCache implements Runnable { 23270 23271 /** 23272 * Scrollbars are not visible 23273 */ 23274 public static final int OFF = 0; 23275 23276 /** 23277 * Scrollbars are visible 23278 */ 23279 public static final int ON = 1; 23280 23281 /** 23282 * Scrollbars are fading away 23283 */ 23284 public static final int FADING = 2; 23285 23286 public boolean fadeScrollBars; 23287 23288 public int fadingEdgeLength; 23289 public int scrollBarDefaultDelayBeforeFade; 23290 public int scrollBarFadeDuration; 23291 23292 public int scrollBarSize; 23293 public ScrollBarDrawable scrollBar; 23294 public float[] interpolatorValues; 23295 public View host; 23296 23297 public final Paint paint; 23298 public final Matrix matrix; 23299 public Shader shader; 23300 23301 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23302 23303 private static final float[] OPAQUE = { 255 }; 23304 private static final float[] TRANSPARENT = { 0.0f }; 23305 23306 /** 23307 * When fading should start. This time moves into the future every time 23308 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23309 */ 23310 public long fadeStartTime; 23311 23312 23313 /** 23314 * The current state of the scrollbars: ON, OFF, or FADING 23315 */ 23316 public int state = OFF; 23317 23318 private int mLastColor; 23319 23320 public final Rect mScrollBarBounds = new Rect(); 23321 23322 public static final int NOT_DRAGGING = 0; 23323 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23324 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23325 public int mScrollBarDraggingState = NOT_DRAGGING; 23326 23327 public float mScrollBarDraggingPos = 0; 23328 23329 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23330 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23331 scrollBarSize = configuration.getScaledScrollBarSize(); 23332 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23333 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23334 23335 paint = new Paint(); 23336 matrix = new Matrix(); 23337 // use use a height of 1, and then wack the matrix each time we 23338 // actually use it. 23339 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23340 paint.setShader(shader); 23341 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23342 23343 this.host = host; 23344 } 23345 23346 public void setFadeColor(int color) { 23347 if (color != mLastColor) { 23348 mLastColor = color; 23349 23350 if (color != 0) { 23351 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23352 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23353 paint.setShader(shader); 23354 // Restore the default transfer mode (src_over) 23355 paint.setXfermode(null); 23356 } else { 23357 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23358 paint.setShader(shader); 23359 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23360 } 23361 } 23362 } 23363 23364 public void run() { 23365 long now = AnimationUtils.currentAnimationTimeMillis(); 23366 if (now >= fadeStartTime) { 23367 23368 // the animation fades the scrollbars out by changing 23369 // the opacity (alpha) from fully opaque to fully 23370 // transparent 23371 int nextFrame = (int) now; 23372 int framesCount = 0; 23373 23374 Interpolator interpolator = scrollBarInterpolator; 23375 23376 // Start opaque 23377 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23378 23379 // End transparent 23380 nextFrame += scrollBarFadeDuration; 23381 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23382 23383 state = FADING; 23384 23385 // Kick off the fade animation 23386 host.invalidate(true); 23387 } 23388 } 23389 } 23390 23391 /** 23392 * Resuable callback for sending 23393 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23394 */ 23395 private class SendViewScrolledAccessibilityEvent implements Runnable { 23396 public volatile boolean mIsPending; 23397 23398 public void run() { 23399 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23400 mIsPending = false; 23401 } 23402 } 23403 23404 /** 23405 * <p> 23406 * This class represents a delegate that can be registered in a {@link View} 23407 * to enhance accessibility support via composition rather via inheritance. 23408 * It is specifically targeted to widget developers that extend basic View 23409 * classes i.e. classes in package android.view, that would like their 23410 * applications to be backwards compatible. 23411 * </p> 23412 * <div class="special reference"> 23413 * <h3>Developer Guides</h3> 23414 * <p>For more information about making applications accessible, read the 23415 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23416 * developer guide.</p> 23417 * </div> 23418 * <p> 23419 * A scenario in which a developer would like to use an accessibility delegate 23420 * is overriding a method introduced in a later API version than the minimal API 23421 * version supported by the application. For example, the method 23422 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23423 * in API version 4 when the accessibility APIs were first introduced. If a 23424 * developer would like his application to run on API version 4 devices (assuming 23425 * all other APIs used by the application are version 4 or lower) and take advantage 23426 * of this method, instead of overriding the method which would break the application's 23427 * backwards compatibility, he can override the corresponding method in this 23428 * delegate and register the delegate in the target View if the API version of 23429 * the system is high enough, i.e. the API version is the same as or higher than the API 23430 * version that introduced 23431 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23432 * </p> 23433 * <p> 23434 * Here is an example implementation: 23435 * </p> 23436 * <code><pre><p> 23437 * if (Build.VERSION.SDK_INT >= 14) { 23438 * // If the API version is equal of higher than the version in 23439 * // which onInitializeAccessibilityNodeInfo was introduced we 23440 * // register a delegate with a customized implementation. 23441 * View view = findViewById(R.id.view_id); 23442 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23443 * public void onInitializeAccessibilityNodeInfo(View host, 23444 * AccessibilityNodeInfo info) { 23445 * // Let the default implementation populate the info. 23446 * super.onInitializeAccessibilityNodeInfo(host, info); 23447 * // Set some other information. 23448 * info.setEnabled(host.isEnabled()); 23449 * } 23450 * }); 23451 * } 23452 * </code></pre></p> 23453 * <p> 23454 * This delegate contains methods that correspond to the accessibility methods 23455 * in View. If a delegate has been specified the implementation in View hands 23456 * off handling to the corresponding method in this delegate. The default 23457 * implementation the delegate methods behaves exactly as the corresponding 23458 * method in View for the case of no accessibility delegate been set. Hence, 23459 * to customize the behavior of a View method, clients can override only the 23460 * corresponding delegate method without altering the behavior of the rest 23461 * accessibility related methods of the host view. 23462 * </p> 23463 * <p> 23464 * <strong>Note:</strong> On platform versions prior to 23465 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23466 * views in the {@code android.widget.*} package are called <i>before</i> 23467 * host methods. This prevents certain properties such as class name from 23468 * being modified by overriding 23469 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23470 * as any changes will be overwritten by the host class. 23471 * <p> 23472 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23473 * methods are called <i>after</i> host methods, which all properties to be 23474 * modified without being overwritten by the host class. 23475 */ 23476 public static class AccessibilityDelegate { 23477 23478 /** 23479 * Sends an accessibility event of the given type. If accessibility is not 23480 * enabled this method has no effect. 23481 * <p> 23482 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23483 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23484 * been set. 23485 * </p> 23486 * 23487 * @param host The View hosting the delegate. 23488 * @param eventType The type of the event to send. 23489 * 23490 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23491 */ 23492 public void sendAccessibilityEvent(View host, int eventType) { 23493 host.sendAccessibilityEventInternal(eventType); 23494 } 23495 23496 /** 23497 * Performs the specified accessibility action on the view. For 23498 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23499 * <p> 23500 * The default implementation behaves as 23501 * {@link View#performAccessibilityAction(int, Bundle) 23502 * View#performAccessibilityAction(int, Bundle)} for the case of 23503 * no accessibility delegate been set. 23504 * </p> 23505 * 23506 * @param action The action to perform. 23507 * @return Whether the action was performed. 23508 * 23509 * @see View#performAccessibilityAction(int, Bundle) 23510 * View#performAccessibilityAction(int, Bundle) 23511 */ 23512 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23513 return host.performAccessibilityActionInternal(action, args); 23514 } 23515 23516 /** 23517 * Sends an accessibility event. This method behaves exactly as 23518 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23519 * empty {@link AccessibilityEvent} and does not perform a check whether 23520 * accessibility is enabled. 23521 * <p> 23522 * The default implementation behaves as 23523 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23524 * View#sendAccessibilityEventUnchecked(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 send. 23530 * 23531 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23532 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23533 */ 23534 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23535 host.sendAccessibilityEventUncheckedInternal(event); 23536 } 23537 23538 /** 23539 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23540 * to its children for adding their text content to the event. 23541 * <p> 23542 * The default implementation behaves as 23543 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23544 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23545 * the case of no accessibility delegate been set. 23546 * </p> 23547 * 23548 * @param host The View hosting the delegate. 23549 * @param event The event. 23550 * @return True if the event population was completed. 23551 * 23552 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23553 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23554 */ 23555 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23556 return host.dispatchPopulateAccessibilityEventInternal(event); 23557 } 23558 23559 /** 23560 * Gives a chance to the host View to populate the accessibility event with its 23561 * text content. 23562 * <p> 23563 * The default implementation behaves as 23564 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23565 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23566 * the case of no accessibility delegate been set. 23567 * </p> 23568 * 23569 * @param host The View hosting the delegate. 23570 * @param event The accessibility event which to populate. 23571 * 23572 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23573 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23574 */ 23575 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23576 host.onPopulateAccessibilityEventInternal(event); 23577 } 23578 23579 /** 23580 * Initializes an {@link AccessibilityEvent} with information about the 23581 * the host View which is the event source. 23582 * <p> 23583 * The default implementation behaves as 23584 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23585 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23586 * the case of no accessibility delegate been set. 23587 * </p> 23588 * 23589 * @param host The View hosting the delegate. 23590 * @param event The event to initialize. 23591 * 23592 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23593 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23594 */ 23595 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23596 host.onInitializeAccessibilityEventInternal(event); 23597 } 23598 23599 /** 23600 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23601 * <p> 23602 * The default implementation behaves as 23603 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23604 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23605 * the case of no accessibility delegate been set. 23606 * </p> 23607 * 23608 * @param host The View hosting the delegate. 23609 * @param info The instance to initialize. 23610 * 23611 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23612 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23613 */ 23614 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23615 host.onInitializeAccessibilityNodeInfoInternal(info); 23616 } 23617 23618 /** 23619 * Called when a child of the host View has requested sending an 23620 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23621 * to augment the event. 23622 * <p> 23623 * The default implementation behaves as 23624 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23625 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23626 * the case of no accessibility delegate been set. 23627 * </p> 23628 * 23629 * @param host The View hosting the delegate. 23630 * @param child The child which requests sending the event. 23631 * @param event The event to be sent. 23632 * @return True if the event should be sent 23633 * 23634 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23635 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23636 */ 23637 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23638 AccessibilityEvent event) { 23639 return host.onRequestSendAccessibilityEventInternal(child, event); 23640 } 23641 23642 /** 23643 * Gets the provider for managing a virtual view hierarchy rooted at this View 23644 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23645 * that explore the window content. 23646 * <p> 23647 * The default implementation behaves as 23648 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23649 * the case of no accessibility delegate been set. 23650 * </p> 23651 * 23652 * @return The provider. 23653 * 23654 * @see AccessibilityNodeProvider 23655 */ 23656 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23657 return null; 23658 } 23659 23660 /** 23661 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23662 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23663 * This method is responsible for obtaining an accessibility node info from a 23664 * pool of reusable instances and calling 23665 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23666 * view to initialize the former. 23667 * <p> 23668 * <strong>Note:</strong> The client is responsible for recycling the obtained 23669 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23670 * creation. 23671 * </p> 23672 * <p> 23673 * The default implementation behaves as 23674 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23675 * the case of no accessibility delegate been set. 23676 * </p> 23677 * @return A populated {@link AccessibilityNodeInfo}. 23678 * 23679 * @see AccessibilityNodeInfo 23680 * 23681 * @hide 23682 */ 23683 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23684 return host.createAccessibilityNodeInfoInternal(); 23685 } 23686 } 23687 23688 private class MatchIdPredicate implements Predicate<View> { 23689 public int mId; 23690 23691 @Override 23692 public boolean apply(View view) { 23693 return (view.mID == mId); 23694 } 23695 } 23696 23697 private class MatchLabelForPredicate implements Predicate<View> { 23698 private int mLabeledId; 23699 23700 @Override 23701 public boolean apply(View view) { 23702 return (view.mLabelForId == mLabeledId); 23703 } 23704 } 23705 23706 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23707 private int mChangeTypes = 0; 23708 private boolean mPosted; 23709 private boolean mPostedWithDelay; 23710 private long mLastEventTimeMillis; 23711 23712 @Override 23713 public void run() { 23714 mPosted = false; 23715 mPostedWithDelay = false; 23716 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23717 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23718 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23719 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23720 event.setContentChangeTypes(mChangeTypes); 23721 sendAccessibilityEventUnchecked(event); 23722 } 23723 mChangeTypes = 0; 23724 } 23725 23726 public void runOrPost(int changeType) { 23727 mChangeTypes |= changeType; 23728 23729 // If this is a live region or the child of a live region, collect 23730 // all events from this frame and send them on the next frame. 23731 if (inLiveRegion()) { 23732 // If we're already posted with a delay, remove that. 23733 if (mPostedWithDelay) { 23734 removeCallbacks(this); 23735 mPostedWithDelay = false; 23736 } 23737 // Only post if we're not already posted. 23738 if (!mPosted) { 23739 post(this); 23740 mPosted = true; 23741 } 23742 return; 23743 } 23744 23745 if (mPosted) { 23746 return; 23747 } 23748 23749 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23750 final long minEventIntevalMillis = 23751 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23752 if (timeSinceLastMillis >= minEventIntevalMillis) { 23753 removeCallbacks(this); 23754 run(); 23755 } else { 23756 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23757 mPostedWithDelay = true; 23758 } 23759 } 23760 } 23761 23762 private boolean inLiveRegion() { 23763 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23764 return true; 23765 } 23766 23767 ViewParent parent = getParent(); 23768 while (parent instanceof View) { 23769 if (((View) parent).getAccessibilityLiveRegion() 23770 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23771 return true; 23772 } 23773 parent = parent.getParent(); 23774 } 23775 23776 return false; 23777 } 23778 23779 /** 23780 * Dump all private flags in readable format, useful for documentation and 23781 * sanity checking. 23782 */ 23783 private static void dumpFlags() { 23784 final HashMap<String, String> found = Maps.newHashMap(); 23785 try { 23786 for (Field field : View.class.getDeclaredFields()) { 23787 final int modifiers = field.getModifiers(); 23788 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23789 if (field.getType().equals(int.class)) { 23790 final int value = field.getInt(null); 23791 dumpFlag(found, field.getName(), value); 23792 } else if (field.getType().equals(int[].class)) { 23793 final int[] values = (int[]) field.get(null); 23794 for (int i = 0; i < values.length; i++) { 23795 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23796 } 23797 } 23798 } 23799 } 23800 } catch (IllegalAccessException e) { 23801 throw new RuntimeException(e); 23802 } 23803 23804 final ArrayList<String> keys = Lists.newArrayList(); 23805 keys.addAll(found.keySet()); 23806 Collections.sort(keys); 23807 for (String key : keys) { 23808 Log.d(VIEW_LOG_TAG, found.get(key)); 23809 } 23810 } 23811 23812 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23813 // Sort flags by prefix, then by bits, always keeping unique keys 23814 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23815 final int prefix = name.indexOf('_'); 23816 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23817 final String output = bits + " " + name; 23818 found.put(key, output); 23819 } 23820 23821 /** {@hide} */ 23822 public void encode(@NonNull ViewHierarchyEncoder stream) { 23823 stream.beginObject(this); 23824 encodeProperties(stream); 23825 stream.endObject(); 23826 } 23827 23828 /** {@hide} */ 23829 @CallSuper 23830 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23831 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23832 if (resolveId instanceof String) { 23833 stream.addProperty("id", (String) resolveId); 23834 } else { 23835 stream.addProperty("id", mID); 23836 } 23837 23838 stream.addProperty("misc:transformation.alpha", 23839 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23840 stream.addProperty("misc:transitionName", getTransitionName()); 23841 23842 // layout 23843 stream.addProperty("layout:left", mLeft); 23844 stream.addProperty("layout:right", mRight); 23845 stream.addProperty("layout:top", mTop); 23846 stream.addProperty("layout:bottom", mBottom); 23847 stream.addProperty("layout:width", getWidth()); 23848 stream.addProperty("layout:height", getHeight()); 23849 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23850 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23851 stream.addProperty("layout:hasTransientState", hasTransientState()); 23852 stream.addProperty("layout:baseline", getBaseline()); 23853 23854 // layout params 23855 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23856 if (layoutParams != null) { 23857 stream.addPropertyKey("layoutParams"); 23858 layoutParams.encode(stream); 23859 } 23860 23861 // scrolling 23862 stream.addProperty("scrolling:scrollX", mScrollX); 23863 stream.addProperty("scrolling:scrollY", mScrollY); 23864 23865 // padding 23866 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23867 stream.addProperty("padding:paddingRight", mPaddingRight); 23868 stream.addProperty("padding:paddingTop", mPaddingTop); 23869 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23870 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23871 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23872 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23873 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23874 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23875 23876 // measurement 23877 stream.addProperty("measurement:minHeight", mMinHeight); 23878 stream.addProperty("measurement:minWidth", mMinWidth); 23879 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23880 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23881 23882 // drawing 23883 stream.addProperty("drawing:elevation", getElevation()); 23884 stream.addProperty("drawing:translationX", getTranslationX()); 23885 stream.addProperty("drawing:translationY", getTranslationY()); 23886 stream.addProperty("drawing:translationZ", getTranslationZ()); 23887 stream.addProperty("drawing:rotation", getRotation()); 23888 stream.addProperty("drawing:rotationX", getRotationX()); 23889 stream.addProperty("drawing:rotationY", getRotationY()); 23890 stream.addProperty("drawing:scaleX", getScaleX()); 23891 stream.addProperty("drawing:scaleY", getScaleY()); 23892 stream.addProperty("drawing:pivotX", getPivotX()); 23893 stream.addProperty("drawing:pivotY", getPivotY()); 23894 stream.addProperty("drawing:opaque", isOpaque()); 23895 stream.addProperty("drawing:alpha", getAlpha()); 23896 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23897 stream.addProperty("drawing:shadow", hasShadow()); 23898 stream.addProperty("drawing:solidColor", getSolidColor()); 23899 stream.addProperty("drawing:layerType", mLayerType); 23900 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23901 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23902 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23903 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23904 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23905 23906 // focus 23907 stream.addProperty("focus:hasFocus", hasFocus()); 23908 stream.addProperty("focus:isFocused", isFocused()); 23909 stream.addProperty("focus:isFocusable", isFocusable()); 23910 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23911 23912 stream.addProperty("misc:clickable", isClickable()); 23913 stream.addProperty("misc:pressed", isPressed()); 23914 stream.addProperty("misc:selected", isSelected()); 23915 stream.addProperty("misc:touchMode", isInTouchMode()); 23916 stream.addProperty("misc:hovered", isHovered()); 23917 stream.addProperty("misc:activated", isActivated()); 23918 23919 stream.addProperty("misc:visibility", getVisibility()); 23920 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23921 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23922 23923 stream.addProperty("misc:enabled", isEnabled()); 23924 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23925 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23926 23927 // theme attributes 23928 Resources.Theme theme = getContext().getTheme(); 23929 if (theme != null) { 23930 stream.addPropertyKey("theme"); 23931 theme.encode(stream); 23932 } 23933 23934 // view attribute information 23935 int n = mAttributes != null ? mAttributes.length : 0; 23936 stream.addProperty("meta:__attrCount__", n/2); 23937 for (int i = 0; i < n; i += 2) { 23938 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23939 } 23940 23941 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23942 23943 // text 23944 stream.addProperty("text:textDirection", getTextDirection()); 23945 stream.addProperty("text:textAlignment", getTextAlignment()); 23946 23947 // accessibility 23948 CharSequence contentDescription = getContentDescription(); 23949 stream.addProperty("accessibility:contentDescription", 23950 contentDescription == null ? "" : contentDescription.toString()); 23951 stream.addProperty("accessibility:labelFor", getLabelFor()); 23952 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23953 } 23954 23955 /** 23956 * Determine if this view is rendered on a round wearable device and is the main view 23957 * on the screen. 23958 */ 23959 private boolean shouldDrawRoundScrollbar() { 23960 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 23961 return false; 23962 } 23963 23964 final View rootView = getRootView(); 23965 final WindowInsets insets = getRootWindowInsets(); 23966 23967 int height = getHeight(); 23968 int width = getWidth(); 23969 int displayHeight = rootView.getHeight(); 23970 int displayWidth = rootView.getWidth(); 23971 23972 if (height != displayHeight || width != displayWidth) { 23973 return false; 23974 } 23975 23976 getLocationOnScreen(mAttachInfo.mTmpLocation); 23977 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 23978 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 23979 } 23980} 23981