View.java revision c2e3594b7f26ab3e91fd69b42791ed2276918485
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 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7198 * 7199 * @return The view accessibility id. 7200 * 7201 * @hide 7202 */ 7203 public int getAccessibilityViewId() { 7204 if (mAccessibilityViewId == NO_ID) { 7205 mAccessibilityViewId = sNextAccessibilityViewId++; 7206 } 7207 return mAccessibilityViewId; 7208 } 7209 7210 /** 7211 * Gets the unique identifier of the window in which this View reseides. 7212 * 7213 * @return The window accessibility id. 7214 * 7215 * @hide 7216 */ 7217 public int getAccessibilityWindowId() { 7218 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7219 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7220 } 7221 7222 /** 7223 * Returns the {@link View}'s content description. 7224 * <p> 7225 * <strong>Note:</strong> Do not override this method, as it will have no 7226 * effect on the content description presented to accessibility services. 7227 * You must call {@link #setContentDescription(CharSequence)} to modify the 7228 * content description. 7229 * 7230 * @return the content description 7231 * @see #setContentDescription(CharSequence) 7232 * @attr ref android.R.styleable#View_contentDescription 7233 */ 7234 @ViewDebug.ExportedProperty(category = "accessibility") 7235 public CharSequence getContentDescription() { 7236 return mContentDescription; 7237 } 7238 7239 /** 7240 * Sets the {@link View}'s content description. 7241 * <p> 7242 * A content description briefly describes the view and is primarily used 7243 * for accessibility support to determine how a view should be presented to 7244 * the user. In the case of a view with no textual representation, such as 7245 * {@link android.widget.ImageButton}, a useful content description 7246 * explains what the view does. For example, an image button with a phone 7247 * icon that is used to place a call may use "Call" as its content 7248 * description. An image of a floppy disk that is used to save a file may 7249 * use "Save". 7250 * 7251 * @param contentDescription The content description. 7252 * @see #getContentDescription() 7253 * @attr ref android.R.styleable#View_contentDescription 7254 */ 7255 @RemotableViewMethod 7256 public void setContentDescription(CharSequence contentDescription) { 7257 if (mContentDescription == null) { 7258 if (contentDescription == null) { 7259 return; 7260 } 7261 } else if (mContentDescription.equals(contentDescription)) { 7262 return; 7263 } 7264 mContentDescription = contentDescription; 7265 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7266 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7267 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7268 notifySubtreeAccessibilityStateChangedIfNeeded(); 7269 } else { 7270 notifyViewAccessibilityStateChangedIfNeeded( 7271 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7272 } 7273 } 7274 7275 /** 7276 * Sets the id of a view before which this one is visited in accessibility traversal. 7277 * A screen-reader must visit the content of this view before the content of the one 7278 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7279 * will traverse the entire content of B before traversing the entire content of A, 7280 * regardles of what traversal strategy it is using. 7281 * <p> 7282 * Views that do not have specified before/after relationships are traversed in order 7283 * determined by the screen-reader. 7284 * </p> 7285 * <p> 7286 * Setting that this view is before a view that is not important for accessibility 7287 * or if this view is not important for accessibility will have no effect as the 7288 * screen-reader is not aware of unimportant views. 7289 * </p> 7290 * 7291 * @param beforeId The id of a view this one precedes in accessibility traversal. 7292 * 7293 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7294 * 7295 * @see #setImportantForAccessibility(int) 7296 */ 7297 @RemotableViewMethod 7298 public void setAccessibilityTraversalBefore(int beforeId) { 7299 if (mAccessibilityTraversalBeforeId == beforeId) { 7300 return; 7301 } 7302 mAccessibilityTraversalBeforeId = beforeId; 7303 notifyViewAccessibilityStateChangedIfNeeded( 7304 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7305 } 7306 7307 /** 7308 * Gets the id of a view before which this one is visited in accessibility traversal. 7309 * 7310 * @return The id of a view this one precedes in accessibility traversal if 7311 * specified, otherwise {@link #NO_ID}. 7312 * 7313 * @see #setAccessibilityTraversalBefore(int) 7314 */ 7315 public int getAccessibilityTraversalBefore() { 7316 return mAccessibilityTraversalBeforeId; 7317 } 7318 7319 /** 7320 * Sets the id of a view after which this one is visited in accessibility traversal. 7321 * A screen-reader must visit the content of the other view before the content of this 7322 * one. For example, if view B is set to be after view A, then a screen-reader 7323 * will traverse the entire content of A before traversing the entire content of B, 7324 * regardles of what traversal strategy it is using. 7325 * <p> 7326 * Views that do not have specified before/after relationships are traversed in order 7327 * determined by the screen-reader. 7328 * </p> 7329 * <p> 7330 * Setting that this view is after a view that is not important for accessibility 7331 * or if this view is not important for accessibility will have no effect as the 7332 * screen-reader is not aware of unimportant views. 7333 * </p> 7334 * 7335 * @param afterId The id of a view this one succedees in accessibility traversal. 7336 * 7337 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7338 * 7339 * @see #setImportantForAccessibility(int) 7340 */ 7341 @RemotableViewMethod 7342 public void setAccessibilityTraversalAfter(int afterId) { 7343 if (mAccessibilityTraversalAfterId == afterId) { 7344 return; 7345 } 7346 mAccessibilityTraversalAfterId = afterId; 7347 notifyViewAccessibilityStateChangedIfNeeded( 7348 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7349 } 7350 7351 /** 7352 * Gets the id of a view after which this one is visited in accessibility traversal. 7353 * 7354 * @return The id of a view this one succeedes in accessibility traversal if 7355 * specified, otherwise {@link #NO_ID}. 7356 * 7357 * @see #setAccessibilityTraversalAfter(int) 7358 */ 7359 public int getAccessibilityTraversalAfter() { 7360 return mAccessibilityTraversalAfterId; 7361 } 7362 7363 /** 7364 * Gets the id of a view for which this view serves as a label for 7365 * accessibility purposes. 7366 * 7367 * @return The labeled view id. 7368 */ 7369 @ViewDebug.ExportedProperty(category = "accessibility") 7370 public int getLabelFor() { 7371 return mLabelForId; 7372 } 7373 7374 /** 7375 * Sets the id of a view for which this view serves as a label for 7376 * accessibility purposes. 7377 * 7378 * @param id The labeled view id. 7379 */ 7380 @RemotableViewMethod 7381 public void setLabelFor(@IdRes int id) { 7382 if (mLabelForId == id) { 7383 return; 7384 } 7385 mLabelForId = id; 7386 if (mLabelForId != View.NO_ID 7387 && mID == View.NO_ID) { 7388 mID = generateViewId(); 7389 } 7390 notifyViewAccessibilityStateChangedIfNeeded( 7391 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7392 } 7393 7394 /** 7395 * Invoked whenever this view loses focus, either by losing window focus or by losing 7396 * focus within its window. This method can be used to clear any state tied to the 7397 * focus. For instance, if a button is held pressed with the trackball and the window 7398 * loses focus, this method can be used to cancel the press. 7399 * 7400 * Subclasses of View overriding this method should always call super.onFocusLost(). 7401 * 7402 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7403 * @see #onWindowFocusChanged(boolean) 7404 * 7405 * @hide pending API council approval 7406 */ 7407 @CallSuper 7408 protected void onFocusLost() { 7409 resetPressedState(); 7410 } 7411 7412 private void resetPressedState() { 7413 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7414 return; 7415 } 7416 7417 if (isPressed()) { 7418 setPressed(false); 7419 7420 if (!mHasPerformedLongPress) { 7421 removeLongPressCallback(); 7422 } 7423 } 7424 } 7425 7426 /** 7427 * Returns true if this view has focus 7428 * 7429 * @return True if this view has focus, false otherwise. 7430 */ 7431 @ViewDebug.ExportedProperty(category = "focus") 7432 public boolean isFocused() { 7433 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7434 } 7435 7436 /** 7437 * Find the view in the hierarchy rooted at this view that currently has 7438 * focus. 7439 * 7440 * @return The view that currently has focus, or null if no focused view can 7441 * be found. 7442 */ 7443 public View findFocus() { 7444 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7445 } 7446 7447 /** 7448 * Indicates whether this view is one of the set of scrollable containers in 7449 * its window. 7450 * 7451 * @return whether this view is one of the set of scrollable containers in 7452 * its window 7453 * 7454 * @attr ref android.R.styleable#View_isScrollContainer 7455 */ 7456 public boolean isScrollContainer() { 7457 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7458 } 7459 7460 /** 7461 * Change whether this view is one of the set of scrollable containers in 7462 * its window. This will be used to determine whether the window can 7463 * resize or must pan when a soft input area is open -- scrollable 7464 * containers allow the window to use resize mode since the container 7465 * will appropriately shrink. 7466 * 7467 * @attr ref android.R.styleable#View_isScrollContainer 7468 */ 7469 public void setScrollContainer(boolean isScrollContainer) { 7470 if (isScrollContainer) { 7471 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7472 mAttachInfo.mScrollContainers.add(this); 7473 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7474 } 7475 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7476 } else { 7477 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7478 mAttachInfo.mScrollContainers.remove(this); 7479 } 7480 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7481 } 7482 } 7483 7484 /** 7485 * Returns the quality of the drawing cache. 7486 * 7487 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7488 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7489 * 7490 * @see #setDrawingCacheQuality(int) 7491 * @see #setDrawingCacheEnabled(boolean) 7492 * @see #isDrawingCacheEnabled() 7493 * 7494 * @attr ref android.R.styleable#View_drawingCacheQuality 7495 */ 7496 @DrawingCacheQuality 7497 public int getDrawingCacheQuality() { 7498 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7499 } 7500 7501 /** 7502 * Set the drawing cache quality of this view. This value is used only when the 7503 * drawing cache is enabled 7504 * 7505 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7506 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7507 * 7508 * @see #getDrawingCacheQuality() 7509 * @see #setDrawingCacheEnabled(boolean) 7510 * @see #isDrawingCacheEnabled() 7511 * 7512 * @attr ref android.R.styleable#View_drawingCacheQuality 7513 */ 7514 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7515 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7516 } 7517 7518 /** 7519 * Returns whether the screen should remain on, corresponding to the current 7520 * value of {@link #KEEP_SCREEN_ON}. 7521 * 7522 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7523 * 7524 * @see #setKeepScreenOn(boolean) 7525 * 7526 * @attr ref android.R.styleable#View_keepScreenOn 7527 */ 7528 public boolean getKeepScreenOn() { 7529 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7530 } 7531 7532 /** 7533 * Controls whether the screen should remain on, modifying the 7534 * value of {@link #KEEP_SCREEN_ON}. 7535 * 7536 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7537 * 7538 * @see #getKeepScreenOn() 7539 * 7540 * @attr ref android.R.styleable#View_keepScreenOn 7541 */ 7542 public void setKeepScreenOn(boolean keepScreenOn) { 7543 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7544 } 7545 7546 /** 7547 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7548 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7549 * 7550 * @attr ref android.R.styleable#View_nextFocusLeft 7551 */ 7552 public int getNextFocusLeftId() { 7553 return mNextFocusLeftId; 7554 } 7555 7556 /** 7557 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7558 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7559 * decide automatically. 7560 * 7561 * @attr ref android.R.styleable#View_nextFocusLeft 7562 */ 7563 public void setNextFocusLeftId(int nextFocusLeftId) { 7564 mNextFocusLeftId = nextFocusLeftId; 7565 } 7566 7567 /** 7568 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7569 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7570 * 7571 * @attr ref android.R.styleable#View_nextFocusRight 7572 */ 7573 public int getNextFocusRightId() { 7574 return mNextFocusRightId; 7575 } 7576 7577 /** 7578 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7579 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7580 * decide automatically. 7581 * 7582 * @attr ref android.R.styleable#View_nextFocusRight 7583 */ 7584 public void setNextFocusRightId(int nextFocusRightId) { 7585 mNextFocusRightId = nextFocusRightId; 7586 } 7587 7588 /** 7589 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7590 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7591 * 7592 * @attr ref android.R.styleable#View_nextFocusUp 7593 */ 7594 public int getNextFocusUpId() { 7595 return mNextFocusUpId; 7596 } 7597 7598 /** 7599 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7600 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7601 * decide automatically. 7602 * 7603 * @attr ref android.R.styleable#View_nextFocusUp 7604 */ 7605 public void setNextFocusUpId(int nextFocusUpId) { 7606 mNextFocusUpId = nextFocusUpId; 7607 } 7608 7609 /** 7610 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7611 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7612 * 7613 * @attr ref android.R.styleable#View_nextFocusDown 7614 */ 7615 public int getNextFocusDownId() { 7616 return mNextFocusDownId; 7617 } 7618 7619 /** 7620 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7621 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7622 * decide automatically. 7623 * 7624 * @attr ref android.R.styleable#View_nextFocusDown 7625 */ 7626 public void setNextFocusDownId(int nextFocusDownId) { 7627 mNextFocusDownId = nextFocusDownId; 7628 } 7629 7630 /** 7631 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7632 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7633 * 7634 * @attr ref android.R.styleable#View_nextFocusForward 7635 */ 7636 public int getNextFocusForwardId() { 7637 return mNextFocusForwardId; 7638 } 7639 7640 /** 7641 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7642 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7643 * decide automatically. 7644 * 7645 * @attr ref android.R.styleable#View_nextFocusForward 7646 */ 7647 public void setNextFocusForwardId(int nextFocusForwardId) { 7648 mNextFocusForwardId = nextFocusForwardId; 7649 } 7650 7651 /** 7652 * Returns the visibility of this view and all of its ancestors 7653 * 7654 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7655 */ 7656 public boolean isShown() { 7657 View current = this; 7658 //noinspection ConstantConditions 7659 do { 7660 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7661 return false; 7662 } 7663 ViewParent parent = current.mParent; 7664 if (parent == null) { 7665 return false; // We are not attached to the view root 7666 } 7667 if (!(parent instanceof View)) { 7668 return true; 7669 } 7670 current = (View) parent; 7671 } while (current != null); 7672 7673 return false; 7674 } 7675 7676 /** 7677 * Called by the view hierarchy when the content insets for a window have 7678 * changed, to allow it to adjust its content to fit within those windows. 7679 * The content insets tell you the space that the status bar, input method, 7680 * and other system windows infringe on the application's window. 7681 * 7682 * <p>You do not normally need to deal with this function, since the default 7683 * window decoration given to applications takes care of applying it to the 7684 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7685 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7686 * and your content can be placed under those system elements. You can then 7687 * use this method within your view hierarchy if you have parts of your UI 7688 * which you would like to ensure are not being covered. 7689 * 7690 * <p>The default implementation of this method simply applies the content 7691 * insets to the view's padding, consuming that content (modifying the 7692 * insets to be 0), and returning true. This behavior is off by default, but can 7693 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7694 * 7695 * <p>This function's traversal down the hierarchy is depth-first. The same content 7696 * insets object is propagated down the hierarchy, so any changes made to it will 7697 * be seen by all following views (including potentially ones above in 7698 * the hierarchy since this is a depth-first traversal). The first view 7699 * that returns true will abort the entire traversal. 7700 * 7701 * <p>The default implementation works well for a situation where it is 7702 * used with a container that covers the entire window, allowing it to 7703 * apply the appropriate insets to its content on all edges. If you need 7704 * a more complicated layout (such as two different views fitting system 7705 * windows, one on the top of the window, and one on the bottom), 7706 * you can override the method and handle the insets however you would like. 7707 * Note that the insets provided by the framework are always relative to the 7708 * far edges of the window, not accounting for the location of the called view 7709 * within that window. (In fact when this method is called you do not yet know 7710 * where the layout will place the view, as it is done before layout happens.) 7711 * 7712 * <p>Note: unlike many View methods, there is no dispatch phase to this 7713 * call. If you are overriding it in a ViewGroup and want to allow the 7714 * call to continue to your children, you must be sure to call the super 7715 * implementation. 7716 * 7717 * <p>Here is a sample layout that makes use of fitting system windows 7718 * to have controls for a video view placed inside of the window decorations 7719 * that it hides and shows. This can be used with code like the second 7720 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7721 * 7722 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7723 * 7724 * @param insets Current content insets of the window. Prior to 7725 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7726 * the insets or else you and Android will be unhappy. 7727 * 7728 * @return {@code true} if this view applied the insets and it should not 7729 * continue propagating further down the hierarchy, {@code false} otherwise. 7730 * @see #getFitsSystemWindows() 7731 * @see #setFitsSystemWindows(boolean) 7732 * @see #setSystemUiVisibility(int) 7733 * 7734 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7735 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7736 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7737 * to implement handling their own insets. 7738 */ 7739 @Deprecated 7740 protected boolean fitSystemWindows(Rect insets) { 7741 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7742 if (insets == null) { 7743 // Null insets by definition have already been consumed. 7744 // This call cannot apply insets since there are none to apply, 7745 // so return false. 7746 return false; 7747 } 7748 // If we're not in the process of dispatching the newer apply insets call, 7749 // that means we're not in the compatibility path. Dispatch into the newer 7750 // apply insets path and take things from there. 7751 try { 7752 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7753 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7754 } finally { 7755 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7756 } 7757 } else { 7758 // We're being called from the newer apply insets path. 7759 // Perform the standard fallback behavior. 7760 return fitSystemWindowsInt(insets); 7761 } 7762 } 7763 7764 private boolean fitSystemWindowsInt(Rect insets) { 7765 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7766 mUserPaddingStart = UNDEFINED_PADDING; 7767 mUserPaddingEnd = UNDEFINED_PADDING; 7768 Rect localInsets = sThreadLocal.get(); 7769 if (localInsets == null) { 7770 localInsets = new Rect(); 7771 sThreadLocal.set(localInsets); 7772 } 7773 boolean res = computeFitSystemWindows(insets, localInsets); 7774 mUserPaddingLeftInitial = localInsets.left; 7775 mUserPaddingRightInitial = localInsets.right; 7776 internalSetPadding(localInsets.left, localInsets.top, 7777 localInsets.right, localInsets.bottom); 7778 return res; 7779 } 7780 return false; 7781 } 7782 7783 /** 7784 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7785 * 7786 * <p>This method should be overridden by views that wish to apply a policy different from or 7787 * in addition to the default behavior. Clients that wish to force a view subtree 7788 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7789 * 7790 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7791 * it will be called during dispatch instead of this method. The listener may optionally 7792 * call this method from its own implementation if it wishes to apply the view's default 7793 * insets policy in addition to its own.</p> 7794 * 7795 * <p>Implementations of this method should either return the insets parameter unchanged 7796 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7797 * that this view applied itself. This allows new inset types added in future platform 7798 * versions to pass through existing implementations unchanged without being erroneously 7799 * consumed.</p> 7800 * 7801 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7802 * property is set then the view will consume the system window insets and apply them 7803 * as padding for the view.</p> 7804 * 7805 * @param insets Insets to apply 7806 * @return The supplied insets with any applied insets consumed 7807 */ 7808 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7809 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7810 // We weren't called from within a direct call to fitSystemWindows, 7811 // call into it as a fallback in case we're in a class that overrides it 7812 // and has logic to perform. 7813 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7814 return insets.consumeSystemWindowInsets(); 7815 } 7816 } else { 7817 // We were called from within a direct call to fitSystemWindows. 7818 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7819 return insets.consumeSystemWindowInsets(); 7820 } 7821 } 7822 return insets; 7823 } 7824 7825 /** 7826 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7827 * window insets to this view. The listener's 7828 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7829 * method will be called instead of the view's 7830 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7831 * 7832 * @param listener Listener to set 7833 * 7834 * @see #onApplyWindowInsets(WindowInsets) 7835 */ 7836 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7837 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7838 } 7839 7840 /** 7841 * Request to apply the given window insets to this view or another view in its subtree. 7842 * 7843 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7844 * obscured by window decorations or overlays. This can include the status and navigation bars, 7845 * action bars, input methods and more. New inset categories may be added in the future. 7846 * The method returns the insets provided minus any that were applied by this view or its 7847 * children.</p> 7848 * 7849 * <p>Clients wishing to provide custom behavior should override the 7850 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7851 * {@link OnApplyWindowInsetsListener} via the 7852 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7853 * method.</p> 7854 * 7855 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7856 * </p> 7857 * 7858 * @param insets Insets to apply 7859 * @return The provided insets minus the insets that were consumed 7860 */ 7861 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7862 try { 7863 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7864 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7865 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7866 } else { 7867 return onApplyWindowInsets(insets); 7868 } 7869 } finally { 7870 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7871 } 7872 } 7873 7874 /** 7875 * Compute the view's coordinate within the surface. 7876 * 7877 * <p>Computes the coordinates of this view in its surface. The argument 7878 * must be an array of two integers. After the method returns, the array 7879 * contains the x and y location in that order.</p> 7880 * @hide 7881 * @param location an array of two integers in which to hold the coordinates 7882 */ 7883 public void getLocationInSurface(@Size(2) int[] location) { 7884 getLocationInWindow(location); 7885 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7886 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7887 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7888 } 7889 } 7890 7891 /** 7892 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7893 * only available if the view is attached. 7894 * 7895 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7896 */ 7897 public WindowInsets getRootWindowInsets() { 7898 if (mAttachInfo != null) { 7899 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7900 } 7901 return null; 7902 } 7903 7904 /** 7905 * @hide Compute the insets that should be consumed by this view and the ones 7906 * that should propagate to those under it. 7907 */ 7908 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7909 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7910 || mAttachInfo == null 7911 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7912 && !mAttachInfo.mOverscanRequested)) { 7913 outLocalInsets.set(inoutInsets); 7914 inoutInsets.set(0, 0, 0, 0); 7915 return true; 7916 } else { 7917 // The application wants to take care of fitting system window for 7918 // the content... however we still need to take care of any overscan here. 7919 final Rect overscan = mAttachInfo.mOverscanInsets; 7920 outLocalInsets.set(overscan); 7921 inoutInsets.left -= overscan.left; 7922 inoutInsets.top -= overscan.top; 7923 inoutInsets.right -= overscan.right; 7924 inoutInsets.bottom -= overscan.bottom; 7925 return false; 7926 } 7927 } 7928 7929 /** 7930 * Compute insets that should be consumed by this view and the ones that should propagate 7931 * to those under it. 7932 * 7933 * @param in Insets currently being processed by this View, likely received as a parameter 7934 * to {@link #onApplyWindowInsets(WindowInsets)}. 7935 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7936 * by this view 7937 * @return Insets that should be passed along to views under this one 7938 */ 7939 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7940 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7941 || mAttachInfo == null 7942 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7943 outLocalInsets.set(in.getSystemWindowInsets()); 7944 return in.consumeSystemWindowInsets(); 7945 } else { 7946 outLocalInsets.set(0, 0, 0, 0); 7947 return in; 7948 } 7949 } 7950 7951 /** 7952 * Sets whether or not this view should account for system screen decorations 7953 * such as the status bar and inset its content; that is, controlling whether 7954 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7955 * executed. See that method for more details. 7956 * 7957 * <p>Note that if you are providing your own implementation of 7958 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7959 * flag to true -- your implementation will be overriding the default 7960 * implementation that checks this flag. 7961 * 7962 * @param fitSystemWindows If true, then the default implementation of 7963 * {@link #fitSystemWindows(Rect)} will be executed. 7964 * 7965 * @attr ref android.R.styleable#View_fitsSystemWindows 7966 * @see #getFitsSystemWindows() 7967 * @see #fitSystemWindows(Rect) 7968 * @see #setSystemUiVisibility(int) 7969 */ 7970 public void setFitsSystemWindows(boolean fitSystemWindows) { 7971 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7972 } 7973 7974 /** 7975 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7976 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7977 * will be executed. 7978 * 7979 * @return {@code true} if the default implementation of 7980 * {@link #fitSystemWindows(Rect)} will be executed. 7981 * 7982 * @attr ref android.R.styleable#View_fitsSystemWindows 7983 * @see #setFitsSystemWindows(boolean) 7984 * @see #fitSystemWindows(Rect) 7985 * @see #setSystemUiVisibility(int) 7986 */ 7987 @ViewDebug.ExportedProperty 7988 public boolean getFitsSystemWindows() { 7989 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7990 } 7991 7992 /** @hide */ 7993 public boolean fitsSystemWindows() { 7994 return getFitsSystemWindows(); 7995 } 7996 7997 /** 7998 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7999 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 8000 */ 8001 @Deprecated 8002 public void requestFitSystemWindows() { 8003 if (mParent != null) { 8004 mParent.requestFitSystemWindows(); 8005 } 8006 } 8007 8008 /** 8009 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 8010 */ 8011 public void requestApplyInsets() { 8012 requestFitSystemWindows(); 8013 } 8014 8015 /** 8016 * For use by PhoneWindow to make its own system window fitting optional. 8017 * @hide 8018 */ 8019 public void makeOptionalFitsSystemWindows() { 8020 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 8021 } 8022 8023 /** 8024 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 8025 * treat them as such. 8026 * @hide 8027 */ 8028 public void getOutsets(Rect outOutsetRect) { 8029 if (mAttachInfo != null) { 8030 outOutsetRect.set(mAttachInfo.mOutsets); 8031 } else { 8032 outOutsetRect.setEmpty(); 8033 } 8034 } 8035 8036 /** 8037 * Returns the visibility status for this view. 8038 * 8039 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8040 * @attr ref android.R.styleable#View_visibility 8041 */ 8042 @ViewDebug.ExportedProperty(mapping = { 8043 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 8044 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 8045 @ViewDebug.IntToString(from = GONE, to = "GONE") 8046 }) 8047 @Visibility 8048 public int getVisibility() { 8049 return mViewFlags & VISIBILITY_MASK; 8050 } 8051 8052 /** 8053 * Set the visibility state of this view. 8054 * 8055 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8056 * @attr ref android.R.styleable#View_visibility 8057 */ 8058 @RemotableViewMethod 8059 public void setVisibility(@Visibility int visibility) { 8060 setFlags(visibility, VISIBILITY_MASK); 8061 } 8062 8063 /** 8064 * Returns the enabled status for this view. The interpretation of the 8065 * enabled state varies by subclass. 8066 * 8067 * @return True if this view is enabled, false otherwise. 8068 */ 8069 @ViewDebug.ExportedProperty 8070 public boolean isEnabled() { 8071 return (mViewFlags & ENABLED_MASK) == ENABLED; 8072 } 8073 8074 /** 8075 * Set the enabled state of this view. The interpretation of the enabled 8076 * state varies by subclass. 8077 * 8078 * @param enabled True if this view is enabled, false otherwise. 8079 */ 8080 @RemotableViewMethod 8081 public void setEnabled(boolean enabled) { 8082 if (enabled == isEnabled()) return; 8083 8084 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8085 8086 /* 8087 * The View most likely has to change its appearance, so refresh 8088 * the drawable state. 8089 */ 8090 refreshDrawableState(); 8091 8092 // Invalidate too, since the default behavior for views is to be 8093 // be drawn at 50% alpha rather than to change the drawable. 8094 invalidate(true); 8095 8096 if (!enabled) { 8097 cancelPendingInputEvents(); 8098 } 8099 } 8100 8101 /** 8102 * Set whether this view can receive the focus. 8103 * 8104 * Setting this to false will also ensure that this view is not focusable 8105 * in touch mode. 8106 * 8107 * @param focusable If true, this view can receive the focus. 8108 * 8109 * @see #setFocusableInTouchMode(boolean) 8110 * @attr ref android.R.styleable#View_focusable 8111 */ 8112 public void setFocusable(boolean focusable) { 8113 if (!focusable) { 8114 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8115 } 8116 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8117 } 8118 8119 /** 8120 * Set whether this view can receive focus while in touch mode. 8121 * 8122 * Setting this to true will also ensure that this view is focusable. 8123 * 8124 * @param focusableInTouchMode If true, this view can receive the focus while 8125 * in touch mode. 8126 * 8127 * @see #setFocusable(boolean) 8128 * @attr ref android.R.styleable#View_focusableInTouchMode 8129 */ 8130 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8131 // Focusable in touch mode should always be set before the focusable flag 8132 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8133 // which, in touch mode, will not successfully request focus on this view 8134 // because the focusable in touch mode flag is not set 8135 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8136 if (focusableInTouchMode) { 8137 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8138 } 8139 } 8140 8141 /** 8142 * Set whether this view should have sound effects enabled for events such as 8143 * clicking and touching. 8144 * 8145 * <p>You may wish to disable sound effects for a view if you already play sounds, 8146 * for instance, a dial key that plays dtmf tones. 8147 * 8148 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8149 * @see #isSoundEffectsEnabled() 8150 * @see #playSoundEffect(int) 8151 * @attr ref android.R.styleable#View_soundEffectsEnabled 8152 */ 8153 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8154 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8155 } 8156 8157 /** 8158 * @return whether this view should have sound effects enabled for events such as 8159 * clicking and touching. 8160 * 8161 * @see #setSoundEffectsEnabled(boolean) 8162 * @see #playSoundEffect(int) 8163 * @attr ref android.R.styleable#View_soundEffectsEnabled 8164 */ 8165 @ViewDebug.ExportedProperty 8166 public boolean isSoundEffectsEnabled() { 8167 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8168 } 8169 8170 /** 8171 * Set whether this view should have haptic feedback for events such as 8172 * long presses. 8173 * 8174 * <p>You may wish to disable haptic feedback if your view already controls 8175 * its own haptic feedback. 8176 * 8177 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8178 * @see #isHapticFeedbackEnabled() 8179 * @see #performHapticFeedback(int) 8180 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8181 */ 8182 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8183 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8184 } 8185 8186 /** 8187 * @return whether this view should have haptic feedback enabled for events 8188 * long presses. 8189 * 8190 * @see #setHapticFeedbackEnabled(boolean) 8191 * @see #performHapticFeedback(int) 8192 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8193 */ 8194 @ViewDebug.ExportedProperty 8195 public boolean isHapticFeedbackEnabled() { 8196 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8197 } 8198 8199 /** 8200 * Returns the layout direction for this view. 8201 * 8202 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8203 * {@link #LAYOUT_DIRECTION_RTL}, 8204 * {@link #LAYOUT_DIRECTION_INHERIT} or 8205 * {@link #LAYOUT_DIRECTION_LOCALE}. 8206 * 8207 * @attr ref android.R.styleable#View_layoutDirection 8208 * 8209 * @hide 8210 */ 8211 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8212 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8213 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8214 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8215 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8216 }) 8217 @LayoutDir 8218 public int getRawLayoutDirection() { 8219 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8220 } 8221 8222 /** 8223 * Set the layout direction for this view. This will propagate a reset of layout direction 8224 * resolution to the view's children and resolve layout direction for this view. 8225 * 8226 * @param layoutDirection the layout direction to set. Should be one of: 8227 * 8228 * {@link #LAYOUT_DIRECTION_LTR}, 8229 * {@link #LAYOUT_DIRECTION_RTL}, 8230 * {@link #LAYOUT_DIRECTION_INHERIT}, 8231 * {@link #LAYOUT_DIRECTION_LOCALE}. 8232 * 8233 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8234 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8235 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8236 * 8237 * @attr ref android.R.styleable#View_layoutDirection 8238 */ 8239 @RemotableViewMethod 8240 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8241 if (getRawLayoutDirection() != layoutDirection) { 8242 // Reset the current layout direction and the resolved one 8243 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8244 resetRtlProperties(); 8245 // Set the new layout direction (filtered) 8246 mPrivateFlags2 |= 8247 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8248 // We need to resolve all RTL properties as they all depend on layout direction 8249 resolveRtlPropertiesIfNeeded(); 8250 requestLayout(); 8251 invalidate(true); 8252 } 8253 } 8254 8255 /** 8256 * Returns the resolved layout direction for this view. 8257 * 8258 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8259 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8260 * 8261 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8262 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8263 * 8264 * @attr ref android.R.styleable#View_layoutDirection 8265 */ 8266 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8267 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8268 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8269 }) 8270 @ResolvedLayoutDir 8271 public int getLayoutDirection() { 8272 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8273 if (targetSdkVersion < JELLY_BEAN_MR1) { 8274 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8275 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8276 } 8277 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8278 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8279 } 8280 8281 /** 8282 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8283 * layout attribute and/or the inherited value from the parent 8284 * 8285 * @return true if the layout is right-to-left. 8286 * 8287 * @hide 8288 */ 8289 @ViewDebug.ExportedProperty(category = "layout") 8290 public boolean isLayoutRtl() { 8291 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8292 } 8293 8294 /** 8295 * Indicates whether the view is currently tracking transient state that the 8296 * app should not need to concern itself with saving and restoring, but that 8297 * the framework should take special note to preserve when possible. 8298 * 8299 * <p>A view with transient state cannot be trivially rebound from an external 8300 * data source, such as an adapter binding item views in a list. This may be 8301 * because the view is performing an animation, tracking user selection 8302 * of content, or similar.</p> 8303 * 8304 * @return true if the view has transient state 8305 */ 8306 @ViewDebug.ExportedProperty(category = "layout") 8307 public boolean hasTransientState() { 8308 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8309 } 8310 8311 /** 8312 * Set whether this view is currently tracking transient state that the 8313 * framework should attempt to preserve when possible. This flag is reference counted, 8314 * so every call to setHasTransientState(true) should be paired with a later call 8315 * to setHasTransientState(false). 8316 * 8317 * <p>A view with transient state cannot be trivially rebound from an external 8318 * data source, such as an adapter binding item views in a list. This may be 8319 * because the view is performing an animation, tracking user selection 8320 * of content, or similar.</p> 8321 * 8322 * @param hasTransientState true if this view has transient state 8323 */ 8324 public void setHasTransientState(boolean hasTransientState) { 8325 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8326 mTransientStateCount - 1; 8327 if (mTransientStateCount < 0) { 8328 mTransientStateCount = 0; 8329 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8330 "unmatched pair of setHasTransientState calls"); 8331 } else if ((hasTransientState && mTransientStateCount == 1) || 8332 (!hasTransientState && mTransientStateCount == 0)) { 8333 // update flag if we've just incremented up from 0 or decremented down to 0 8334 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8335 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8336 if (mParent != null) { 8337 try { 8338 mParent.childHasTransientStateChanged(this, hasTransientState); 8339 } catch (AbstractMethodError e) { 8340 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8341 " does not fully implement ViewParent", e); 8342 } 8343 } 8344 } 8345 } 8346 8347 /** 8348 * Returns true if this view is currently attached to a window. 8349 */ 8350 public boolean isAttachedToWindow() { 8351 return mAttachInfo != null; 8352 } 8353 8354 /** 8355 * Returns true if this view has been through at least one layout since it 8356 * was last attached to or detached from a window. 8357 */ 8358 public boolean isLaidOut() { 8359 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8360 } 8361 8362 /** 8363 * If this view doesn't do any drawing on its own, set this flag to 8364 * allow further optimizations. By default, this flag is not set on 8365 * View, but could be set on some View subclasses such as ViewGroup. 8366 * 8367 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8368 * you should clear this flag. 8369 * 8370 * @param willNotDraw whether or not this View draw on its own 8371 */ 8372 public void setWillNotDraw(boolean willNotDraw) { 8373 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8374 } 8375 8376 /** 8377 * Returns whether or not this View draws on its own. 8378 * 8379 * @return true if this view has nothing to draw, false otherwise 8380 */ 8381 @ViewDebug.ExportedProperty(category = "drawing") 8382 public boolean willNotDraw() { 8383 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8384 } 8385 8386 /** 8387 * When a View's drawing cache is enabled, drawing is redirected to an 8388 * offscreen bitmap. Some views, like an ImageView, must be able to 8389 * bypass this mechanism if they already draw a single bitmap, to avoid 8390 * unnecessary usage of the memory. 8391 * 8392 * @param willNotCacheDrawing true if this view does not cache its 8393 * drawing, false otherwise 8394 */ 8395 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8396 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8397 } 8398 8399 /** 8400 * Returns whether or not this View can cache its drawing or not. 8401 * 8402 * @return true if this view does not cache its drawing, false otherwise 8403 */ 8404 @ViewDebug.ExportedProperty(category = "drawing") 8405 public boolean willNotCacheDrawing() { 8406 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8407 } 8408 8409 /** 8410 * Indicates whether this view reacts to click events or not. 8411 * 8412 * @return true if the view is clickable, false otherwise 8413 * 8414 * @see #setClickable(boolean) 8415 * @attr ref android.R.styleable#View_clickable 8416 */ 8417 @ViewDebug.ExportedProperty 8418 public boolean isClickable() { 8419 return (mViewFlags & CLICKABLE) == CLICKABLE; 8420 } 8421 8422 /** 8423 * Enables or disables click events for this view. When a view 8424 * is clickable it will change its state to "pressed" on every click. 8425 * Subclasses should set the view clickable to visually react to 8426 * user's clicks. 8427 * 8428 * @param clickable true to make the view clickable, false otherwise 8429 * 8430 * @see #isClickable() 8431 * @attr ref android.R.styleable#View_clickable 8432 */ 8433 public void setClickable(boolean clickable) { 8434 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8435 } 8436 8437 /** 8438 * Indicates whether this view reacts to long click events or not. 8439 * 8440 * @return true if the view is long clickable, false otherwise 8441 * 8442 * @see #setLongClickable(boolean) 8443 * @attr ref android.R.styleable#View_longClickable 8444 */ 8445 public boolean isLongClickable() { 8446 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8447 } 8448 8449 /** 8450 * Enables or disables long click events for this view. When a view is long 8451 * clickable it reacts to the user holding down the button for a longer 8452 * duration than a tap. This event can either launch the listener or a 8453 * context menu. 8454 * 8455 * @param longClickable true to make the view long clickable, false otherwise 8456 * @see #isLongClickable() 8457 * @attr ref android.R.styleable#View_longClickable 8458 */ 8459 public void setLongClickable(boolean longClickable) { 8460 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8461 } 8462 8463 /** 8464 * Indicates whether this view reacts to context clicks or not. 8465 * 8466 * @return true if the view is context clickable, false otherwise 8467 * @see #setContextClickable(boolean) 8468 * @attr ref android.R.styleable#View_contextClickable 8469 */ 8470 public boolean isContextClickable() { 8471 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8472 } 8473 8474 /** 8475 * Enables or disables context clicking for this view. This event can launch the listener. 8476 * 8477 * @param contextClickable true to make the view react to a context click, false otherwise 8478 * @see #isContextClickable() 8479 * @attr ref android.R.styleable#View_contextClickable 8480 */ 8481 public void setContextClickable(boolean contextClickable) { 8482 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8483 } 8484 8485 /** 8486 * Sets the pressed state for this view and provides a touch coordinate for 8487 * animation hinting. 8488 * 8489 * @param pressed Pass true to set the View's internal state to "pressed", 8490 * or false to reverts the View's internal state from a 8491 * previously set "pressed" state. 8492 * @param x The x coordinate of the touch that caused the press 8493 * @param y The y coordinate of the touch that caused the press 8494 */ 8495 private void setPressed(boolean pressed, float x, float y) { 8496 if (pressed) { 8497 drawableHotspotChanged(x, y); 8498 } 8499 8500 setPressed(pressed); 8501 } 8502 8503 /** 8504 * Sets the pressed state for this view. 8505 * 8506 * @see #isClickable() 8507 * @see #setClickable(boolean) 8508 * 8509 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8510 * the View's internal state from a previously set "pressed" state. 8511 */ 8512 public void setPressed(boolean pressed) { 8513 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8514 8515 if (pressed) { 8516 mPrivateFlags |= PFLAG_PRESSED; 8517 } else { 8518 mPrivateFlags &= ~PFLAG_PRESSED; 8519 } 8520 8521 if (needsRefresh) { 8522 refreshDrawableState(); 8523 } 8524 dispatchSetPressed(pressed); 8525 } 8526 8527 /** 8528 * Dispatch setPressed to all of this View's children. 8529 * 8530 * @see #setPressed(boolean) 8531 * 8532 * @param pressed The new pressed state 8533 */ 8534 protected void dispatchSetPressed(boolean pressed) { 8535 } 8536 8537 /** 8538 * Indicates whether the view is currently in pressed state. Unless 8539 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8540 * the pressed state. 8541 * 8542 * @see #setPressed(boolean) 8543 * @see #isClickable() 8544 * @see #setClickable(boolean) 8545 * 8546 * @return true if the view is currently pressed, false otherwise 8547 */ 8548 @ViewDebug.ExportedProperty 8549 public boolean isPressed() { 8550 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8551 } 8552 8553 /** 8554 * @hide 8555 * Indicates whether this view will participate in data collection through 8556 * {@link ViewStructure}. If true, it will not provide any data 8557 * for itself or its children. If false, the normal data collection will be allowed. 8558 * 8559 * @return Returns false if assist data collection is not blocked, else true. 8560 * 8561 * @see #setAssistBlocked(boolean) 8562 * @attr ref android.R.styleable#View_assistBlocked 8563 */ 8564 public boolean isAssistBlocked() { 8565 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8566 } 8567 8568 /** 8569 * @hide 8570 * Controls whether assist data collection from this view and its children is enabled 8571 * (that is, whether {@link #onProvideStructure} and 8572 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8573 * allowing normal assist collection. Setting this to false will disable assist collection. 8574 * 8575 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8576 * (the default) to allow it. 8577 * 8578 * @see #isAssistBlocked() 8579 * @see #onProvideStructure 8580 * @see #onProvideVirtualStructure 8581 * @attr ref android.R.styleable#View_assistBlocked 8582 */ 8583 public void setAssistBlocked(boolean enabled) { 8584 if (enabled) { 8585 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8586 } else { 8587 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8588 } 8589 } 8590 8591 /** 8592 * Indicates whether this view will save its state (that is, 8593 * whether its {@link #onSaveInstanceState} method will be called). 8594 * 8595 * @return Returns true if the view state saving is enabled, else false. 8596 * 8597 * @see #setSaveEnabled(boolean) 8598 * @attr ref android.R.styleable#View_saveEnabled 8599 */ 8600 public boolean isSaveEnabled() { 8601 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8602 } 8603 8604 /** 8605 * Controls whether the saving of this view's state is 8606 * enabled (that is, whether its {@link #onSaveInstanceState} method 8607 * will be called). Note that even if freezing is enabled, the 8608 * view still must have an id assigned to it (via {@link #setId(int)}) 8609 * for its state to be saved. This flag can only disable the 8610 * saving of this view; any child views may still have their state saved. 8611 * 8612 * @param enabled Set to false to <em>disable</em> state saving, or true 8613 * (the default) to allow it. 8614 * 8615 * @see #isSaveEnabled() 8616 * @see #setId(int) 8617 * @see #onSaveInstanceState() 8618 * @attr ref android.R.styleable#View_saveEnabled 8619 */ 8620 public void setSaveEnabled(boolean enabled) { 8621 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8622 } 8623 8624 /** 8625 * Gets whether the framework should discard touches when the view's 8626 * window is obscured by another visible window. 8627 * Refer to the {@link View} security documentation for more details. 8628 * 8629 * @return True if touch filtering is enabled. 8630 * 8631 * @see #setFilterTouchesWhenObscured(boolean) 8632 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8633 */ 8634 @ViewDebug.ExportedProperty 8635 public boolean getFilterTouchesWhenObscured() { 8636 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8637 } 8638 8639 /** 8640 * Sets whether the framework should discard touches when the view's 8641 * window is obscured by another visible window. 8642 * Refer to the {@link View} security documentation for more details. 8643 * 8644 * @param enabled True if touch filtering should be enabled. 8645 * 8646 * @see #getFilterTouchesWhenObscured 8647 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8648 */ 8649 public void setFilterTouchesWhenObscured(boolean enabled) { 8650 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8651 FILTER_TOUCHES_WHEN_OBSCURED); 8652 } 8653 8654 /** 8655 * Indicates whether the entire hierarchy under this view will save its 8656 * state when a state saving traversal occurs from its parent. The default 8657 * is true; if false, these views will not be saved unless 8658 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8659 * 8660 * @return Returns true if the view state saving from parent is enabled, else false. 8661 * 8662 * @see #setSaveFromParentEnabled(boolean) 8663 */ 8664 public boolean isSaveFromParentEnabled() { 8665 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8666 } 8667 8668 /** 8669 * Controls whether the entire hierarchy under this view will save its 8670 * state when a state saving traversal occurs from its parent. The default 8671 * is true; if false, these views will not be saved unless 8672 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8673 * 8674 * @param enabled Set to false to <em>disable</em> state saving, or true 8675 * (the default) to allow it. 8676 * 8677 * @see #isSaveFromParentEnabled() 8678 * @see #setId(int) 8679 * @see #onSaveInstanceState() 8680 */ 8681 public void setSaveFromParentEnabled(boolean enabled) { 8682 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8683 } 8684 8685 8686 /** 8687 * Returns whether this View is able to take focus. 8688 * 8689 * @return True if this view can take focus, or false otherwise. 8690 * @attr ref android.R.styleable#View_focusable 8691 */ 8692 @ViewDebug.ExportedProperty(category = "focus") 8693 public final boolean isFocusable() { 8694 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8695 } 8696 8697 /** 8698 * When a view is focusable, it may not want to take focus when in touch mode. 8699 * For example, a button would like focus when the user is navigating via a D-pad 8700 * so that the user can click on it, but once the user starts touching the screen, 8701 * the button shouldn't take focus 8702 * @return Whether the view is focusable in touch mode. 8703 * @attr ref android.R.styleable#View_focusableInTouchMode 8704 */ 8705 @ViewDebug.ExportedProperty 8706 public final boolean isFocusableInTouchMode() { 8707 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8708 } 8709 8710 /** 8711 * Find the nearest view in the specified direction that can take focus. 8712 * This does not actually give focus to that view. 8713 * 8714 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8715 * 8716 * @return The nearest focusable in the specified direction, or null if none 8717 * can be found. 8718 */ 8719 public View focusSearch(@FocusRealDirection int direction) { 8720 if (mParent != null) { 8721 return mParent.focusSearch(this, direction); 8722 } else { 8723 return null; 8724 } 8725 } 8726 8727 /** 8728 * This method is the last chance for the focused view and its ancestors to 8729 * respond to an arrow key. This is called when the focused view did not 8730 * consume the key internally, nor could the view system find a new view in 8731 * the requested direction to give focus to. 8732 * 8733 * @param focused The currently focused view. 8734 * @param direction The direction focus wants to move. One of FOCUS_UP, 8735 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8736 * @return True if the this view consumed this unhandled move. 8737 */ 8738 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8739 return false; 8740 } 8741 8742 /** 8743 * If a user manually specified the next view id for a particular direction, 8744 * use the root to look up the view. 8745 * @param root The root view of the hierarchy containing this view. 8746 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8747 * or FOCUS_BACKWARD. 8748 * @return The user specified next view, or null if there is none. 8749 */ 8750 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8751 switch (direction) { 8752 case FOCUS_LEFT: 8753 if (mNextFocusLeftId == View.NO_ID) return null; 8754 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8755 case FOCUS_RIGHT: 8756 if (mNextFocusRightId == View.NO_ID) return null; 8757 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8758 case FOCUS_UP: 8759 if (mNextFocusUpId == View.NO_ID) return null; 8760 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8761 case FOCUS_DOWN: 8762 if (mNextFocusDownId == View.NO_ID) return null; 8763 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8764 case FOCUS_FORWARD: 8765 if (mNextFocusForwardId == View.NO_ID) return null; 8766 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8767 case FOCUS_BACKWARD: { 8768 if (mID == View.NO_ID) return null; 8769 final int id = mID; 8770 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8771 @Override 8772 public boolean apply(View t) { 8773 return t.mNextFocusForwardId == id; 8774 } 8775 }); 8776 } 8777 } 8778 return null; 8779 } 8780 8781 private View findViewInsideOutShouldExist(View root, int id) { 8782 if (mMatchIdPredicate == null) { 8783 mMatchIdPredicate = new MatchIdPredicate(); 8784 } 8785 mMatchIdPredicate.mId = id; 8786 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8787 if (result == null) { 8788 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8789 } 8790 return result; 8791 } 8792 8793 /** 8794 * Find and return all focusable views that are descendants of this view, 8795 * possibly including this view if it is focusable itself. 8796 * 8797 * @param direction The direction of the focus 8798 * @return A list of focusable views 8799 */ 8800 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8801 ArrayList<View> result = new ArrayList<View>(24); 8802 addFocusables(result, direction); 8803 return result; 8804 } 8805 8806 /** 8807 * Add any focusable views that are descendants of this view (possibly 8808 * including this view if it is focusable itself) to views. If we are in touch mode, 8809 * only add views that are also focusable in touch mode. 8810 * 8811 * @param views Focusable views found so far 8812 * @param direction The direction of the focus 8813 */ 8814 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8815 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 8816 } 8817 8818 /** 8819 * Adds any focusable views that are descendants of this view (possibly 8820 * including this view if it is focusable itself) to views. This method 8821 * adds all focusable views regardless if we are in touch mode or 8822 * only views focusable in touch mode if we are in touch mode or 8823 * only views that can take accessibility focus if accessibility is enabled 8824 * depending on the focusable mode parameter. 8825 * 8826 * @param views Focusable views found so far or null if all we are interested is 8827 * the number of focusables. 8828 * @param direction The direction of the focus. 8829 * @param focusableMode The type of focusables to be added. 8830 * 8831 * @see #FOCUSABLES_ALL 8832 * @see #FOCUSABLES_TOUCH_MODE 8833 */ 8834 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8835 @FocusableMode int focusableMode) { 8836 if (views == null) { 8837 return; 8838 } 8839 if (!isFocusable()) { 8840 return; 8841 } 8842 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8843 && !isFocusableInTouchMode()) { 8844 return; 8845 } 8846 views.add(this); 8847 } 8848 8849 /** 8850 * Finds the Views that contain given text. The containment is case insensitive. 8851 * The search is performed by either the text that the View renders or the content 8852 * description that describes the view for accessibility purposes and the view does 8853 * not render or both. Clients can specify how the search is to be performed via 8854 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8855 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8856 * 8857 * @param outViews The output list of matching Views. 8858 * @param searched The text to match against. 8859 * 8860 * @see #FIND_VIEWS_WITH_TEXT 8861 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8862 * @see #setContentDescription(CharSequence) 8863 */ 8864 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8865 @FindViewFlags int flags) { 8866 if (getAccessibilityNodeProvider() != null) { 8867 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8868 outViews.add(this); 8869 } 8870 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8871 && (searched != null && searched.length() > 0) 8872 && (mContentDescription != null && mContentDescription.length() > 0)) { 8873 String searchedLowerCase = searched.toString().toLowerCase(); 8874 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8875 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8876 outViews.add(this); 8877 } 8878 } 8879 } 8880 8881 /** 8882 * Find and return all touchable views that are descendants of this view, 8883 * possibly including this view if it is touchable itself. 8884 * 8885 * @return A list of touchable views 8886 */ 8887 public ArrayList<View> getTouchables() { 8888 ArrayList<View> result = new ArrayList<View>(); 8889 addTouchables(result); 8890 return result; 8891 } 8892 8893 /** 8894 * Add any touchable views that are descendants of this view (possibly 8895 * including this view if it is touchable itself) to views. 8896 * 8897 * @param views Touchable views found so far 8898 */ 8899 public void addTouchables(ArrayList<View> views) { 8900 final int viewFlags = mViewFlags; 8901 8902 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8903 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8904 && (viewFlags & ENABLED_MASK) == ENABLED) { 8905 views.add(this); 8906 } 8907 } 8908 8909 /** 8910 * Returns whether this View is accessibility focused. 8911 * 8912 * @return True if this View is accessibility focused. 8913 */ 8914 public boolean isAccessibilityFocused() { 8915 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8916 } 8917 8918 /** 8919 * Call this to try to give accessibility focus to this view. 8920 * 8921 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8922 * returns false or the view is no visible or the view already has accessibility 8923 * focus. 8924 * 8925 * See also {@link #focusSearch(int)}, which is what you call to say that you 8926 * have focus, and you want your parent to look for the next one. 8927 * 8928 * @return Whether this view actually took accessibility focus. 8929 * 8930 * @hide 8931 */ 8932 public boolean requestAccessibilityFocus() { 8933 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8934 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8935 return false; 8936 } 8937 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8938 return false; 8939 } 8940 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8941 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8942 ViewRootImpl viewRootImpl = getViewRootImpl(); 8943 if (viewRootImpl != null) { 8944 viewRootImpl.setAccessibilityFocus(this, null); 8945 } 8946 invalidate(); 8947 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8948 return true; 8949 } 8950 return false; 8951 } 8952 8953 /** 8954 * Call this to try to clear accessibility focus of this view. 8955 * 8956 * See also {@link #focusSearch(int)}, which is what you call to say that you 8957 * have focus, and you want your parent to look for the next one. 8958 * 8959 * @hide 8960 */ 8961 public void clearAccessibilityFocus() { 8962 clearAccessibilityFocusNoCallbacks(0); 8963 8964 // Clear the global reference of accessibility focus if this view or 8965 // any of its descendants had accessibility focus. This will NOT send 8966 // an event or update internal state if focus is cleared from a 8967 // descendant view, which may leave views in inconsistent states. 8968 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8969 if (viewRootImpl != null) { 8970 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8971 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8972 viewRootImpl.setAccessibilityFocus(null, null); 8973 } 8974 } 8975 } 8976 8977 private void sendAccessibilityHoverEvent(int eventType) { 8978 // Since we are not delivering to a client accessibility events from not 8979 // important views (unless the clinet request that) we need to fire the 8980 // event from the deepest view exposed to the client. As a consequence if 8981 // the user crosses a not exposed view the client will see enter and exit 8982 // of the exposed predecessor followed by and enter and exit of that same 8983 // predecessor when entering and exiting the not exposed descendant. This 8984 // is fine since the client has a clear idea which view is hovered at the 8985 // price of a couple more events being sent. This is a simple and 8986 // working solution. 8987 View source = this; 8988 while (true) { 8989 if (source.includeForAccessibility()) { 8990 source.sendAccessibilityEvent(eventType); 8991 return; 8992 } 8993 ViewParent parent = source.getParent(); 8994 if (parent instanceof View) { 8995 source = (View) parent; 8996 } else { 8997 return; 8998 } 8999 } 9000 } 9001 9002 /** 9003 * Clears accessibility focus without calling any callback methods 9004 * normally invoked in {@link #clearAccessibilityFocus()}. This method 9005 * is used separately from that one for clearing accessibility focus when 9006 * giving this focus to another view. 9007 * 9008 * @param action The action, if any, that led to focus being cleared. Set to 9009 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 9010 * the window. 9011 */ 9012 void clearAccessibilityFocusNoCallbacks(int action) { 9013 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 9014 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 9015 invalidate(); 9016 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9017 AccessibilityEvent event = AccessibilityEvent.obtain( 9018 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 9019 event.setAction(action); 9020 if (mAccessibilityDelegate != null) { 9021 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 9022 } else { 9023 sendAccessibilityEventUnchecked(event); 9024 } 9025 } 9026 } 9027 } 9028 9029 /** 9030 * Call this to try to give focus to a specific view or to one of its 9031 * descendants. 9032 * 9033 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9034 * false), or if it is focusable and it is not focusable in touch mode 9035 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9036 * 9037 * See also {@link #focusSearch(int)}, which is what you call to say that you 9038 * have focus, and you want your parent to look for the next one. 9039 * 9040 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 9041 * {@link #FOCUS_DOWN} and <code>null</code>. 9042 * 9043 * @return Whether this view or one of its descendants actually took focus. 9044 */ 9045 public final boolean requestFocus() { 9046 return requestFocus(View.FOCUS_DOWN); 9047 } 9048 9049 /** 9050 * Call this to try to give focus to a specific view or to one of its 9051 * descendants and give it a hint about what direction focus is heading. 9052 * 9053 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9054 * false), or if it is focusable and it is not focusable in touch mode 9055 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9056 * 9057 * See also {@link #focusSearch(int)}, which is what you call to say that you 9058 * have focus, and you want your parent to look for the next one. 9059 * 9060 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 9061 * <code>null</code> set for the previously focused rectangle. 9062 * 9063 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9064 * @return Whether this view or one of its descendants actually took focus. 9065 */ 9066 public final boolean requestFocus(int direction) { 9067 return requestFocus(direction, null); 9068 } 9069 9070 /** 9071 * Call this to try to give focus to a specific view or to one of its descendants 9072 * and give it hints about the direction and a specific rectangle that the focus 9073 * is coming from. The rectangle can help give larger views a finer grained hint 9074 * about where focus is coming from, and therefore, where to show selection, or 9075 * forward focus change internally. 9076 * 9077 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9078 * false), or if it is focusable and it is not focusable in touch mode 9079 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9080 * 9081 * A View will not take focus if it is not visible. 9082 * 9083 * A View will not take focus if one of its parents has 9084 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9085 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9086 * 9087 * See also {@link #focusSearch(int)}, which is what you call to say that you 9088 * have focus, and you want your parent to look for the next one. 9089 * 9090 * You may wish to override this method if your custom {@link View} has an internal 9091 * {@link View} that it wishes to forward the request to. 9092 * 9093 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9094 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9095 * to give a finer grained hint about where focus is coming from. May be null 9096 * if there is no hint. 9097 * @return Whether this view or one of its descendants actually took focus. 9098 */ 9099 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9100 return requestFocusNoSearch(direction, previouslyFocusedRect); 9101 } 9102 9103 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9104 // need to be focusable 9105 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9106 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9107 return false; 9108 } 9109 9110 // need to be focusable in touch mode if in touch mode 9111 if (isInTouchMode() && 9112 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9113 return false; 9114 } 9115 9116 // need to not have any parents blocking us 9117 if (hasAncestorThatBlocksDescendantFocus()) { 9118 return false; 9119 } 9120 9121 handleFocusGainInternal(direction, previouslyFocusedRect); 9122 return true; 9123 } 9124 9125 /** 9126 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9127 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9128 * touch mode to request focus when they are touched. 9129 * 9130 * @return Whether this view or one of its descendants actually took focus. 9131 * 9132 * @see #isInTouchMode() 9133 * 9134 */ 9135 public final boolean requestFocusFromTouch() { 9136 // Leave touch mode if we need to 9137 if (isInTouchMode()) { 9138 ViewRootImpl viewRoot = getViewRootImpl(); 9139 if (viewRoot != null) { 9140 viewRoot.ensureTouchMode(false); 9141 } 9142 } 9143 return requestFocus(View.FOCUS_DOWN); 9144 } 9145 9146 /** 9147 * @return Whether any ancestor of this view blocks descendant focus. 9148 */ 9149 private boolean hasAncestorThatBlocksDescendantFocus() { 9150 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9151 ViewParent ancestor = mParent; 9152 while (ancestor instanceof ViewGroup) { 9153 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9154 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9155 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9156 return true; 9157 } else { 9158 ancestor = vgAncestor.getParent(); 9159 } 9160 } 9161 return false; 9162 } 9163 9164 /** 9165 * Gets the mode for determining whether this View is important for accessibility. 9166 * A view is important for accessibility if it fires accessibility events and if it 9167 * is reported to accessibility services that query the screen. 9168 * 9169 * @return The mode for determining whether a view is important for accessibility, one 9170 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 9171 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 9172 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 9173 * 9174 * @attr ref android.R.styleable#View_importantForAccessibility 9175 * 9176 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9177 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9178 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9179 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9180 */ 9181 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9182 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9183 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9184 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9185 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9186 to = "noHideDescendants") 9187 }) 9188 public int getImportantForAccessibility() { 9189 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9190 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9191 } 9192 9193 /** 9194 * Sets the live region mode for this view. This indicates to accessibility 9195 * services whether they should automatically notify the user about changes 9196 * to the view's content description or text, or to the content descriptions 9197 * or text of the view's children (where applicable). 9198 * <p> 9199 * For example, in a login screen with a TextView that displays an "incorrect 9200 * password" notification, that view should be marked as a live region with 9201 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9202 * <p> 9203 * To disable change notifications for this view, use 9204 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9205 * mode for most views. 9206 * <p> 9207 * To indicate that the user should be notified of changes, use 9208 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9209 * <p> 9210 * If the view's changes should interrupt ongoing speech and notify the user 9211 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9212 * 9213 * @param mode The live region mode for this view, one of: 9214 * <ul> 9215 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9216 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9217 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9218 * </ul> 9219 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9220 */ 9221 public void setAccessibilityLiveRegion(int mode) { 9222 if (mode != getAccessibilityLiveRegion()) { 9223 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9224 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9225 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9226 notifyViewAccessibilityStateChangedIfNeeded( 9227 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9228 } 9229 } 9230 9231 /** 9232 * Gets the live region mode for this View. 9233 * 9234 * @return The live region mode for the view. 9235 * 9236 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9237 * 9238 * @see #setAccessibilityLiveRegion(int) 9239 */ 9240 public int getAccessibilityLiveRegion() { 9241 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9242 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9243 } 9244 9245 /** 9246 * Sets how to determine whether this view is important for accessibility 9247 * which is if it fires accessibility events and if it is reported to 9248 * accessibility services that query the screen. 9249 * 9250 * @param mode How to determine whether this view is important for accessibility. 9251 * 9252 * @attr ref android.R.styleable#View_importantForAccessibility 9253 * 9254 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9255 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9256 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9257 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9258 */ 9259 public void setImportantForAccessibility(int mode) { 9260 final int oldMode = getImportantForAccessibility(); 9261 if (mode != oldMode) { 9262 final boolean hideDescendants = 9263 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9264 9265 // If this node or its descendants are no longer important, try to 9266 // clear accessibility focus. 9267 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9268 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9269 if (focusHost != null) { 9270 focusHost.clearAccessibilityFocus(); 9271 } 9272 } 9273 9274 // If we're moving between AUTO and another state, we might not need 9275 // to send a subtree changed notification. We'll store the computed 9276 // importance, since we'll need to check it later to make sure. 9277 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9278 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9279 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9280 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9281 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9282 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9283 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9284 notifySubtreeAccessibilityStateChangedIfNeeded(); 9285 } else { 9286 notifyViewAccessibilityStateChangedIfNeeded( 9287 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9288 } 9289 } 9290 } 9291 9292 /** 9293 * Returns the view within this view's hierarchy that is hosting 9294 * accessibility focus. 9295 * 9296 * @param searchDescendants whether to search for focus in descendant views 9297 * @return the view hosting accessibility focus, or {@code null} 9298 */ 9299 private View findAccessibilityFocusHost(boolean searchDescendants) { 9300 if (isAccessibilityFocusedViewOrHost()) { 9301 return this; 9302 } 9303 9304 if (searchDescendants) { 9305 final ViewRootImpl viewRoot = getViewRootImpl(); 9306 if (viewRoot != null) { 9307 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9308 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9309 return focusHost; 9310 } 9311 } 9312 } 9313 9314 return null; 9315 } 9316 9317 /** 9318 * Computes whether this view should be exposed for accessibility. In 9319 * general, views that are interactive or provide information are exposed 9320 * while views that serve only as containers are hidden. 9321 * <p> 9322 * If an ancestor of this view has importance 9323 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9324 * returns <code>false</code>. 9325 * <p> 9326 * Otherwise, the value is computed according to the view's 9327 * {@link #getImportantForAccessibility()} value: 9328 * <ol> 9329 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9330 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9331 * </code> 9332 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9333 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9334 * view satisfies any of the following: 9335 * <ul> 9336 * <li>Is actionable, e.g. {@link #isClickable()}, 9337 * {@link #isLongClickable()}, or {@link #isFocusable()} 9338 * <li>Has an {@link AccessibilityDelegate} 9339 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9340 * {@link OnKeyListener}, etc. 9341 * <li>Is an accessibility live region, e.g. 9342 * {@link #getAccessibilityLiveRegion()} is not 9343 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9344 * </ul> 9345 * </ol> 9346 * 9347 * @return Whether the view is exposed for accessibility. 9348 * @see #setImportantForAccessibility(int) 9349 * @see #getImportantForAccessibility() 9350 */ 9351 public boolean isImportantForAccessibility() { 9352 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9353 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9354 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9355 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9356 return false; 9357 } 9358 9359 // Check parent mode to ensure we're not hidden. 9360 ViewParent parent = mParent; 9361 while (parent instanceof View) { 9362 if (((View) parent).getImportantForAccessibility() 9363 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9364 return false; 9365 } 9366 parent = parent.getParent(); 9367 } 9368 9369 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9370 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9371 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9372 } 9373 9374 /** 9375 * Gets the parent for accessibility purposes. Note that the parent for 9376 * accessibility is not necessary the immediate parent. It is the first 9377 * predecessor that is important for accessibility. 9378 * 9379 * @return The parent for accessibility purposes. 9380 */ 9381 public ViewParent getParentForAccessibility() { 9382 if (mParent instanceof View) { 9383 View parentView = (View) mParent; 9384 if (parentView.includeForAccessibility()) { 9385 return mParent; 9386 } else { 9387 return mParent.getParentForAccessibility(); 9388 } 9389 } 9390 return null; 9391 } 9392 9393 /** 9394 * Adds the children of this View relevant for accessibility to the given list 9395 * as output. Since some Views are not important for accessibility the added 9396 * child views are not necessarily direct children of this view, rather they are 9397 * the first level of descendants important for accessibility. 9398 * 9399 * @param outChildren The output list that will receive children for accessibility. 9400 */ 9401 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9402 9403 } 9404 9405 /** 9406 * Whether to regard this view for accessibility. A view is regarded for 9407 * accessibility if it is important for accessibility or the querying 9408 * accessibility service has explicitly requested that view not 9409 * important for accessibility are regarded. 9410 * 9411 * @return Whether to regard the view for accessibility. 9412 * 9413 * @hide 9414 */ 9415 public boolean includeForAccessibility() { 9416 if (mAttachInfo != null) { 9417 return (mAttachInfo.mAccessibilityFetchFlags 9418 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9419 || isImportantForAccessibility(); 9420 } 9421 return false; 9422 } 9423 9424 /** 9425 * Returns whether the View is considered actionable from 9426 * accessibility perspective. Such view are important for 9427 * accessibility. 9428 * 9429 * @return True if the view is actionable for accessibility. 9430 * 9431 * @hide 9432 */ 9433 public boolean isActionableForAccessibility() { 9434 return (isClickable() || isLongClickable() || isFocusable()); 9435 } 9436 9437 /** 9438 * Returns whether the View has registered callbacks which makes it 9439 * important for accessibility. 9440 * 9441 * @return True if the view is actionable for accessibility. 9442 */ 9443 private boolean hasListenersForAccessibility() { 9444 ListenerInfo info = getListenerInfo(); 9445 return mTouchDelegate != null || info.mOnKeyListener != null 9446 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9447 || info.mOnHoverListener != null || info.mOnDragListener != null; 9448 } 9449 9450 /** 9451 * Notifies that the accessibility state of this view changed. The change 9452 * is local to this view and does not represent structural changes such 9453 * as children and parent. For example, the view became focusable. The 9454 * notification is at at most once every 9455 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9456 * to avoid unnecessary load to the system. Also once a view has a pending 9457 * notification this method is a NOP until the notification has been sent. 9458 * 9459 * @hide 9460 */ 9461 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9462 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9463 return; 9464 } 9465 if (mSendViewStateChangedAccessibilityEvent == null) { 9466 mSendViewStateChangedAccessibilityEvent = 9467 new SendViewStateChangedAccessibilityEvent(); 9468 } 9469 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9470 } 9471 9472 /** 9473 * Notifies that the accessibility state of this view changed. The change 9474 * is *not* local to this view and does represent structural changes such 9475 * as children and parent. For example, the view size changed. The 9476 * notification is at at most once every 9477 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9478 * to avoid unnecessary load to the system. Also once a view has a pending 9479 * notification this method is a NOP until the notification has been sent. 9480 * 9481 * @hide 9482 */ 9483 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9484 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9485 return; 9486 } 9487 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9488 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9489 if (mParent != null) { 9490 try { 9491 mParent.notifySubtreeAccessibilityStateChanged( 9492 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9493 } catch (AbstractMethodError e) { 9494 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9495 " does not fully implement ViewParent", e); 9496 } 9497 } 9498 } 9499 } 9500 9501 /** 9502 * Change the visibility of the View without triggering any other changes. This is 9503 * important for transitions, where visibility changes should not adjust focus or 9504 * trigger a new layout. This is only used when the visibility has already been changed 9505 * and we need a transient value during an animation. When the animation completes, 9506 * the original visibility value is always restored. 9507 * 9508 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9509 * @hide 9510 */ 9511 public void setTransitionVisibility(@Visibility int visibility) { 9512 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9513 } 9514 9515 /** 9516 * Reset the flag indicating the accessibility state of the subtree rooted 9517 * at this view changed. 9518 */ 9519 void resetSubtreeAccessibilityStateChanged() { 9520 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9521 } 9522 9523 /** 9524 * Report an accessibility action to this view's parents for delegated processing. 9525 * 9526 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9527 * call this method to delegate an accessibility action to a supporting parent. If the parent 9528 * returns true from its 9529 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9530 * method this method will return true to signify that the action was consumed.</p> 9531 * 9532 * <p>This method is useful for implementing nested scrolling child views. If 9533 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9534 * a custom view implementation may invoke this method to allow a parent to consume the 9535 * scroll first. If this method returns true the custom view should skip its own scrolling 9536 * behavior.</p> 9537 * 9538 * @param action Accessibility action to delegate 9539 * @param arguments Optional action arguments 9540 * @return true if the action was consumed by a parent 9541 */ 9542 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9543 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9544 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9545 return true; 9546 } 9547 } 9548 return false; 9549 } 9550 9551 /** 9552 * Performs the specified accessibility action on the view. For 9553 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9554 * <p> 9555 * If an {@link AccessibilityDelegate} has been specified via calling 9556 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9557 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9558 * is responsible for handling this call. 9559 * </p> 9560 * 9561 * <p>The default implementation will delegate 9562 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9563 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9564 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9565 * 9566 * @param action The action to perform. 9567 * @param arguments Optional action arguments. 9568 * @return Whether the action was performed. 9569 */ 9570 public boolean performAccessibilityAction(int action, Bundle arguments) { 9571 if (mAccessibilityDelegate != null) { 9572 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9573 } else { 9574 return performAccessibilityActionInternal(action, arguments); 9575 } 9576 } 9577 9578 /** 9579 * @see #performAccessibilityAction(int, Bundle) 9580 * 9581 * Note: Called from the default {@link AccessibilityDelegate}. 9582 * 9583 * @hide 9584 */ 9585 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9586 if (isNestedScrollingEnabled() 9587 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9588 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9589 || action == R.id.accessibilityActionScrollUp 9590 || action == R.id.accessibilityActionScrollLeft 9591 || action == R.id.accessibilityActionScrollDown 9592 || action == R.id.accessibilityActionScrollRight)) { 9593 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9594 return true; 9595 } 9596 } 9597 9598 switch (action) { 9599 case AccessibilityNodeInfo.ACTION_CLICK: { 9600 if (isClickable()) { 9601 performClick(); 9602 return true; 9603 } 9604 } break; 9605 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9606 if (isLongClickable()) { 9607 performLongClick(); 9608 return true; 9609 } 9610 } break; 9611 case AccessibilityNodeInfo.ACTION_FOCUS: { 9612 if (!hasFocus()) { 9613 // Get out of touch mode since accessibility 9614 // wants to move focus around. 9615 getViewRootImpl().ensureTouchMode(false); 9616 return requestFocus(); 9617 } 9618 } break; 9619 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9620 if (hasFocus()) { 9621 clearFocus(); 9622 return !isFocused(); 9623 } 9624 } break; 9625 case AccessibilityNodeInfo.ACTION_SELECT: { 9626 if (!isSelected()) { 9627 setSelected(true); 9628 return isSelected(); 9629 } 9630 } break; 9631 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9632 if (isSelected()) { 9633 setSelected(false); 9634 return !isSelected(); 9635 } 9636 } break; 9637 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9638 if (!isAccessibilityFocused()) { 9639 return requestAccessibilityFocus(); 9640 } 9641 } break; 9642 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9643 if (isAccessibilityFocused()) { 9644 clearAccessibilityFocus(); 9645 return true; 9646 } 9647 } break; 9648 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9649 if (arguments != null) { 9650 final int granularity = arguments.getInt( 9651 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9652 final boolean extendSelection = arguments.getBoolean( 9653 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9654 return traverseAtGranularity(granularity, true, extendSelection); 9655 } 9656 } break; 9657 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9658 if (arguments != null) { 9659 final int granularity = arguments.getInt( 9660 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9661 final boolean extendSelection = arguments.getBoolean( 9662 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9663 return traverseAtGranularity(granularity, false, extendSelection); 9664 } 9665 } break; 9666 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9667 CharSequence text = getIterableTextForAccessibility(); 9668 if (text == null) { 9669 return false; 9670 } 9671 final int start = (arguments != null) ? arguments.getInt( 9672 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9673 final int end = (arguments != null) ? arguments.getInt( 9674 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9675 // Only cursor position can be specified (selection length == 0) 9676 if ((getAccessibilitySelectionStart() != start 9677 || getAccessibilitySelectionEnd() != end) 9678 && (start == end)) { 9679 setAccessibilitySelection(start, end); 9680 notifyViewAccessibilityStateChangedIfNeeded( 9681 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9682 return true; 9683 } 9684 } break; 9685 case R.id.accessibilityActionShowOnScreen: { 9686 if (mAttachInfo != null) { 9687 final Rect r = mAttachInfo.mTmpInvalRect; 9688 getDrawingRect(r); 9689 return requestRectangleOnScreen(r, true); 9690 } 9691 } break; 9692 case R.id.accessibilityActionContextClick: { 9693 if (isContextClickable()) { 9694 performContextClick(); 9695 return true; 9696 } 9697 } break; 9698 } 9699 return false; 9700 } 9701 9702 private boolean traverseAtGranularity(int granularity, boolean forward, 9703 boolean extendSelection) { 9704 CharSequence text = getIterableTextForAccessibility(); 9705 if (text == null || text.length() == 0) { 9706 return false; 9707 } 9708 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9709 if (iterator == null) { 9710 return false; 9711 } 9712 int current = getAccessibilitySelectionEnd(); 9713 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9714 current = forward ? 0 : text.length(); 9715 } 9716 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9717 if (range == null) { 9718 return false; 9719 } 9720 final int segmentStart = range[0]; 9721 final int segmentEnd = range[1]; 9722 int selectionStart; 9723 int selectionEnd; 9724 if (extendSelection && isAccessibilitySelectionExtendable()) { 9725 selectionStart = getAccessibilitySelectionStart(); 9726 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9727 selectionStart = forward ? segmentStart : segmentEnd; 9728 } 9729 selectionEnd = forward ? segmentEnd : segmentStart; 9730 } else { 9731 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9732 } 9733 setAccessibilitySelection(selectionStart, selectionEnd); 9734 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9735 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9736 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9737 return true; 9738 } 9739 9740 /** 9741 * Gets the text reported for accessibility purposes. 9742 * 9743 * @return The accessibility text. 9744 * 9745 * @hide 9746 */ 9747 public CharSequence getIterableTextForAccessibility() { 9748 return getContentDescription(); 9749 } 9750 9751 /** 9752 * Gets whether accessibility selection can be extended. 9753 * 9754 * @return If selection is extensible. 9755 * 9756 * @hide 9757 */ 9758 public boolean isAccessibilitySelectionExtendable() { 9759 return false; 9760 } 9761 9762 /** 9763 * @hide 9764 */ 9765 public int getAccessibilitySelectionStart() { 9766 return mAccessibilityCursorPosition; 9767 } 9768 9769 /** 9770 * @hide 9771 */ 9772 public int getAccessibilitySelectionEnd() { 9773 return getAccessibilitySelectionStart(); 9774 } 9775 9776 /** 9777 * @hide 9778 */ 9779 public void setAccessibilitySelection(int start, int end) { 9780 if (start == end && end == mAccessibilityCursorPosition) { 9781 return; 9782 } 9783 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9784 mAccessibilityCursorPosition = start; 9785 } else { 9786 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9787 } 9788 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9789 } 9790 9791 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9792 int fromIndex, int toIndex) { 9793 if (mParent == null) { 9794 return; 9795 } 9796 AccessibilityEvent event = AccessibilityEvent.obtain( 9797 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9798 onInitializeAccessibilityEvent(event); 9799 onPopulateAccessibilityEvent(event); 9800 event.setFromIndex(fromIndex); 9801 event.setToIndex(toIndex); 9802 event.setAction(action); 9803 event.setMovementGranularity(granularity); 9804 mParent.requestSendAccessibilityEvent(this, event); 9805 } 9806 9807 /** 9808 * @hide 9809 */ 9810 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9811 switch (granularity) { 9812 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9813 CharSequence text = getIterableTextForAccessibility(); 9814 if (text != null && text.length() > 0) { 9815 CharacterTextSegmentIterator iterator = 9816 CharacterTextSegmentIterator.getInstance( 9817 mContext.getResources().getConfiguration().locale); 9818 iterator.initialize(text.toString()); 9819 return iterator; 9820 } 9821 } break; 9822 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9823 CharSequence text = getIterableTextForAccessibility(); 9824 if (text != null && text.length() > 0) { 9825 WordTextSegmentIterator iterator = 9826 WordTextSegmentIterator.getInstance( 9827 mContext.getResources().getConfiguration().locale); 9828 iterator.initialize(text.toString()); 9829 return iterator; 9830 } 9831 } break; 9832 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9833 CharSequence text = getIterableTextForAccessibility(); 9834 if (text != null && text.length() > 0) { 9835 ParagraphTextSegmentIterator iterator = 9836 ParagraphTextSegmentIterator.getInstance(); 9837 iterator.initialize(text.toString()); 9838 return iterator; 9839 } 9840 } break; 9841 } 9842 return null; 9843 } 9844 9845 /** 9846 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 9847 * and {@link #onFinishTemporaryDetach()}. 9848 * 9849 * <p>This method always returns {@code true} when called directly or indirectly from 9850 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 9851 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 9852 * <ul> 9853 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 9854 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 9855 * </ul> 9856 * </p> 9857 * 9858 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9859 * and {@link #onFinishTemporaryDetach()}. 9860 */ 9861 public final boolean isTemporarilyDetached() { 9862 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9863 } 9864 9865 /** 9866 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9867 * a container View. 9868 */ 9869 @CallSuper 9870 public void dispatchStartTemporaryDetach() { 9871 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9872 onStartTemporaryDetach(); 9873 } 9874 9875 /** 9876 * This is called when a container is going to temporarily detach a child, with 9877 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9878 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9879 * {@link #onDetachedFromWindow()} when the container is done. 9880 */ 9881 public void onStartTemporaryDetach() { 9882 removeUnsetPressCallback(); 9883 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9884 } 9885 9886 /** 9887 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9888 * a container View. 9889 */ 9890 @CallSuper 9891 public void dispatchFinishTemporaryDetach() { 9892 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9893 onFinishTemporaryDetach(); 9894 if (hasWindowFocus() && hasFocus()) { 9895 InputMethodManager.getInstance().focusIn(this); 9896 } 9897 } 9898 9899 /** 9900 * Called after {@link #onStartTemporaryDetach} when the container is done 9901 * changing the view. 9902 */ 9903 public void onFinishTemporaryDetach() { 9904 } 9905 9906 /** 9907 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9908 * for this view's window. Returns null if the view is not currently attached 9909 * to the window. Normally you will not need to use this directly, but 9910 * just use the standard high-level event callbacks like 9911 * {@link #onKeyDown(int, KeyEvent)}. 9912 */ 9913 public KeyEvent.DispatcherState getKeyDispatcherState() { 9914 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9915 } 9916 9917 /** 9918 * Dispatch a key event before it is processed by any input method 9919 * associated with the view hierarchy. This can be used to intercept 9920 * key events in special situations before the IME consumes them; a 9921 * typical example would be handling the BACK key to update the application's 9922 * UI instead of allowing the IME to see it and close itself. 9923 * 9924 * @param event The key event to be dispatched. 9925 * @return True if the event was handled, false otherwise. 9926 */ 9927 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9928 return onKeyPreIme(event.getKeyCode(), event); 9929 } 9930 9931 /** 9932 * Dispatch a key event to the next view on the focus path. This path runs 9933 * from the top of the view tree down to the currently focused view. If this 9934 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9935 * the next node down the focus path. This method also fires any key 9936 * listeners. 9937 * 9938 * @param event The key event to be dispatched. 9939 * @return True if the event was handled, false otherwise. 9940 */ 9941 public boolean dispatchKeyEvent(KeyEvent event) { 9942 if (mInputEventConsistencyVerifier != null) { 9943 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9944 } 9945 9946 // Give any attached key listener a first crack at the event. 9947 //noinspection SimplifiableIfStatement 9948 ListenerInfo li = mListenerInfo; 9949 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9950 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9951 return true; 9952 } 9953 9954 if (event.dispatch(this, mAttachInfo != null 9955 ? mAttachInfo.mKeyDispatchState : null, this)) { 9956 return true; 9957 } 9958 9959 if (mInputEventConsistencyVerifier != null) { 9960 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9961 } 9962 return false; 9963 } 9964 9965 /** 9966 * Dispatches a key shortcut event. 9967 * 9968 * @param event The key event to be dispatched. 9969 * @return True if the event was handled by the view, false otherwise. 9970 */ 9971 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9972 return onKeyShortcut(event.getKeyCode(), event); 9973 } 9974 9975 /** 9976 * Pass the touch screen motion event down to the target view, or this 9977 * view if it is the target. 9978 * 9979 * @param event The motion event to be dispatched. 9980 * @return True if the event was handled by the view, false otherwise. 9981 */ 9982 public boolean dispatchTouchEvent(MotionEvent event) { 9983 // If the event should be handled by accessibility focus first. 9984 if (event.isTargetAccessibilityFocus()) { 9985 // We don't have focus or no virtual descendant has it, do not handle the event. 9986 if (!isAccessibilityFocusedViewOrHost()) { 9987 return false; 9988 } 9989 // We have focus and got the event, then use normal event dispatch. 9990 event.setTargetAccessibilityFocus(false); 9991 } 9992 9993 boolean result = false; 9994 9995 if (mInputEventConsistencyVerifier != null) { 9996 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9997 } 9998 9999 final int actionMasked = event.getActionMasked(); 10000 if (actionMasked == MotionEvent.ACTION_DOWN) { 10001 // Defensive cleanup for new gesture 10002 stopNestedScroll(); 10003 } 10004 10005 if (onFilterTouchEventForSecurity(event)) { 10006 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 10007 result = true; 10008 } 10009 //noinspection SimplifiableIfStatement 10010 ListenerInfo li = mListenerInfo; 10011 if (li != null && li.mOnTouchListener != null 10012 && (mViewFlags & ENABLED_MASK) == ENABLED 10013 && li.mOnTouchListener.onTouch(this, event)) { 10014 result = true; 10015 } 10016 10017 if (!result && onTouchEvent(event)) { 10018 result = true; 10019 } 10020 } 10021 10022 if (!result && mInputEventConsistencyVerifier != null) { 10023 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10024 } 10025 10026 // Clean up after nested scrolls if this is the end of a gesture; 10027 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 10028 // of the gesture. 10029 if (actionMasked == MotionEvent.ACTION_UP || 10030 actionMasked == MotionEvent.ACTION_CANCEL || 10031 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 10032 stopNestedScroll(); 10033 } 10034 10035 return result; 10036 } 10037 10038 boolean isAccessibilityFocusedViewOrHost() { 10039 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 10040 .getAccessibilityFocusedHost() == this); 10041 } 10042 10043 /** 10044 * Filter the touch event to apply security policies. 10045 * 10046 * @param event The motion event to be filtered. 10047 * @return True if the event should be dispatched, false if the event should be dropped. 10048 * 10049 * @see #getFilterTouchesWhenObscured 10050 */ 10051 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 10052 //noinspection RedundantIfStatement 10053 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 10054 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 10055 // Window is obscured, drop this touch. 10056 return false; 10057 } 10058 return true; 10059 } 10060 10061 /** 10062 * Pass a trackball motion event down to the focused view. 10063 * 10064 * @param event The motion event to be dispatched. 10065 * @return True if the event was handled by the view, false otherwise. 10066 */ 10067 public boolean dispatchTrackballEvent(MotionEvent event) { 10068 if (mInputEventConsistencyVerifier != null) { 10069 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 10070 } 10071 10072 return onTrackballEvent(event); 10073 } 10074 10075 /** 10076 * Dispatch a generic motion event. 10077 * <p> 10078 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10079 * are delivered to the view under the pointer. All other generic motion events are 10080 * delivered to the focused view. Hover events are handled specially and are delivered 10081 * to {@link #onHoverEvent(MotionEvent)}. 10082 * </p> 10083 * 10084 * @param event The motion event to be dispatched. 10085 * @return True if the event was handled by the view, false otherwise. 10086 */ 10087 public boolean dispatchGenericMotionEvent(MotionEvent event) { 10088 if (mInputEventConsistencyVerifier != null) { 10089 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10090 } 10091 10092 final int source = event.getSource(); 10093 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10094 final int action = event.getAction(); 10095 if (action == MotionEvent.ACTION_HOVER_ENTER 10096 || action == MotionEvent.ACTION_HOVER_MOVE 10097 || action == MotionEvent.ACTION_HOVER_EXIT) { 10098 if (dispatchHoverEvent(event)) { 10099 return true; 10100 } 10101 } else if (dispatchGenericPointerEvent(event)) { 10102 return true; 10103 } 10104 } else if (dispatchGenericFocusedEvent(event)) { 10105 return true; 10106 } 10107 10108 if (dispatchGenericMotionEventInternal(event)) { 10109 return true; 10110 } 10111 10112 if (mInputEventConsistencyVerifier != null) { 10113 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10114 } 10115 return false; 10116 } 10117 10118 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10119 //noinspection SimplifiableIfStatement 10120 ListenerInfo li = mListenerInfo; 10121 if (li != null && li.mOnGenericMotionListener != null 10122 && (mViewFlags & ENABLED_MASK) == ENABLED 10123 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10124 return true; 10125 } 10126 10127 if (onGenericMotionEvent(event)) { 10128 return true; 10129 } 10130 10131 final int actionButton = event.getActionButton(); 10132 switch (event.getActionMasked()) { 10133 case MotionEvent.ACTION_BUTTON_PRESS: 10134 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10135 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10136 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10137 if (performContextClick(event.getX(), event.getY())) { 10138 mInContextButtonPress = true; 10139 setPressed(true, event.getX(), event.getY()); 10140 removeTapCallback(); 10141 removeLongPressCallback(); 10142 return true; 10143 } 10144 } 10145 break; 10146 10147 case MotionEvent.ACTION_BUTTON_RELEASE: 10148 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10149 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10150 mInContextButtonPress = false; 10151 mIgnoreNextUpEvent = true; 10152 } 10153 break; 10154 } 10155 10156 if (mInputEventConsistencyVerifier != null) { 10157 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10158 } 10159 return false; 10160 } 10161 10162 /** 10163 * Dispatch a hover event. 10164 * <p> 10165 * Do not call this method directly. 10166 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10167 * </p> 10168 * 10169 * @param event The motion event to be dispatched. 10170 * @return True if the event was handled by the view, false otherwise. 10171 */ 10172 protected boolean dispatchHoverEvent(MotionEvent event) { 10173 ListenerInfo li = mListenerInfo; 10174 //noinspection SimplifiableIfStatement 10175 if (li != null && li.mOnHoverListener != null 10176 && (mViewFlags & ENABLED_MASK) == ENABLED 10177 && li.mOnHoverListener.onHover(this, event)) { 10178 return true; 10179 } 10180 10181 return onHoverEvent(event); 10182 } 10183 10184 /** 10185 * Returns true if the view has a child to which it has recently sent 10186 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10187 * it does not have a hovered child, then it must be the innermost hovered view. 10188 * @hide 10189 */ 10190 protected boolean hasHoveredChild() { 10191 return false; 10192 } 10193 10194 /** 10195 * Dispatch a generic motion event to the view under the first pointer. 10196 * <p> 10197 * Do not call this method directly. 10198 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10199 * </p> 10200 * 10201 * @param event The motion event to be dispatched. 10202 * @return True if the event was handled by the view, false otherwise. 10203 */ 10204 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10205 return false; 10206 } 10207 10208 /** 10209 * Dispatch a generic motion event to the currently focused view. 10210 * <p> 10211 * Do not call this method directly. 10212 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10213 * </p> 10214 * 10215 * @param event The motion event to be dispatched. 10216 * @return True if the event was handled by the view, false otherwise. 10217 */ 10218 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10219 return false; 10220 } 10221 10222 /** 10223 * Dispatch a pointer event. 10224 * <p> 10225 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10226 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10227 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10228 * and should not be expected to handle other pointing device features. 10229 * </p> 10230 * 10231 * @param event The motion event to be dispatched. 10232 * @return True if the event was handled by the view, false otherwise. 10233 * @hide 10234 */ 10235 public final boolean dispatchPointerEvent(MotionEvent event) { 10236 if (event.isTouchEvent()) { 10237 return dispatchTouchEvent(event); 10238 } else { 10239 return dispatchGenericMotionEvent(event); 10240 } 10241 } 10242 10243 /** 10244 * Called when the window containing this view gains or loses window focus. 10245 * ViewGroups should override to route to their children. 10246 * 10247 * @param hasFocus True if the window containing this view now has focus, 10248 * false otherwise. 10249 */ 10250 public void dispatchWindowFocusChanged(boolean hasFocus) { 10251 onWindowFocusChanged(hasFocus); 10252 } 10253 10254 /** 10255 * Called when the window containing this view gains or loses focus. Note 10256 * that this is separate from view focus: to receive key events, both 10257 * your view and its window must have focus. If a window is displayed 10258 * on top of yours that takes input focus, then your own window will lose 10259 * focus but the view focus will remain unchanged. 10260 * 10261 * @param hasWindowFocus True if the window containing this view now has 10262 * focus, false otherwise. 10263 */ 10264 public void onWindowFocusChanged(boolean hasWindowFocus) { 10265 InputMethodManager imm = InputMethodManager.peekInstance(); 10266 if (!hasWindowFocus) { 10267 if (isPressed()) { 10268 setPressed(false); 10269 } 10270 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10271 imm.focusOut(this); 10272 } 10273 removeLongPressCallback(); 10274 removeTapCallback(); 10275 onFocusLost(); 10276 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10277 imm.focusIn(this); 10278 } 10279 refreshDrawableState(); 10280 } 10281 10282 /** 10283 * Returns true if this view is in a window that currently has window focus. 10284 * Note that this is not the same as the view itself having focus. 10285 * 10286 * @return True if this view is in a window that currently has window focus. 10287 */ 10288 public boolean hasWindowFocus() { 10289 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10290 } 10291 10292 /** 10293 * Dispatch a view visibility change down the view hierarchy. 10294 * ViewGroups should override to route to their children. 10295 * @param changedView The view whose visibility changed. Could be 'this' or 10296 * an ancestor view. 10297 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10298 * {@link #INVISIBLE} or {@link #GONE}. 10299 */ 10300 protected void dispatchVisibilityChanged(@NonNull View changedView, 10301 @Visibility int visibility) { 10302 onVisibilityChanged(changedView, visibility); 10303 } 10304 10305 /** 10306 * Called when the visibility of the view or an ancestor of the view has 10307 * changed. 10308 * 10309 * @param changedView The view whose visibility changed. May be 10310 * {@code this} or an ancestor view. 10311 * @param visibility The new visibility, one of {@link #VISIBLE}, 10312 * {@link #INVISIBLE} or {@link #GONE}. 10313 */ 10314 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10315 } 10316 10317 /** 10318 * Dispatch a hint about whether this view is displayed. For instance, when 10319 * a View moves out of the screen, it might receives a display hint indicating 10320 * the view is not displayed. Applications should not <em>rely</em> on this hint 10321 * as there is no guarantee that they will receive one. 10322 * 10323 * @param hint A hint about whether or not this view is displayed: 10324 * {@link #VISIBLE} or {@link #INVISIBLE}. 10325 */ 10326 public void dispatchDisplayHint(@Visibility int hint) { 10327 onDisplayHint(hint); 10328 } 10329 10330 /** 10331 * Gives this view a hint about whether is displayed or not. For instance, when 10332 * a View moves out of the screen, it might receives a display hint indicating 10333 * the view is not displayed. Applications should not <em>rely</em> on this hint 10334 * as there is no guarantee that they will receive one. 10335 * 10336 * @param hint A hint about whether or not this view is displayed: 10337 * {@link #VISIBLE} or {@link #INVISIBLE}. 10338 */ 10339 protected void onDisplayHint(@Visibility int hint) { 10340 } 10341 10342 /** 10343 * Dispatch a window visibility change down the view hierarchy. 10344 * ViewGroups should override to route to their children. 10345 * 10346 * @param visibility The new visibility of the window. 10347 * 10348 * @see #onWindowVisibilityChanged(int) 10349 */ 10350 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10351 onWindowVisibilityChanged(visibility); 10352 } 10353 10354 /** 10355 * Called when the window containing has change its visibility 10356 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10357 * that this tells you whether or not your window is being made visible 10358 * to the window manager; this does <em>not</em> tell you whether or not 10359 * your window is obscured by other windows on the screen, even if it 10360 * is itself visible. 10361 * 10362 * @param visibility The new visibility of the window. 10363 */ 10364 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10365 if (visibility == VISIBLE) { 10366 initialAwakenScrollBars(); 10367 } 10368 } 10369 10370 /** 10371 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10372 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10373 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10374 * 10375 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10376 * ancestors or by window visibility 10377 * @return true if this view is visible to the user, not counting clipping or overlapping 10378 */ 10379 boolean dispatchVisibilityAggregated(boolean isVisible) { 10380 final boolean thisVisible = getVisibility() == VISIBLE; 10381 // If we're not visible but something is telling us we are, ignore it. 10382 if (thisVisible || !isVisible) { 10383 onVisibilityAggregated(isVisible); 10384 } 10385 return thisVisible && isVisible; 10386 } 10387 10388 /** 10389 * Called when the user-visibility of this View is potentially affected by a change 10390 * to this view itself, an ancestor view or the window this view is attached to. 10391 * 10392 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10393 * and this view's window is also visible 10394 */ 10395 @CallSuper 10396 public void onVisibilityAggregated(boolean isVisible) { 10397 if (isVisible && mAttachInfo != null) { 10398 initialAwakenScrollBars(); 10399 } 10400 10401 final Drawable dr = mBackground; 10402 if (dr != null && isVisible != dr.isVisible()) { 10403 dr.setVisible(isVisible, false); 10404 } 10405 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10406 if (fg != null && isVisible != fg.isVisible()) { 10407 fg.setVisible(isVisible, false); 10408 } 10409 } 10410 10411 /** 10412 * Returns the current visibility of the window this view is attached to 10413 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10414 * 10415 * @return Returns the current visibility of the view's window. 10416 */ 10417 @Visibility 10418 public int getWindowVisibility() { 10419 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10420 } 10421 10422 /** 10423 * Retrieve the overall visible display size in which the window this view is 10424 * attached to has been positioned in. This takes into account screen 10425 * decorations above the window, for both cases where the window itself 10426 * is being position inside of them or the window is being placed under 10427 * then and covered insets are used for the window to position its content 10428 * inside. In effect, this tells you the available area where content can 10429 * be placed and remain visible to users. 10430 * 10431 * <p>This function requires an IPC back to the window manager to retrieve 10432 * the requested information, so should not be used in performance critical 10433 * code like drawing. 10434 * 10435 * @param outRect Filled in with the visible display frame. If the view 10436 * is not attached to a window, this is simply the raw display size. 10437 */ 10438 public void getWindowVisibleDisplayFrame(Rect outRect) { 10439 if (mAttachInfo != null) { 10440 try { 10441 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10442 } catch (RemoteException e) { 10443 return; 10444 } 10445 // XXX This is really broken, and probably all needs to be done 10446 // in the window manager, and we need to know more about whether 10447 // we want the area behind or in front of the IME. 10448 final Rect insets = mAttachInfo.mVisibleInsets; 10449 outRect.left += insets.left; 10450 outRect.top += insets.top; 10451 outRect.right -= insets.right; 10452 outRect.bottom -= insets.bottom; 10453 return; 10454 } 10455 // The view is not attached to a display so we don't have a context. 10456 // Make a best guess about the display size. 10457 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10458 d.getRectSize(outRect); 10459 } 10460 10461 /** 10462 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10463 * is currently in without any insets. 10464 * 10465 * @hide 10466 */ 10467 public void getWindowDisplayFrame(Rect outRect) { 10468 if (mAttachInfo != null) { 10469 try { 10470 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10471 } catch (RemoteException e) { 10472 return; 10473 } 10474 return; 10475 } 10476 // The view is not attached to a display so we don't have a context. 10477 // Make a best guess about the display size. 10478 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10479 d.getRectSize(outRect); 10480 } 10481 10482 /** 10483 * Dispatch a notification about a resource configuration change down 10484 * the view hierarchy. 10485 * ViewGroups should override to route to their children. 10486 * 10487 * @param newConfig The new resource configuration. 10488 * 10489 * @see #onConfigurationChanged(android.content.res.Configuration) 10490 */ 10491 public void dispatchConfigurationChanged(Configuration newConfig) { 10492 onConfigurationChanged(newConfig); 10493 } 10494 10495 /** 10496 * Called when the current configuration of the resources being used 10497 * by the application have changed. You can use this to decide when 10498 * to reload resources that can changed based on orientation and other 10499 * configuration characteristics. You only need to use this if you are 10500 * not relying on the normal {@link android.app.Activity} mechanism of 10501 * recreating the activity instance upon a configuration change. 10502 * 10503 * @param newConfig The new resource configuration. 10504 */ 10505 protected void onConfigurationChanged(Configuration newConfig) { 10506 } 10507 10508 /** 10509 * Private function to aggregate all per-view attributes in to the view 10510 * root. 10511 */ 10512 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10513 performCollectViewAttributes(attachInfo, visibility); 10514 } 10515 10516 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10517 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10518 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10519 attachInfo.mKeepScreenOn = true; 10520 } 10521 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10522 ListenerInfo li = mListenerInfo; 10523 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10524 attachInfo.mHasSystemUiListeners = true; 10525 } 10526 } 10527 } 10528 10529 void needGlobalAttributesUpdate(boolean force) { 10530 final AttachInfo ai = mAttachInfo; 10531 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10532 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10533 || ai.mHasSystemUiListeners) { 10534 ai.mRecomputeGlobalAttributes = true; 10535 } 10536 } 10537 } 10538 10539 /** 10540 * Returns whether the device is currently in touch mode. Touch mode is entered 10541 * once the user begins interacting with the device by touch, and affects various 10542 * things like whether focus is always visible to the user. 10543 * 10544 * @return Whether the device is in touch mode. 10545 */ 10546 @ViewDebug.ExportedProperty 10547 public boolean isInTouchMode() { 10548 if (mAttachInfo != null) { 10549 return mAttachInfo.mInTouchMode; 10550 } else { 10551 return ViewRootImpl.isInTouchMode(); 10552 } 10553 } 10554 10555 /** 10556 * Returns the context the view is running in, through which it can 10557 * access the current theme, resources, etc. 10558 * 10559 * @return The view's Context. 10560 */ 10561 @ViewDebug.CapturedViewProperty 10562 public final Context getContext() { 10563 return mContext; 10564 } 10565 10566 /** 10567 * Handle a key event before it is processed by any input method 10568 * associated with the view hierarchy. This can be used to intercept 10569 * key events in special situations before the IME consumes them; a 10570 * typical example would be handling the BACK key to update the application's 10571 * UI instead of allowing the IME to see it and close itself. 10572 * 10573 * @param keyCode The value in event.getKeyCode(). 10574 * @param event Description of the key event. 10575 * @return If you handled the event, return true. If you want to allow the 10576 * event to be handled by the next receiver, return false. 10577 */ 10578 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10579 return false; 10580 } 10581 10582 /** 10583 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10584 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10585 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10586 * is released, if the view is enabled and clickable. 10587 * <p> 10588 * Key presses in software keyboards will generally NOT trigger this 10589 * listener, although some may elect to do so in some situations. Do not 10590 * rely on this to catch software key presses. 10591 * 10592 * @param keyCode a key code that represents the button pressed, from 10593 * {@link android.view.KeyEvent} 10594 * @param event the KeyEvent object that defines the button action 10595 */ 10596 public boolean onKeyDown(int keyCode, KeyEvent event) { 10597 if (KeyEvent.isConfirmKey(keyCode)) { 10598 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10599 return true; 10600 } 10601 10602 // Long clickable items don't necessarily have to be clickable. 10603 if (((mViewFlags & CLICKABLE) == CLICKABLE 10604 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10605 && (event.getRepeatCount() == 0)) { 10606 // For the purposes of menu anchoring and drawable hotspots, 10607 // key events are considered to be at the center of the view. 10608 final float x = getWidth() / 2f; 10609 final float y = getHeight() / 2f; 10610 setPressed(true, x, y); 10611 checkForLongClick(0, x, y); 10612 return true; 10613 } 10614 } 10615 10616 return false; 10617 } 10618 10619 /** 10620 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10621 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10622 * the event). 10623 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10624 * although some may elect to do so in some situations. Do not rely on this to 10625 * catch software key presses. 10626 */ 10627 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10628 return false; 10629 } 10630 10631 /** 10632 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10633 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10634 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10635 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10636 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10637 * although some may elect to do so in some situations. Do not rely on this to 10638 * catch software key presses. 10639 * 10640 * @param keyCode A key code that represents the button pressed, from 10641 * {@link android.view.KeyEvent}. 10642 * @param event The KeyEvent object that defines the button action. 10643 */ 10644 public boolean onKeyUp(int keyCode, KeyEvent event) { 10645 if (KeyEvent.isConfirmKey(keyCode)) { 10646 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10647 return true; 10648 } 10649 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10650 setPressed(false); 10651 10652 if (!mHasPerformedLongPress) { 10653 // This is a tap, so remove the longpress check 10654 removeLongPressCallback(); 10655 return performClick(); 10656 } 10657 } 10658 } 10659 return false; 10660 } 10661 10662 /** 10663 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10664 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10665 * the event). 10666 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10667 * although some may elect to do so in some situations. Do not rely on this to 10668 * catch software key presses. 10669 * 10670 * @param keyCode A key code that represents the button pressed, from 10671 * {@link android.view.KeyEvent}. 10672 * @param repeatCount The number of times the action was made. 10673 * @param event The KeyEvent object that defines the button action. 10674 */ 10675 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10676 return false; 10677 } 10678 10679 /** 10680 * Called on the focused view when a key shortcut event is not handled. 10681 * Override this method to implement local key shortcuts for the View. 10682 * Key shortcuts can also be implemented by setting the 10683 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10684 * 10685 * @param keyCode The value in event.getKeyCode(). 10686 * @param event Description of the key event. 10687 * @return If you handled the event, return true. If you want to allow the 10688 * event to be handled by the next receiver, return false. 10689 */ 10690 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10691 return false; 10692 } 10693 10694 /** 10695 * Check whether the called view is a text editor, in which case it 10696 * would make sense to automatically display a soft input window for 10697 * it. Subclasses should override this if they implement 10698 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10699 * a call on that method would return a non-null InputConnection, and 10700 * they are really a first-class editor that the user would normally 10701 * start typing on when the go into a window containing your view. 10702 * 10703 * <p>The default implementation always returns false. This does 10704 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10705 * will not be called or the user can not otherwise perform edits on your 10706 * view; it is just a hint to the system that this is not the primary 10707 * purpose of this view. 10708 * 10709 * @return Returns true if this view is a text editor, else false. 10710 */ 10711 public boolean onCheckIsTextEditor() { 10712 return false; 10713 } 10714 10715 /** 10716 * Create a new InputConnection for an InputMethod to interact 10717 * with the view. The default implementation returns null, since it doesn't 10718 * support input methods. You can override this to implement such support. 10719 * This is only needed for views that take focus and text input. 10720 * 10721 * <p>When implementing this, you probably also want to implement 10722 * {@link #onCheckIsTextEditor()} to indicate you will return a 10723 * non-null InputConnection.</p> 10724 * 10725 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10726 * object correctly and in its entirety, so that the connected IME can rely 10727 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10728 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10729 * must be filled in with the correct cursor position for IMEs to work correctly 10730 * with your application.</p> 10731 * 10732 * @param outAttrs Fill in with attribute information about the connection. 10733 */ 10734 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10735 return null; 10736 } 10737 10738 /** 10739 * Called by the {@link android.view.inputmethod.InputMethodManager} 10740 * when a view who is not the current 10741 * input connection target is trying to make a call on the manager. The 10742 * default implementation returns false; you can override this to return 10743 * true for certain views if you are performing InputConnection proxying 10744 * to them. 10745 * @param view The View that is making the InputMethodManager call. 10746 * @return Return true to allow the call, false to reject. 10747 */ 10748 public boolean checkInputConnectionProxy(View view) { 10749 return false; 10750 } 10751 10752 /** 10753 * Show the context menu for this view. It is not safe to hold on to the 10754 * menu after returning from this method. 10755 * 10756 * You should normally not overload this method. Overload 10757 * {@link #onCreateContextMenu(ContextMenu)} or define an 10758 * {@link OnCreateContextMenuListener} to add items to the context menu. 10759 * 10760 * @param menu The context menu to populate 10761 */ 10762 public void createContextMenu(ContextMenu menu) { 10763 ContextMenuInfo menuInfo = getContextMenuInfo(); 10764 10765 // Sets the current menu info so all items added to menu will have 10766 // my extra info set. 10767 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10768 10769 onCreateContextMenu(menu); 10770 ListenerInfo li = mListenerInfo; 10771 if (li != null && li.mOnCreateContextMenuListener != null) { 10772 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10773 } 10774 10775 // Clear the extra information so subsequent items that aren't mine don't 10776 // have my extra info. 10777 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10778 10779 if (mParent != null) { 10780 mParent.createContextMenu(menu); 10781 } 10782 } 10783 10784 /** 10785 * Views should implement this if they have extra information to associate 10786 * with the context menu. The return result is supplied as a parameter to 10787 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10788 * callback. 10789 * 10790 * @return Extra information about the item for which the context menu 10791 * should be shown. This information will vary across different 10792 * subclasses of View. 10793 */ 10794 protected ContextMenuInfo getContextMenuInfo() { 10795 return null; 10796 } 10797 10798 /** 10799 * Views should implement this if the view itself is going to add items to 10800 * the context menu. 10801 * 10802 * @param menu the context menu to populate 10803 */ 10804 protected void onCreateContextMenu(ContextMenu menu) { 10805 } 10806 10807 /** 10808 * Implement this method to handle trackball motion events. The 10809 * <em>relative</em> movement of the trackball since the last event 10810 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10811 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10812 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10813 * they will often be fractional values, representing the more fine-grained 10814 * movement information available from a trackball). 10815 * 10816 * @param event The motion event. 10817 * @return True if the event was handled, false otherwise. 10818 */ 10819 public boolean onTrackballEvent(MotionEvent event) { 10820 return false; 10821 } 10822 10823 /** 10824 * Implement this method to handle generic motion events. 10825 * <p> 10826 * Generic motion events describe joystick movements, mouse hovers, track pad 10827 * touches, scroll wheel movements and other input events. The 10828 * {@link MotionEvent#getSource() source} of the motion event specifies 10829 * the class of input that was received. Implementations of this method 10830 * must examine the bits in the source before processing the event. 10831 * The following code example shows how this is done. 10832 * </p><p> 10833 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10834 * are delivered to the view under the pointer. All other generic motion events are 10835 * delivered to the focused view. 10836 * </p> 10837 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10838 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10839 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10840 * // process the joystick movement... 10841 * return true; 10842 * } 10843 * } 10844 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10845 * switch (event.getAction()) { 10846 * case MotionEvent.ACTION_HOVER_MOVE: 10847 * // process the mouse hover movement... 10848 * return true; 10849 * case MotionEvent.ACTION_SCROLL: 10850 * // process the scroll wheel movement... 10851 * return true; 10852 * } 10853 * } 10854 * return super.onGenericMotionEvent(event); 10855 * }</pre> 10856 * 10857 * @param event The generic motion event being processed. 10858 * @return True if the event was handled, false otherwise. 10859 */ 10860 public boolean onGenericMotionEvent(MotionEvent event) { 10861 return false; 10862 } 10863 10864 /** 10865 * Implement this method to handle hover events. 10866 * <p> 10867 * This method is called whenever a pointer is hovering into, over, or out of the 10868 * bounds of a view and the view is not currently being touched. 10869 * Hover events are represented as pointer events with action 10870 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10871 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10872 * </p> 10873 * <ul> 10874 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10875 * when the pointer enters the bounds of the view.</li> 10876 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10877 * when the pointer has already entered the bounds of the view and has moved.</li> 10878 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10879 * when the pointer has exited the bounds of the view or when the pointer is 10880 * about to go down due to a button click, tap, or similar user action that 10881 * causes the view to be touched.</li> 10882 * </ul> 10883 * <p> 10884 * The view should implement this method to return true to indicate that it is 10885 * handling the hover event, such as by changing its drawable state. 10886 * </p><p> 10887 * The default implementation calls {@link #setHovered} to update the hovered state 10888 * of the view when a hover enter or hover exit event is received, if the view 10889 * is enabled and is clickable. The default implementation also sends hover 10890 * accessibility events. 10891 * </p> 10892 * 10893 * @param event The motion event that describes the hover. 10894 * @return True if the view handled the hover event. 10895 * 10896 * @see #isHovered 10897 * @see #setHovered 10898 * @see #onHoverChanged 10899 */ 10900 public boolean onHoverEvent(MotionEvent event) { 10901 // The root view may receive hover (or touch) events that are outside the bounds of 10902 // the window. This code ensures that we only send accessibility events for 10903 // hovers that are actually within the bounds of the root view. 10904 final int action = event.getActionMasked(); 10905 if (!mSendingHoverAccessibilityEvents) { 10906 if ((action == MotionEvent.ACTION_HOVER_ENTER 10907 || action == MotionEvent.ACTION_HOVER_MOVE) 10908 && !hasHoveredChild() 10909 && pointInView(event.getX(), event.getY())) { 10910 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10911 mSendingHoverAccessibilityEvents = true; 10912 } 10913 } else { 10914 if (action == MotionEvent.ACTION_HOVER_EXIT 10915 || (action == MotionEvent.ACTION_MOVE 10916 && !pointInView(event.getX(), event.getY()))) { 10917 mSendingHoverAccessibilityEvents = false; 10918 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10919 } 10920 } 10921 10922 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10923 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10924 && isOnScrollbar(event.getX(), event.getY())) { 10925 awakenScrollBars(); 10926 } 10927 if (isHoverable()) { 10928 switch (action) { 10929 case MotionEvent.ACTION_HOVER_ENTER: 10930 setHovered(true); 10931 break; 10932 case MotionEvent.ACTION_HOVER_EXIT: 10933 setHovered(false); 10934 break; 10935 } 10936 10937 // Dispatch the event to onGenericMotionEvent before returning true. 10938 // This is to provide compatibility with existing applications that 10939 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10940 // break because of the new default handling for hoverable views 10941 // in onHoverEvent. 10942 // Note that onGenericMotionEvent will be called by default when 10943 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10944 dispatchGenericMotionEventInternal(event); 10945 // The event was already handled by calling setHovered(), so always 10946 // return true. 10947 return true; 10948 } 10949 10950 return false; 10951 } 10952 10953 /** 10954 * Returns true if the view should handle {@link #onHoverEvent} 10955 * by calling {@link #setHovered} to change its hovered state. 10956 * 10957 * @return True if the view is hoverable. 10958 */ 10959 private boolean isHoverable() { 10960 final int viewFlags = mViewFlags; 10961 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10962 return false; 10963 } 10964 10965 return (viewFlags & CLICKABLE) == CLICKABLE 10966 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10967 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10968 } 10969 10970 /** 10971 * Returns true if the view is currently hovered. 10972 * 10973 * @return True if the view is currently hovered. 10974 * 10975 * @see #setHovered 10976 * @see #onHoverChanged 10977 */ 10978 @ViewDebug.ExportedProperty 10979 public boolean isHovered() { 10980 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10981 } 10982 10983 /** 10984 * Sets whether the view is currently hovered. 10985 * <p> 10986 * Calling this method also changes the drawable state of the view. This 10987 * enables the view to react to hover by using different drawable resources 10988 * to change its appearance. 10989 * </p><p> 10990 * The {@link #onHoverChanged} method is called when the hovered state changes. 10991 * </p> 10992 * 10993 * @param hovered True if the view is hovered. 10994 * 10995 * @see #isHovered 10996 * @see #onHoverChanged 10997 */ 10998 public void setHovered(boolean hovered) { 10999 if (hovered) { 11000 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 11001 mPrivateFlags |= PFLAG_HOVERED; 11002 refreshDrawableState(); 11003 onHoverChanged(true); 11004 } 11005 } else { 11006 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 11007 mPrivateFlags &= ~PFLAG_HOVERED; 11008 refreshDrawableState(); 11009 onHoverChanged(false); 11010 } 11011 } 11012 } 11013 11014 /** 11015 * Implement this method to handle hover state changes. 11016 * <p> 11017 * This method is called whenever the hover state changes as a result of a 11018 * call to {@link #setHovered}. 11019 * </p> 11020 * 11021 * @param hovered The current hover state, as returned by {@link #isHovered}. 11022 * 11023 * @see #isHovered 11024 * @see #setHovered 11025 */ 11026 public void onHoverChanged(boolean hovered) { 11027 } 11028 11029 /** 11030 * Handles scroll bar dragging by mouse input. 11031 * 11032 * @hide 11033 * @param event The motion event. 11034 * 11035 * @return true if the event was handled as a scroll bar dragging, false otherwise. 11036 */ 11037 protected boolean handleScrollBarDragging(MotionEvent event) { 11038 if (mScrollCache == null) { 11039 return false; 11040 } 11041 final float x = event.getX(); 11042 final float y = event.getY(); 11043 final int action = event.getAction(); 11044 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 11045 && action != MotionEvent.ACTION_DOWN) 11046 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 11047 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 11048 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11049 return false; 11050 } 11051 11052 switch (action) { 11053 case MotionEvent.ACTION_MOVE: 11054 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 11055 return false; 11056 } 11057 if (mScrollCache.mScrollBarDraggingState 11058 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 11059 final Rect bounds = mScrollCache.mScrollBarBounds; 11060 getVerticalScrollBarBounds(bounds); 11061 final int range = computeVerticalScrollRange(); 11062 final int offset = computeVerticalScrollOffset(); 11063 final int extent = computeVerticalScrollExtent(); 11064 11065 final int thumbLength = ScrollBarUtils.getThumbLength( 11066 bounds.height(), bounds.width(), extent, range); 11067 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11068 bounds.height(), thumbLength, extent, range, offset); 11069 11070 final float diff = y - mScrollCache.mScrollBarDraggingPos; 11071 final float maxThumbOffset = bounds.height() - thumbLength; 11072 final float newThumbOffset = 11073 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11074 final int height = getHeight(); 11075 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11076 && height > 0 && extent > 0) { 11077 final int newY = Math.round((range - extent) 11078 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 11079 if (newY != getScrollY()) { 11080 mScrollCache.mScrollBarDraggingPos = y; 11081 setScrollY(newY); 11082 } 11083 } 11084 return true; 11085 } 11086 if (mScrollCache.mScrollBarDraggingState 11087 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 11088 final Rect bounds = mScrollCache.mScrollBarBounds; 11089 getHorizontalScrollBarBounds(bounds); 11090 final int range = computeHorizontalScrollRange(); 11091 final int offset = computeHorizontalScrollOffset(); 11092 final int extent = computeHorizontalScrollExtent(); 11093 11094 final int thumbLength = ScrollBarUtils.getThumbLength( 11095 bounds.width(), bounds.height(), extent, range); 11096 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11097 bounds.width(), thumbLength, extent, range, offset); 11098 11099 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11100 final float maxThumbOffset = bounds.width() - thumbLength; 11101 final float newThumbOffset = 11102 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11103 final int width = getWidth(); 11104 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11105 && width > 0 && extent > 0) { 11106 final int newX = Math.round((range - extent) 11107 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11108 if (newX != getScrollX()) { 11109 mScrollCache.mScrollBarDraggingPos = x; 11110 setScrollX(newX); 11111 } 11112 } 11113 return true; 11114 } 11115 case MotionEvent.ACTION_DOWN: 11116 if (mScrollCache.state == ScrollabilityCache.OFF) { 11117 return false; 11118 } 11119 if (isOnVerticalScrollbarThumb(x, y)) { 11120 mScrollCache.mScrollBarDraggingState = 11121 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11122 mScrollCache.mScrollBarDraggingPos = y; 11123 return true; 11124 } 11125 if (isOnHorizontalScrollbarThumb(x, y)) { 11126 mScrollCache.mScrollBarDraggingState = 11127 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11128 mScrollCache.mScrollBarDraggingPos = x; 11129 return true; 11130 } 11131 } 11132 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11133 return false; 11134 } 11135 11136 /** 11137 * Implement this method to handle touch screen motion events. 11138 * <p> 11139 * If this method is used to detect click actions, it is recommended that 11140 * the actions be performed by implementing and calling 11141 * {@link #performClick()}. This will ensure consistent system behavior, 11142 * including: 11143 * <ul> 11144 * <li>obeying click sound preferences 11145 * <li>dispatching OnClickListener calls 11146 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11147 * accessibility features are enabled 11148 * </ul> 11149 * 11150 * @param event The motion event. 11151 * @return True if the event was handled, false otherwise. 11152 */ 11153 public boolean onTouchEvent(MotionEvent event) { 11154 final float x = event.getX(); 11155 final float y = event.getY(); 11156 final int viewFlags = mViewFlags; 11157 final int action = event.getAction(); 11158 11159 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11160 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11161 setPressed(false); 11162 } 11163 // A disabled view that is clickable still consumes the touch 11164 // events, it just doesn't respond to them. 11165 return (((viewFlags & CLICKABLE) == CLICKABLE 11166 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11167 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11168 } 11169 if (mTouchDelegate != null) { 11170 if (mTouchDelegate.onTouchEvent(event)) { 11171 return true; 11172 } 11173 } 11174 11175 if (((viewFlags & CLICKABLE) == CLICKABLE || 11176 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11177 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11178 switch (action) { 11179 case MotionEvent.ACTION_UP: 11180 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11181 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11182 // take focus if we don't have it already and we should in 11183 // touch mode. 11184 boolean focusTaken = false; 11185 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11186 focusTaken = requestFocus(); 11187 } 11188 11189 if (prepressed) { 11190 // The button is being released before we actually 11191 // showed it as pressed. Make it show the pressed 11192 // state now (before scheduling the click) to ensure 11193 // the user sees it. 11194 setPressed(true, x, y); 11195 } 11196 11197 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11198 // This is a tap, so remove the longpress check 11199 removeLongPressCallback(); 11200 11201 // Only perform take click actions if we were in the pressed state 11202 if (!focusTaken) { 11203 // Use a Runnable and post this rather than calling 11204 // performClick directly. This lets other visual state 11205 // of the view update before click actions start. 11206 if (mPerformClick == null) { 11207 mPerformClick = new PerformClick(); 11208 } 11209 if (!post(mPerformClick)) { 11210 performClick(); 11211 } 11212 } 11213 } 11214 11215 if (mUnsetPressedState == null) { 11216 mUnsetPressedState = new UnsetPressedState(); 11217 } 11218 11219 if (prepressed) { 11220 postDelayed(mUnsetPressedState, 11221 ViewConfiguration.getPressedStateDuration()); 11222 } else if (!post(mUnsetPressedState)) { 11223 // If the post failed, unpress right now 11224 mUnsetPressedState.run(); 11225 } 11226 11227 removeTapCallback(); 11228 } 11229 mIgnoreNextUpEvent = false; 11230 break; 11231 11232 case MotionEvent.ACTION_DOWN: 11233 mHasPerformedLongPress = false; 11234 11235 if (performButtonActionOnTouchDown(event)) { 11236 break; 11237 } 11238 11239 // Walk up the hierarchy to determine if we're inside a scrolling container. 11240 boolean isInScrollingContainer = isInScrollingContainer(); 11241 11242 // For views inside a scrolling container, delay the pressed feedback for 11243 // a short period in case this is a scroll. 11244 if (isInScrollingContainer) { 11245 mPrivateFlags |= PFLAG_PREPRESSED; 11246 if (mPendingCheckForTap == null) { 11247 mPendingCheckForTap = new CheckForTap(); 11248 } 11249 mPendingCheckForTap.x = event.getX(); 11250 mPendingCheckForTap.y = event.getY(); 11251 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11252 } else { 11253 // Not inside a scrolling container, so show the feedback right away 11254 setPressed(true, x, y); 11255 checkForLongClick(0, x, y); 11256 } 11257 break; 11258 11259 case MotionEvent.ACTION_CANCEL: 11260 setPressed(false); 11261 removeTapCallback(); 11262 removeLongPressCallback(); 11263 mInContextButtonPress = false; 11264 mHasPerformedLongPress = false; 11265 mIgnoreNextUpEvent = false; 11266 break; 11267 11268 case MotionEvent.ACTION_MOVE: 11269 drawableHotspotChanged(x, y); 11270 11271 // Be lenient about moving outside of buttons 11272 if (!pointInView(x, y, mTouchSlop)) { 11273 // Outside button 11274 removeTapCallback(); 11275 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11276 // Remove any future long press/tap checks 11277 removeLongPressCallback(); 11278 11279 setPressed(false); 11280 } 11281 } 11282 break; 11283 } 11284 11285 return true; 11286 } 11287 11288 return false; 11289 } 11290 11291 /** 11292 * @hide 11293 */ 11294 public boolean isInScrollingContainer() { 11295 ViewParent p = getParent(); 11296 while (p != null && p instanceof ViewGroup) { 11297 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11298 return true; 11299 } 11300 p = p.getParent(); 11301 } 11302 return false; 11303 } 11304 11305 /** 11306 * Remove the longpress detection timer. 11307 */ 11308 private void removeLongPressCallback() { 11309 if (mPendingCheckForLongPress != null) { 11310 removeCallbacks(mPendingCheckForLongPress); 11311 } 11312 } 11313 11314 /** 11315 * Remove the pending click action 11316 */ 11317 private void removePerformClickCallback() { 11318 if (mPerformClick != null) { 11319 removeCallbacks(mPerformClick); 11320 } 11321 } 11322 11323 /** 11324 * Remove the prepress detection timer. 11325 */ 11326 private void removeUnsetPressCallback() { 11327 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11328 setPressed(false); 11329 removeCallbacks(mUnsetPressedState); 11330 } 11331 } 11332 11333 /** 11334 * Remove the tap detection timer. 11335 */ 11336 private void removeTapCallback() { 11337 if (mPendingCheckForTap != null) { 11338 mPrivateFlags &= ~PFLAG_PREPRESSED; 11339 removeCallbacks(mPendingCheckForTap); 11340 } 11341 } 11342 11343 /** 11344 * Cancels a pending long press. Your subclass can use this if you 11345 * want the context menu to come up if the user presses and holds 11346 * at the same place, but you don't want it to come up if they press 11347 * and then move around enough to cause scrolling. 11348 */ 11349 public void cancelLongPress() { 11350 removeLongPressCallback(); 11351 11352 /* 11353 * The prepressed state handled by the tap callback is a display 11354 * construct, but the tap callback will post a long press callback 11355 * less its own timeout. Remove it here. 11356 */ 11357 removeTapCallback(); 11358 } 11359 11360 /** 11361 * Remove the pending callback for sending a 11362 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11363 */ 11364 private void removeSendViewScrolledAccessibilityEventCallback() { 11365 if (mSendViewScrolledAccessibilityEvent != null) { 11366 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11367 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11368 } 11369 } 11370 11371 /** 11372 * Sets the TouchDelegate for this View. 11373 */ 11374 public void setTouchDelegate(TouchDelegate delegate) { 11375 mTouchDelegate = delegate; 11376 } 11377 11378 /** 11379 * Gets the TouchDelegate for this View. 11380 */ 11381 public TouchDelegate getTouchDelegate() { 11382 return mTouchDelegate; 11383 } 11384 11385 /** 11386 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11387 * 11388 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11389 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11390 * available. This method should only be called for touch events. 11391 * 11392 * <p class="note">This api is not intended for most applications. Buffered dispatch 11393 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11394 * streams will not improve your input latency. Side effects include: increased latency, 11395 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11396 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11397 * you.</p> 11398 */ 11399 public final void requestUnbufferedDispatch(MotionEvent event) { 11400 final int action = event.getAction(); 11401 if (mAttachInfo == null 11402 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11403 || !event.isTouchEvent()) { 11404 return; 11405 } 11406 mAttachInfo.mUnbufferedDispatchRequested = true; 11407 } 11408 11409 /** 11410 * Set flags controlling behavior of this view. 11411 * 11412 * @param flags Constant indicating the value which should be set 11413 * @param mask Constant indicating the bit range that should be changed 11414 */ 11415 void setFlags(int flags, int mask) { 11416 final boolean accessibilityEnabled = 11417 AccessibilityManager.getInstance(mContext).isEnabled(); 11418 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11419 11420 int old = mViewFlags; 11421 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11422 11423 int changed = mViewFlags ^ old; 11424 if (changed == 0) { 11425 return; 11426 } 11427 int privateFlags = mPrivateFlags; 11428 11429 /* Check if the FOCUSABLE bit has changed */ 11430 if (((changed & FOCUSABLE_MASK) != 0) && 11431 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11432 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11433 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11434 /* Give up focus if we are no longer focusable */ 11435 clearFocus(); 11436 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11437 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11438 /* 11439 * Tell the view system that we are now available to take focus 11440 * if no one else already has it. 11441 */ 11442 if (mParent != null) mParent.focusableViewAvailable(this); 11443 } 11444 } 11445 11446 final int newVisibility = flags & VISIBILITY_MASK; 11447 if (newVisibility == VISIBLE) { 11448 if ((changed & VISIBILITY_MASK) != 0) { 11449 /* 11450 * If this view is becoming visible, invalidate it in case it changed while 11451 * it was not visible. Marking it drawn ensures that the invalidation will 11452 * go through. 11453 */ 11454 mPrivateFlags |= PFLAG_DRAWN; 11455 invalidate(true); 11456 11457 needGlobalAttributesUpdate(true); 11458 11459 // a view becoming visible is worth notifying the parent 11460 // about in case nothing has focus. even if this specific view 11461 // isn't focusable, it may contain something that is, so let 11462 // the root view try to give this focus if nothing else does. 11463 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11464 mParent.focusableViewAvailable(this); 11465 } 11466 } 11467 } 11468 11469 /* Check if the GONE bit has changed */ 11470 if ((changed & GONE) != 0) { 11471 needGlobalAttributesUpdate(false); 11472 requestLayout(); 11473 11474 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11475 if (hasFocus()) clearFocus(); 11476 clearAccessibilityFocus(); 11477 destroyDrawingCache(); 11478 if (mParent instanceof View) { 11479 // GONE views noop invalidation, so invalidate the parent 11480 ((View) mParent).invalidate(true); 11481 } 11482 // Mark the view drawn to ensure that it gets invalidated properly the next 11483 // time it is visible and gets invalidated 11484 mPrivateFlags |= PFLAG_DRAWN; 11485 } 11486 if (mAttachInfo != null) { 11487 mAttachInfo.mViewVisibilityChanged = true; 11488 } 11489 } 11490 11491 /* Check if the VISIBLE bit has changed */ 11492 if ((changed & INVISIBLE) != 0) { 11493 needGlobalAttributesUpdate(false); 11494 /* 11495 * If this view is becoming invisible, set the DRAWN flag so that 11496 * the next invalidate() will not be skipped. 11497 */ 11498 mPrivateFlags |= PFLAG_DRAWN; 11499 11500 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11501 // root view becoming invisible shouldn't clear focus and accessibility focus 11502 if (getRootView() != this) { 11503 if (hasFocus()) clearFocus(); 11504 clearAccessibilityFocus(); 11505 } 11506 } 11507 if (mAttachInfo != null) { 11508 mAttachInfo.mViewVisibilityChanged = true; 11509 } 11510 } 11511 11512 if ((changed & VISIBILITY_MASK) != 0) { 11513 // If the view is invisible, cleanup its display list to free up resources 11514 if (newVisibility != VISIBLE && mAttachInfo != null) { 11515 cleanupDraw(); 11516 } 11517 11518 if (mParent instanceof ViewGroup) { 11519 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11520 (changed & VISIBILITY_MASK), newVisibility); 11521 ((View) mParent).invalidate(true); 11522 } else if (mParent != null) { 11523 mParent.invalidateChild(this, null); 11524 } 11525 11526 if (mAttachInfo != null) { 11527 dispatchVisibilityChanged(this, newVisibility); 11528 11529 // Aggregated visibility changes are dispatched to attached views 11530 // in visible windows where the parent is currently shown/drawn 11531 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11532 // discounting clipping or overlapping. This makes it a good place 11533 // to change animation states. 11534 if (mParent != null && getWindowVisibility() == VISIBLE && 11535 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11536 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11537 } 11538 notifySubtreeAccessibilityStateChangedIfNeeded(); 11539 } 11540 } 11541 11542 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11543 destroyDrawingCache(); 11544 } 11545 11546 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11547 destroyDrawingCache(); 11548 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11549 invalidateParentCaches(); 11550 } 11551 11552 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11553 destroyDrawingCache(); 11554 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11555 } 11556 11557 if ((changed & DRAW_MASK) != 0) { 11558 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11559 if (mBackground != null 11560 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11561 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11562 } else { 11563 mPrivateFlags |= PFLAG_SKIP_DRAW; 11564 } 11565 } else { 11566 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11567 } 11568 requestLayout(); 11569 invalidate(true); 11570 } 11571 11572 if ((changed & KEEP_SCREEN_ON) != 0) { 11573 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11574 mParent.recomputeViewAttributes(this); 11575 } 11576 } 11577 11578 if (accessibilityEnabled) { 11579 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11580 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11581 || (changed & CONTEXT_CLICKABLE) != 0) { 11582 if (oldIncludeForAccessibility != includeForAccessibility()) { 11583 notifySubtreeAccessibilityStateChangedIfNeeded(); 11584 } else { 11585 notifyViewAccessibilityStateChangedIfNeeded( 11586 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11587 } 11588 } else if ((changed & ENABLED_MASK) != 0) { 11589 notifyViewAccessibilityStateChangedIfNeeded( 11590 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11591 } 11592 } 11593 } 11594 11595 /** 11596 * Change the view's z order in the tree, so it's on top of other sibling 11597 * views. This ordering change may affect layout, if the parent container 11598 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11599 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11600 * method should be followed by calls to {@link #requestLayout()} and 11601 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11602 * with the new child ordering. 11603 * 11604 * @see ViewGroup#bringChildToFront(View) 11605 */ 11606 public void bringToFront() { 11607 if (mParent != null) { 11608 mParent.bringChildToFront(this); 11609 } 11610 } 11611 11612 /** 11613 * This is called in response to an internal scroll in this view (i.e., the 11614 * view scrolled its own contents). This is typically as a result of 11615 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11616 * called. 11617 * 11618 * @param l Current horizontal scroll origin. 11619 * @param t Current vertical scroll origin. 11620 * @param oldl Previous horizontal scroll origin. 11621 * @param oldt Previous vertical scroll origin. 11622 */ 11623 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11624 notifySubtreeAccessibilityStateChangedIfNeeded(); 11625 11626 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11627 postSendViewScrolledAccessibilityEventCallback(); 11628 } 11629 11630 mBackgroundSizeChanged = true; 11631 if (mForegroundInfo != null) { 11632 mForegroundInfo.mBoundsChanged = true; 11633 } 11634 11635 final AttachInfo ai = mAttachInfo; 11636 if (ai != null) { 11637 ai.mViewScrollChanged = true; 11638 } 11639 11640 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11641 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11642 } 11643 } 11644 11645 /** 11646 * Interface definition for a callback to be invoked when the scroll 11647 * X or Y positions of a view change. 11648 * <p> 11649 * <b>Note:</b> Some views handle scrolling independently from View and may 11650 * have their own separate listeners for scroll-type events. For example, 11651 * {@link android.widget.ListView ListView} allows clients to register an 11652 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11653 * to listen for changes in list scroll position. 11654 * 11655 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11656 */ 11657 public interface OnScrollChangeListener { 11658 /** 11659 * Called when the scroll position of a view changes. 11660 * 11661 * @param v The view whose scroll position has changed. 11662 * @param scrollX Current horizontal scroll origin. 11663 * @param scrollY Current vertical scroll origin. 11664 * @param oldScrollX Previous horizontal scroll origin. 11665 * @param oldScrollY Previous vertical scroll origin. 11666 */ 11667 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11668 } 11669 11670 /** 11671 * Interface definition for a callback to be invoked when the layout bounds of a view 11672 * changes due to layout processing. 11673 */ 11674 public interface OnLayoutChangeListener { 11675 /** 11676 * Called when the layout bounds of a view changes due to layout processing. 11677 * 11678 * @param v The view whose bounds have changed. 11679 * @param left The new value of the view's left property. 11680 * @param top The new value of the view's top property. 11681 * @param right The new value of the view's right property. 11682 * @param bottom The new value of the view's bottom property. 11683 * @param oldLeft The previous value of the view's left property. 11684 * @param oldTop The previous value of the view's top property. 11685 * @param oldRight The previous value of the view's right property. 11686 * @param oldBottom The previous value of the view's bottom property. 11687 */ 11688 void onLayoutChange(View v, int left, int top, int right, int bottom, 11689 int oldLeft, int oldTop, int oldRight, int oldBottom); 11690 } 11691 11692 /** 11693 * This is called during layout when the size of this view has changed. If 11694 * you were just added to the view hierarchy, you're called with the old 11695 * values of 0. 11696 * 11697 * @param w Current width of this view. 11698 * @param h Current height of this view. 11699 * @param oldw Old width of this view. 11700 * @param oldh Old height of this view. 11701 */ 11702 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11703 } 11704 11705 /** 11706 * Called by draw to draw the child views. This may be overridden 11707 * by derived classes to gain control just before its children are drawn 11708 * (but after its own view has been drawn). 11709 * @param canvas the canvas on which to draw the view 11710 */ 11711 protected void dispatchDraw(Canvas canvas) { 11712 11713 } 11714 11715 /** 11716 * Gets the parent of this view. Note that the parent is a 11717 * ViewParent and not necessarily a View. 11718 * 11719 * @return Parent of this view. 11720 */ 11721 public final ViewParent getParent() { 11722 return mParent; 11723 } 11724 11725 /** 11726 * Set the horizontal scrolled position of your view. This will cause a call to 11727 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11728 * invalidated. 11729 * @param value the x position to scroll to 11730 */ 11731 public void setScrollX(int value) { 11732 scrollTo(value, mScrollY); 11733 } 11734 11735 /** 11736 * Set the vertical scrolled position of your view. This will cause a call to 11737 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11738 * invalidated. 11739 * @param value the y position to scroll to 11740 */ 11741 public void setScrollY(int value) { 11742 scrollTo(mScrollX, value); 11743 } 11744 11745 /** 11746 * Return the scrolled left position of this view. This is the left edge of 11747 * the displayed part of your view. You do not need to draw any pixels 11748 * farther left, since those are outside of the frame of your view on 11749 * screen. 11750 * 11751 * @return The left edge of the displayed part of your view, in pixels. 11752 */ 11753 public final int getScrollX() { 11754 return mScrollX; 11755 } 11756 11757 /** 11758 * Return the scrolled top position of this view. This is the top edge of 11759 * the displayed part of your view. You do not need to draw any pixels above 11760 * it, since those are outside of the frame of your view on screen. 11761 * 11762 * @return The top edge of the displayed part of your view, in pixels. 11763 */ 11764 public final int getScrollY() { 11765 return mScrollY; 11766 } 11767 11768 /** 11769 * Return the width of the your view. 11770 * 11771 * @return The width of your view, in pixels. 11772 */ 11773 @ViewDebug.ExportedProperty(category = "layout") 11774 public final int getWidth() { 11775 return mRight - mLeft; 11776 } 11777 11778 /** 11779 * Return the height of your view. 11780 * 11781 * @return The height of your view, in pixels. 11782 */ 11783 @ViewDebug.ExportedProperty(category = "layout") 11784 public final int getHeight() { 11785 return mBottom - mTop; 11786 } 11787 11788 /** 11789 * Return the visible drawing bounds of your view. Fills in the output 11790 * rectangle with the values from getScrollX(), getScrollY(), 11791 * getWidth(), and getHeight(). These bounds do not account for any 11792 * transformation properties currently set on the view, such as 11793 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11794 * 11795 * @param outRect The (scrolled) drawing bounds of the view. 11796 */ 11797 public void getDrawingRect(Rect outRect) { 11798 outRect.left = mScrollX; 11799 outRect.top = mScrollY; 11800 outRect.right = mScrollX + (mRight - mLeft); 11801 outRect.bottom = mScrollY + (mBottom - mTop); 11802 } 11803 11804 /** 11805 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11806 * raw width component (that is the result is masked by 11807 * {@link #MEASURED_SIZE_MASK}). 11808 * 11809 * @return The raw measured width of this view. 11810 */ 11811 public final int getMeasuredWidth() { 11812 return mMeasuredWidth & MEASURED_SIZE_MASK; 11813 } 11814 11815 /** 11816 * Return the full width measurement information for this view as computed 11817 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11818 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11819 * This should be used during measurement and layout calculations only. Use 11820 * {@link #getWidth()} to see how wide a view is after layout. 11821 * 11822 * @return The measured width of this view as a bit mask. 11823 */ 11824 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11825 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11826 name = "MEASURED_STATE_TOO_SMALL"), 11827 }) 11828 public final int getMeasuredWidthAndState() { 11829 return mMeasuredWidth; 11830 } 11831 11832 /** 11833 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11834 * raw height component (that is the result is masked by 11835 * {@link #MEASURED_SIZE_MASK}). 11836 * 11837 * @return The raw measured height of this view. 11838 */ 11839 public final int getMeasuredHeight() { 11840 return mMeasuredHeight & MEASURED_SIZE_MASK; 11841 } 11842 11843 /** 11844 * Return the full height measurement information for this view as computed 11845 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11846 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11847 * This should be used during measurement and layout calculations only. Use 11848 * {@link #getHeight()} to see how wide a view is after layout. 11849 * 11850 * @return The measured height of this view as a bit mask. 11851 */ 11852 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11853 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11854 name = "MEASURED_STATE_TOO_SMALL"), 11855 }) 11856 public final int getMeasuredHeightAndState() { 11857 return mMeasuredHeight; 11858 } 11859 11860 /** 11861 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11862 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11863 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11864 * and the height component is at the shifted bits 11865 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11866 */ 11867 public final int getMeasuredState() { 11868 return (mMeasuredWidth&MEASURED_STATE_MASK) 11869 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11870 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11871 } 11872 11873 /** 11874 * The transform matrix of this view, which is calculated based on the current 11875 * rotation, scale, and pivot properties. 11876 * 11877 * @see #getRotation() 11878 * @see #getScaleX() 11879 * @see #getScaleY() 11880 * @see #getPivotX() 11881 * @see #getPivotY() 11882 * @return The current transform matrix for the view 11883 */ 11884 public Matrix getMatrix() { 11885 ensureTransformationInfo(); 11886 final Matrix matrix = mTransformationInfo.mMatrix; 11887 mRenderNode.getMatrix(matrix); 11888 return matrix; 11889 } 11890 11891 /** 11892 * Returns true if the transform matrix is the identity matrix. 11893 * Recomputes the matrix if necessary. 11894 * 11895 * @return True if the transform matrix is the identity matrix, false otherwise. 11896 */ 11897 final boolean hasIdentityMatrix() { 11898 return mRenderNode.hasIdentityMatrix(); 11899 } 11900 11901 void ensureTransformationInfo() { 11902 if (mTransformationInfo == null) { 11903 mTransformationInfo = new TransformationInfo(); 11904 } 11905 } 11906 11907 /** 11908 * Utility method to retrieve the inverse of the current mMatrix property. 11909 * We cache the matrix to avoid recalculating it when transform properties 11910 * have not changed. 11911 * 11912 * @return The inverse of the current matrix of this view. 11913 * @hide 11914 */ 11915 public final Matrix getInverseMatrix() { 11916 ensureTransformationInfo(); 11917 if (mTransformationInfo.mInverseMatrix == null) { 11918 mTransformationInfo.mInverseMatrix = new Matrix(); 11919 } 11920 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11921 mRenderNode.getInverseMatrix(matrix); 11922 return matrix; 11923 } 11924 11925 /** 11926 * Gets the distance along the Z axis from the camera to this view. 11927 * 11928 * @see #setCameraDistance(float) 11929 * 11930 * @return The distance along the Z axis. 11931 */ 11932 public float getCameraDistance() { 11933 final float dpi = mResources.getDisplayMetrics().densityDpi; 11934 return -(mRenderNode.getCameraDistance() * dpi); 11935 } 11936 11937 /** 11938 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11939 * views are drawn) from the camera to this view. The camera's distance 11940 * affects 3D transformations, for instance rotations around the X and Y 11941 * axis. If the rotationX or rotationY properties are changed and this view is 11942 * large (more than half the size of the screen), it is recommended to always 11943 * use a camera distance that's greater than the height (X axis rotation) or 11944 * the width (Y axis rotation) of this view.</p> 11945 * 11946 * <p>The distance of the camera from the view plane can have an affect on the 11947 * perspective distortion of the view when it is rotated around the x or y axis. 11948 * For example, a large distance will result in a large viewing angle, and there 11949 * will not be much perspective distortion of the view as it rotates. A short 11950 * distance may cause much more perspective distortion upon rotation, and can 11951 * also result in some drawing artifacts if the rotated view ends up partially 11952 * behind the camera (which is why the recommendation is to use a distance at 11953 * least as far as the size of the view, if the view is to be rotated.)</p> 11954 * 11955 * <p>The distance is expressed in "depth pixels." The default distance depends 11956 * on the screen density. For instance, on a medium density display, the 11957 * default distance is 1280. On a high density display, the default distance 11958 * is 1920.</p> 11959 * 11960 * <p>If you want to specify a distance that leads to visually consistent 11961 * results across various densities, use the following formula:</p> 11962 * <pre> 11963 * float scale = context.getResources().getDisplayMetrics().density; 11964 * view.setCameraDistance(distance * scale); 11965 * </pre> 11966 * 11967 * <p>The density scale factor of a high density display is 1.5, 11968 * and 1920 = 1280 * 1.5.</p> 11969 * 11970 * @param distance The distance in "depth pixels", if negative the opposite 11971 * value is used 11972 * 11973 * @see #setRotationX(float) 11974 * @see #setRotationY(float) 11975 */ 11976 public void setCameraDistance(float distance) { 11977 final float dpi = mResources.getDisplayMetrics().densityDpi; 11978 11979 invalidateViewProperty(true, false); 11980 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11981 invalidateViewProperty(false, false); 11982 11983 invalidateParentIfNeededAndWasQuickRejected(); 11984 } 11985 11986 /** 11987 * The degrees that the view is rotated around the pivot point. 11988 * 11989 * @see #setRotation(float) 11990 * @see #getPivotX() 11991 * @see #getPivotY() 11992 * 11993 * @return The degrees of rotation. 11994 */ 11995 @ViewDebug.ExportedProperty(category = "drawing") 11996 public float getRotation() { 11997 return mRenderNode.getRotation(); 11998 } 11999 12000 /** 12001 * Sets the degrees that the view is rotated around the pivot point. Increasing values 12002 * result in clockwise rotation. 12003 * 12004 * @param rotation The degrees of rotation. 12005 * 12006 * @see #getRotation() 12007 * @see #getPivotX() 12008 * @see #getPivotY() 12009 * @see #setRotationX(float) 12010 * @see #setRotationY(float) 12011 * 12012 * @attr ref android.R.styleable#View_rotation 12013 */ 12014 public void setRotation(float rotation) { 12015 if (rotation != getRotation()) { 12016 // Double-invalidation is necessary to capture view's old and new areas 12017 invalidateViewProperty(true, false); 12018 mRenderNode.setRotation(rotation); 12019 invalidateViewProperty(false, true); 12020 12021 invalidateParentIfNeededAndWasQuickRejected(); 12022 notifySubtreeAccessibilityStateChangedIfNeeded(); 12023 } 12024 } 12025 12026 /** 12027 * The degrees that the view is rotated around the vertical axis through the pivot point. 12028 * 12029 * @see #getPivotX() 12030 * @see #getPivotY() 12031 * @see #setRotationY(float) 12032 * 12033 * @return The degrees of Y rotation. 12034 */ 12035 @ViewDebug.ExportedProperty(category = "drawing") 12036 public float getRotationY() { 12037 return mRenderNode.getRotationY(); 12038 } 12039 12040 /** 12041 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 12042 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 12043 * down the y axis. 12044 * 12045 * When rotating large views, it is recommended to adjust the camera distance 12046 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12047 * 12048 * @param rotationY The degrees of Y rotation. 12049 * 12050 * @see #getRotationY() 12051 * @see #getPivotX() 12052 * @see #getPivotY() 12053 * @see #setRotation(float) 12054 * @see #setRotationX(float) 12055 * @see #setCameraDistance(float) 12056 * 12057 * @attr ref android.R.styleable#View_rotationY 12058 */ 12059 public void setRotationY(float rotationY) { 12060 if (rotationY != getRotationY()) { 12061 invalidateViewProperty(true, false); 12062 mRenderNode.setRotationY(rotationY); 12063 invalidateViewProperty(false, true); 12064 12065 invalidateParentIfNeededAndWasQuickRejected(); 12066 notifySubtreeAccessibilityStateChangedIfNeeded(); 12067 } 12068 } 12069 12070 /** 12071 * The degrees that the view is rotated around the horizontal axis through the pivot point. 12072 * 12073 * @see #getPivotX() 12074 * @see #getPivotY() 12075 * @see #setRotationX(float) 12076 * 12077 * @return The degrees of X rotation. 12078 */ 12079 @ViewDebug.ExportedProperty(category = "drawing") 12080 public float getRotationX() { 12081 return mRenderNode.getRotationX(); 12082 } 12083 12084 /** 12085 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 12086 * Increasing values result in clockwise rotation from the viewpoint of looking down the 12087 * x axis. 12088 * 12089 * When rotating large views, it is recommended to adjust the camera distance 12090 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12091 * 12092 * @param rotationX The degrees of X rotation. 12093 * 12094 * @see #getRotationX() 12095 * @see #getPivotX() 12096 * @see #getPivotY() 12097 * @see #setRotation(float) 12098 * @see #setRotationY(float) 12099 * @see #setCameraDistance(float) 12100 * 12101 * @attr ref android.R.styleable#View_rotationX 12102 */ 12103 public void setRotationX(float rotationX) { 12104 if (rotationX != getRotationX()) { 12105 invalidateViewProperty(true, false); 12106 mRenderNode.setRotationX(rotationX); 12107 invalidateViewProperty(false, true); 12108 12109 invalidateParentIfNeededAndWasQuickRejected(); 12110 notifySubtreeAccessibilityStateChangedIfNeeded(); 12111 } 12112 } 12113 12114 /** 12115 * The amount that the view is scaled in x around the pivot point, as a proportion of 12116 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12117 * 12118 * <p>By default, this is 1.0f. 12119 * 12120 * @see #getPivotX() 12121 * @see #getPivotY() 12122 * @return The scaling factor. 12123 */ 12124 @ViewDebug.ExportedProperty(category = "drawing") 12125 public float getScaleX() { 12126 return mRenderNode.getScaleX(); 12127 } 12128 12129 /** 12130 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12131 * the view's unscaled width. A value of 1 means that no scaling is applied. 12132 * 12133 * @param scaleX The scaling factor. 12134 * @see #getPivotX() 12135 * @see #getPivotY() 12136 * 12137 * @attr ref android.R.styleable#View_scaleX 12138 */ 12139 public void setScaleX(float scaleX) { 12140 if (scaleX != getScaleX()) { 12141 invalidateViewProperty(true, false); 12142 mRenderNode.setScaleX(scaleX); 12143 invalidateViewProperty(false, true); 12144 12145 invalidateParentIfNeededAndWasQuickRejected(); 12146 notifySubtreeAccessibilityStateChangedIfNeeded(); 12147 } 12148 } 12149 12150 /** 12151 * The amount that the view is scaled in y around the pivot point, as a proportion of 12152 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12153 * 12154 * <p>By default, this is 1.0f. 12155 * 12156 * @see #getPivotX() 12157 * @see #getPivotY() 12158 * @return The scaling factor. 12159 */ 12160 @ViewDebug.ExportedProperty(category = "drawing") 12161 public float getScaleY() { 12162 return mRenderNode.getScaleY(); 12163 } 12164 12165 /** 12166 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12167 * the view's unscaled width. A value of 1 means that no scaling is applied. 12168 * 12169 * @param scaleY The scaling factor. 12170 * @see #getPivotX() 12171 * @see #getPivotY() 12172 * 12173 * @attr ref android.R.styleable#View_scaleY 12174 */ 12175 public void setScaleY(float scaleY) { 12176 if (scaleY != getScaleY()) { 12177 invalidateViewProperty(true, false); 12178 mRenderNode.setScaleY(scaleY); 12179 invalidateViewProperty(false, true); 12180 12181 invalidateParentIfNeededAndWasQuickRejected(); 12182 notifySubtreeAccessibilityStateChangedIfNeeded(); 12183 } 12184 } 12185 12186 /** 12187 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12188 * and {@link #setScaleX(float) scaled}. 12189 * 12190 * @see #getRotation() 12191 * @see #getScaleX() 12192 * @see #getScaleY() 12193 * @see #getPivotY() 12194 * @return The x location of the pivot point. 12195 * 12196 * @attr ref android.R.styleable#View_transformPivotX 12197 */ 12198 @ViewDebug.ExportedProperty(category = "drawing") 12199 public float getPivotX() { 12200 return mRenderNode.getPivotX(); 12201 } 12202 12203 /** 12204 * Sets the x location of the point around which the view is 12205 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12206 * By default, the pivot point is centered on the object. 12207 * Setting this property disables this behavior and causes the view to use only the 12208 * explicitly set pivotX and pivotY values. 12209 * 12210 * @param pivotX The x location of the pivot point. 12211 * @see #getRotation() 12212 * @see #getScaleX() 12213 * @see #getScaleY() 12214 * @see #getPivotY() 12215 * 12216 * @attr ref android.R.styleable#View_transformPivotX 12217 */ 12218 public void setPivotX(float pivotX) { 12219 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12220 invalidateViewProperty(true, false); 12221 mRenderNode.setPivotX(pivotX); 12222 invalidateViewProperty(false, true); 12223 12224 invalidateParentIfNeededAndWasQuickRejected(); 12225 } 12226 } 12227 12228 /** 12229 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12230 * and {@link #setScaleY(float) scaled}. 12231 * 12232 * @see #getRotation() 12233 * @see #getScaleX() 12234 * @see #getScaleY() 12235 * @see #getPivotY() 12236 * @return The y location of the pivot point. 12237 * 12238 * @attr ref android.R.styleable#View_transformPivotY 12239 */ 12240 @ViewDebug.ExportedProperty(category = "drawing") 12241 public float getPivotY() { 12242 return mRenderNode.getPivotY(); 12243 } 12244 12245 /** 12246 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12247 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12248 * Setting this property disables this behavior and causes the view to use only the 12249 * explicitly set pivotX and pivotY values. 12250 * 12251 * @param pivotY The y location of the pivot point. 12252 * @see #getRotation() 12253 * @see #getScaleX() 12254 * @see #getScaleY() 12255 * @see #getPivotY() 12256 * 12257 * @attr ref android.R.styleable#View_transformPivotY 12258 */ 12259 public void setPivotY(float pivotY) { 12260 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12261 invalidateViewProperty(true, false); 12262 mRenderNode.setPivotY(pivotY); 12263 invalidateViewProperty(false, true); 12264 12265 invalidateParentIfNeededAndWasQuickRejected(); 12266 } 12267 } 12268 12269 /** 12270 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12271 * completely transparent and 1 means the view is completely opaque. 12272 * 12273 * <p>By default this is 1.0f. 12274 * @return The opacity of the view. 12275 */ 12276 @ViewDebug.ExportedProperty(category = "drawing") 12277 public float getAlpha() { 12278 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12279 } 12280 12281 /** 12282 * Sets the behavior for overlapping rendering for this view (see {@link 12283 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12284 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12285 * providing the value which is then used internally. That is, when {@link 12286 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12287 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12288 * instead. 12289 * 12290 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12291 * instead of that returned by {@link #hasOverlappingRendering()}. 12292 * 12293 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12294 */ 12295 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12296 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12297 if (hasOverlappingRendering) { 12298 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12299 } else { 12300 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12301 } 12302 } 12303 12304 /** 12305 * Returns the value for overlapping rendering that is used internally. This is either 12306 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12307 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12308 * 12309 * @return The value for overlapping rendering being used internally. 12310 */ 12311 public final boolean getHasOverlappingRendering() { 12312 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12313 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12314 hasOverlappingRendering(); 12315 } 12316 12317 /** 12318 * Returns whether this View has content which overlaps. 12319 * 12320 * <p>This function, intended to be overridden by specific View types, is an optimization when 12321 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12322 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12323 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12324 * directly. An example of overlapping rendering is a TextView with a background image, such as 12325 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12326 * ImageView with only the foreground image. The default implementation returns true; subclasses 12327 * should override if they have cases which can be optimized.</p> 12328 * 12329 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12330 * necessitates that a View return true if it uses the methods internally without passing the 12331 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12332 * 12333 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12334 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12335 * 12336 * @return true if the content in this view might overlap, false otherwise. 12337 */ 12338 @ViewDebug.ExportedProperty(category = "drawing") 12339 public boolean hasOverlappingRendering() { 12340 return true; 12341 } 12342 12343 /** 12344 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12345 * completely transparent and 1 means the view is completely opaque. 12346 * 12347 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12348 * can have significant performance implications, especially for large views. It is best to use 12349 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12350 * 12351 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12352 * strongly recommended for performance reasons to either override 12353 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12354 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12355 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12356 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12357 * of rendering cost, even for simple or small views. Starting with 12358 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12359 * applied to the view at the rendering level.</p> 12360 * 12361 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12362 * responsible for applying the opacity itself.</p> 12363 * 12364 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12365 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12366 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12367 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12368 * 12369 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12370 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12371 * {@link #hasOverlappingRendering}.</p> 12372 * 12373 * @param alpha The opacity of the view. 12374 * 12375 * @see #hasOverlappingRendering() 12376 * @see #setLayerType(int, android.graphics.Paint) 12377 * 12378 * @attr ref android.R.styleable#View_alpha 12379 */ 12380 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12381 ensureTransformationInfo(); 12382 if (mTransformationInfo.mAlpha != alpha) { 12383 // Report visibility changes, which can affect children, to accessibility 12384 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 12385 notifySubtreeAccessibilityStateChangedIfNeeded(); 12386 } 12387 mTransformationInfo.mAlpha = alpha; 12388 if (onSetAlpha((int) (alpha * 255))) { 12389 mPrivateFlags |= PFLAG_ALPHA_SET; 12390 // subclass is handling alpha - don't optimize rendering cache invalidation 12391 invalidateParentCaches(); 12392 invalidate(true); 12393 } else { 12394 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12395 invalidateViewProperty(true, false); 12396 mRenderNode.setAlpha(getFinalAlpha()); 12397 } 12398 } 12399 } 12400 12401 /** 12402 * Faster version of setAlpha() which performs the same steps except there are 12403 * no calls to invalidate(). The caller of this function should perform proper invalidation 12404 * on the parent and this object. The return value indicates whether the subclass handles 12405 * alpha (the return value for onSetAlpha()). 12406 * 12407 * @param alpha The new value for the alpha property 12408 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12409 * the new value for the alpha property is different from the old value 12410 */ 12411 boolean setAlphaNoInvalidation(float alpha) { 12412 ensureTransformationInfo(); 12413 if (mTransformationInfo.mAlpha != alpha) { 12414 mTransformationInfo.mAlpha = alpha; 12415 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12416 if (subclassHandlesAlpha) { 12417 mPrivateFlags |= PFLAG_ALPHA_SET; 12418 return true; 12419 } else { 12420 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12421 mRenderNode.setAlpha(getFinalAlpha()); 12422 } 12423 } 12424 return false; 12425 } 12426 12427 /** 12428 * This property is hidden and intended only for use by the Fade transition, which 12429 * animates it to produce a visual translucency that does not side-effect (or get 12430 * affected by) the real alpha property. This value is composited with the other 12431 * alpha value (and the AlphaAnimation value, when that is present) to produce 12432 * a final visual translucency result, which is what is passed into the DisplayList. 12433 * 12434 * @hide 12435 */ 12436 public void setTransitionAlpha(float alpha) { 12437 ensureTransformationInfo(); 12438 if (mTransformationInfo.mTransitionAlpha != alpha) { 12439 mTransformationInfo.mTransitionAlpha = alpha; 12440 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12441 invalidateViewProperty(true, false); 12442 mRenderNode.setAlpha(getFinalAlpha()); 12443 } 12444 } 12445 12446 /** 12447 * Calculates the visual alpha of this view, which is a combination of the actual 12448 * alpha value and the transitionAlpha value (if set). 12449 */ 12450 private float getFinalAlpha() { 12451 if (mTransformationInfo != null) { 12452 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12453 } 12454 return 1; 12455 } 12456 12457 /** 12458 * This property is hidden and intended only for use by the Fade transition, which 12459 * animates it to produce a visual translucency that does not side-effect (or get 12460 * affected by) the real alpha property. This value is composited with the other 12461 * alpha value (and the AlphaAnimation value, when that is present) to produce 12462 * a final visual translucency result, which is what is passed into the DisplayList. 12463 * 12464 * @hide 12465 */ 12466 @ViewDebug.ExportedProperty(category = "drawing") 12467 public float getTransitionAlpha() { 12468 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12469 } 12470 12471 /** 12472 * Top position of this view relative to its parent. 12473 * 12474 * @return The top of this view, in pixels. 12475 */ 12476 @ViewDebug.CapturedViewProperty 12477 public final int getTop() { 12478 return mTop; 12479 } 12480 12481 /** 12482 * Sets the top position of this view relative to its parent. This method is meant to be called 12483 * by the layout system and should not generally be called otherwise, because the property 12484 * may be changed at any time by the layout. 12485 * 12486 * @param top The top of this view, in pixels. 12487 */ 12488 public final void setTop(int top) { 12489 if (top != mTop) { 12490 final boolean matrixIsIdentity = hasIdentityMatrix(); 12491 if (matrixIsIdentity) { 12492 if (mAttachInfo != null) { 12493 int minTop; 12494 int yLoc; 12495 if (top < mTop) { 12496 minTop = top; 12497 yLoc = top - mTop; 12498 } else { 12499 minTop = mTop; 12500 yLoc = 0; 12501 } 12502 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12503 } 12504 } else { 12505 // Double-invalidation is necessary to capture view's old and new areas 12506 invalidate(true); 12507 } 12508 12509 int width = mRight - mLeft; 12510 int oldHeight = mBottom - mTop; 12511 12512 mTop = top; 12513 mRenderNode.setTop(mTop); 12514 12515 sizeChange(width, mBottom - mTop, width, oldHeight); 12516 12517 if (!matrixIsIdentity) { 12518 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12519 invalidate(true); 12520 } 12521 mBackgroundSizeChanged = true; 12522 if (mForegroundInfo != null) { 12523 mForegroundInfo.mBoundsChanged = true; 12524 } 12525 invalidateParentIfNeeded(); 12526 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12527 // View was rejected last time it was drawn by its parent; this may have changed 12528 invalidateParentIfNeeded(); 12529 } 12530 } 12531 } 12532 12533 /** 12534 * Bottom position of this view relative to its parent. 12535 * 12536 * @return The bottom of this view, in pixels. 12537 */ 12538 @ViewDebug.CapturedViewProperty 12539 public final int getBottom() { 12540 return mBottom; 12541 } 12542 12543 /** 12544 * True if this view has changed since the last time being drawn. 12545 * 12546 * @return The dirty state of this view. 12547 */ 12548 public boolean isDirty() { 12549 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12550 } 12551 12552 /** 12553 * Sets the bottom position of this view relative to its parent. This method is meant to be 12554 * called by the layout system and should not generally be called otherwise, because the 12555 * property may be changed at any time by the layout. 12556 * 12557 * @param bottom The bottom of this view, in pixels. 12558 */ 12559 public final void setBottom(int bottom) { 12560 if (bottom != mBottom) { 12561 final boolean matrixIsIdentity = hasIdentityMatrix(); 12562 if (matrixIsIdentity) { 12563 if (mAttachInfo != null) { 12564 int maxBottom; 12565 if (bottom < mBottom) { 12566 maxBottom = mBottom; 12567 } else { 12568 maxBottom = bottom; 12569 } 12570 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12571 } 12572 } else { 12573 // Double-invalidation is necessary to capture view's old and new areas 12574 invalidate(true); 12575 } 12576 12577 int width = mRight - mLeft; 12578 int oldHeight = mBottom - mTop; 12579 12580 mBottom = bottom; 12581 mRenderNode.setBottom(mBottom); 12582 12583 sizeChange(width, mBottom - mTop, width, oldHeight); 12584 12585 if (!matrixIsIdentity) { 12586 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12587 invalidate(true); 12588 } 12589 mBackgroundSizeChanged = true; 12590 if (mForegroundInfo != null) { 12591 mForegroundInfo.mBoundsChanged = true; 12592 } 12593 invalidateParentIfNeeded(); 12594 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12595 // View was rejected last time it was drawn by its parent; this may have changed 12596 invalidateParentIfNeeded(); 12597 } 12598 } 12599 } 12600 12601 /** 12602 * Left position of this view relative to its parent. 12603 * 12604 * @return The left edge of this view, in pixels. 12605 */ 12606 @ViewDebug.CapturedViewProperty 12607 public final int getLeft() { 12608 return mLeft; 12609 } 12610 12611 /** 12612 * Sets the left position of this view relative to its parent. This method is meant to be called 12613 * by the layout system and should not generally be called otherwise, because the property 12614 * may be changed at any time by the layout. 12615 * 12616 * @param left The left of this view, in pixels. 12617 */ 12618 public final void setLeft(int left) { 12619 if (left != mLeft) { 12620 final boolean matrixIsIdentity = hasIdentityMatrix(); 12621 if (matrixIsIdentity) { 12622 if (mAttachInfo != null) { 12623 int minLeft; 12624 int xLoc; 12625 if (left < mLeft) { 12626 minLeft = left; 12627 xLoc = left - mLeft; 12628 } else { 12629 minLeft = mLeft; 12630 xLoc = 0; 12631 } 12632 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12633 } 12634 } else { 12635 // Double-invalidation is necessary to capture view's old and new areas 12636 invalidate(true); 12637 } 12638 12639 int oldWidth = mRight - mLeft; 12640 int height = mBottom - mTop; 12641 12642 mLeft = left; 12643 mRenderNode.setLeft(left); 12644 12645 sizeChange(mRight - mLeft, height, oldWidth, height); 12646 12647 if (!matrixIsIdentity) { 12648 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12649 invalidate(true); 12650 } 12651 mBackgroundSizeChanged = true; 12652 if (mForegroundInfo != null) { 12653 mForegroundInfo.mBoundsChanged = true; 12654 } 12655 invalidateParentIfNeeded(); 12656 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12657 // View was rejected last time it was drawn by its parent; this may have changed 12658 invalidateParentIfNeeded(); 12659 } 12660 } 12661 } 12662 12663 /** 12664 * Right position of this view relative to its parent. 12665 * 12666 * @return The right edge of this view, in pixels. 12667 */ 12668 @ViewDebug.CapturedViewProperty 12669 public final int getRight() { 12670 return mRight; 12671 } 12672 12673 /** 12674 * Sets the right position of this view relative to its parent. This method is meant to be called 12675 * by the layout system and should not generally be called otherwise, because the property 12676 * may be changed at any time by the layout. 12677 * 12678 * @param right The right of this view, in pixels. 12679 */ 12680 public final void setRight(int right) { 12681 if (right != mRight) { 12682 final boolean matrixIsIdentity = hasIdentityMatrix(); 12683 if (matrixIsIdentity) { 12684 if (mAttachInfo != null) { 12685 int maxRight; 12686 if (right < mRight) { 12687 maxRight = mRight; 12688 } else { 12689 maxRight = right; 12690 } 12691 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12692 } 12693 } else { 12694 // Double-invalidation is necessary to capture view's old and new areas 12695 invalidate(true); 12696 } 12697 12698 int oldWidth = mRight - mLeft; 12699 int height = mBottom - mTop; 12700 12701 mRight = right; 12702 mRenderNode.setRight(mRight); 12703 12704 sizeChange(mRight - mLeft, height, oldWidth, height); 12705 12706 if (!matrixIsIdentity) { 12707 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12708 invalidate(true); 12709 } 12710 mBackgroundSizeChanged = true; 12711 if (mForegroundInfo != null) { 12712 mForegroundInfo.mBoundsChanged = true; 12713 } 12714 invalidateParentIfNeeded(); 12715 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12716 // View was rejected last time it was drawn by its parent; this may have changed 12717 invalidateParentIfNeeded(); 12718 } 12719 } 12720 } 12721 12722 /** 12723 * The visual x position of this view, in pixels. This is equivalent to the 12724 * {@link #setTranslationX(float) translationX} property plus the current 12725 * {@link #getLeft() left} property. 12726 * 12727 * @return The visual x position of this view, in pixels. 12728 */ 12729 @ViewDebug.ExportedProperty(category = "drawing") 12730 public float getX() { 12731 return mLeft + getTranslationX(); 12732 } 12733 12734 /** 12735 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12736 * {@link #setTranslationX(float) translationX} property to be the difference between 12737 * the x value passed in and the current {@link #getLeft() left} property. 12738 * 12739 * @param x The visual x position of this view, in pixels. 12740 */ 12741 public void setX(float x) { 12742 setTranslationX(x - mLeft); 12743 } 12744 12745 /** 12746 * The visual y position of this view, in pixels. This is equivalent to the 12747 * {@link #setTranslationY(float) translationY} property plus the current 12748 * {@link #getTop() top} property. 12749 * 12750 * @return The visual y position of this view, in pixels. 12751 */ 12752 @ViewDebug.ExportedProperty(category = "drawing") 12753 public float getY() { 12754 return mTop + getTranslationY(); 12755 } 12756 12757 /** 12758 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12759 * {@link #setTranslationY(float) translationY} property to be the difference between 12760 * the y value passed in and the current {@link #getTop() top} property. 12761 * 12762 * @param y The visual y position of this view, in pixels. 12763 */ 12764 public void setY(float y) { 12765 setTranslationY(y - mTop); 12766 } 12767 12768 /** 12769 * The visual z position of this view, in pixels. This is equivalent to the 12770 * {@link #setTranslationZ(float) translationZ} property plus the current 12771 * {@link #getElevation() elevation} property. 12772 * 12773 * @return The visual z position of this view, in pixels. 12774 */ 12775 @ViewDebug.ExportedProperty(category = "drawing") 12776 public float getZ() { 12777 return getElevation() + getTranslationZ(); 12778 } 12779 12780 /** 12781 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12782 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12783 * the x value passed in and the current {@link #getElevation() elevation} property. 12784 * 12785 * @param z The visual z position of this view, in pixels. 12786 */ 12787 public void setZ(float z) { 12788 setTranslationZ(z - getElevation()); 12789 } 12790 12791 /** 12792 * The base elevation of this view relative to its parent, in pixels. 12793 * 12794 * @return The base depth position of the view, in pixels. 12795 */ 12796 @ViewDebug.ExportedProperty(category = "drawing") 12797 public float getElevation() { 12798 return mRenderNode.getElevation(); 12799 } 12800 12801 /** 12802 * Sets the base elevation of this view, in pixels. 12803 * 12804 * @attr ref android.R.styleable#View_elevation 12805 */ 12806 public void setElevation(float elevation) { 12807 if (elevation != getElevation()) { 12808 invalidateViewProperty(true, false); 12809 mRenderNode.setElevation(elevation); 12810 invalidateViewProperty(false, true); 12811 12812 invalidateParentIfNeededAndWasQuickRejected(); 12813 } 12814 } 12815 12816 /** 12817 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12818 * This position is post-layout, in addition to wherever the object's 12819 * layout placed it. 12820 * 12821 * @return The horizontal position of this view relative to its left position, in pixels. 12822 */ 12823 @ViewDebug.ExportedProperty(category = "drawing") 12824 public float getTranslationX() { 12825 return mRenderNode.getTranslationX(); 12826 } 12827 12828 /** 12829 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12830 * This effectively positions the object post-layout, in addition to wherever the object's 12831 * layout placed it. 12832 * 12833 * @param translationX The horizontal position of this view relative to its left position, 12834 * in pixels. 12835 * 12836 * @attr ref android.R.styleable#View_translationX 12837 */ 12838 public void setTranslationX(float translationX) { 12839 if (translationX != getTranslationX()) { 12840 invalidateViewProperty(true, false); 12841 mRenderNode.setTranslationX(translationX); 12842 invalidateViewProperty(false, true); 12843 12844 invalidateParentIfNeededAndWasQuickRejected(); 12845 notifySubtreeAccessibilityStateChangedIfNeeded(); 12846 } 12847 } 12848 12849 /** 12850 * The vertical location of this view relative to its {@link #getTop() top} position. 12851 * This position is post-layout, in addition to wherever the object's 12852 * layout placed it. 12853 * 12854 * @return The vertical position of this view relative to its top position, 12855 * in pixels. 12856 */ 12857 @ViewDebug.ExportedProperty(category = "drawing") 12858 public float getTranslationY() { 12859 return mRenderNode.getTranslationY(); 12860 } 12861 12862 /** 12863 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12864 * This effectively positions the object post-layout, in addition to wherever the object's 12865 * layout placed it. 12866 * 12867 * @param translationY The vertical position of this view relative to its top position, 12868 * in pixels. 12869 * 12870 * @attr ref android.R.styleable#View_translationY 12871 */ 12872 public void setTranslationY(float translationY) { 12873 if (translationY != getTranslationY()) { 12874 invalidateViewProperty(true, false); 12875 mRenderNode.setTranslationY(translationY); 12876 invalidateViewProperty(false, true); 12877 12878 invalidateParentIfNeededAndWasQuickRejected(); 12879 notifySubtreeAccessibilityStateChangedIfNeeded(); 12880 } 12881 } 12882 12883 /** 12884 * The depth location of this view relative to its {@link #getElevation() elevation}. 12885 * 12886 * @return The depth of this view relative to its elevation. 12887 */ 12888 @ViewDebug.ExportedProperty(category = "drawing") 12889 public float getTranslationZ() { 12890 return mRenderNode.getTranslationZ(); 12891 } 12892 12893 /** 12894 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12895 * 12896 * @attr ref android.R.styleable#View_translationZ 12897 */ 12898 public void setTranslationZ(float translationZ) { 12899 if (translationZ != getTranslationZ()) { 12900 invalidateViewProperty(true, false); 12901 mRenderNode.setTranslationZ(translationZ); 12902 invalidateViewProperty(false, true); 12903 12904 invalidateParentIfNeededAndWasQuickRejected(); 12905 } 12906 } 12907 12908 /** @hide */ 12909 public void setAnimationMatrix(Matrix matrix) { 12910 invalidateViewProperty(true, false); 12911 mRenderNode.setAnimationMatrix(matrix); 12912 invalidateViewProperty(false, true); 12913 12914 invalidateParentIfNeededAndWasQuickRejected(); 12915 } 12916 12917 /** 12918 * Returns the current StateListAnimator if exists. 12919 * 12920 * @return StateListAnimator or null if it does not exists 12921 * @see #setStateListAnimator(android.animation.StateListAnimator) 12922 */ 12923 public StateListAnimator getStateListAnimator() { 12924 return mStateListAnimator; 12925 } 12926 12927 /** 12928 * Attaches the provided StateListAnimator to this View. 12929 * <p> 12930 * Any previously attached StateListAnimator will be detached. 12931 * 12932 * @param stateListAnimator The StateListAnimator to update the view 12933 * @see {@link android.animation.StateListAnimator} 12934 */ 12935 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12936 if (mStateListAnimator == stateListAnimator) { 12937 return; 12938 } 12939 if (mStateListAnimator != null) { 12940 mStateListAnimator.setTarget(null); 12941 } 12942 mStateListAnimator = stateListAnimator; 12943 if (stateListAnimator != null) { 12944 stateListAnimator.setTarget(this); 12945 if (isAttachedToWindow()) { 12946 stateListAnimator.setState(getDrawableState()); 12947 } 12948 } 12949 } 12950 12951 /** 12952 * Returns whether the Outline should be used to clip the contents of the View. 12953 * <p> 12954 * Note that this flag will only be respected if the View's Outline returns true from 12955 * {@link Outline#canClip()}. 12956 * 12957 * @see #setOutlineProvider(ViewOutlineProvider) 12958 * @see #setClipToOutline(boolean) 12959 */ 12960 public final boolean getClipToOutline() { 12961 return mRenderNode.getClipToOutline(); 12962 } 12963 12964 /** 12965 * Sets whether the View's Outline should be used to clip the contents of the View. 12966 * <p> 12967 * Only a single non-rectangular clip can be applied on a View at any time. 12968 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12969 * circular reveal} animation take priority over Outline clipping, and 12970 * child Outline clipping takes priority over Outline clipping done by a 12971 * parent. 12972 * <p> 12973 * Note that this flag will only be respected if the View's Outline returns true from 12974 * {@link Outline#canClip()}. 12975 * 12976 * @see #setOutlineProvider(ViewOutlineProvider) 12977 * @see #getClipToOutline() 12978 */ 12979 public void setClipToOutline(boolean clipToOutline) { 12980 damageInParent(); 12981 if (getClipToOutline() != clipToOutline) { 12982 mRenderNode.setClipToOutline(clipToOutline); 12983 } 12984 } 12985 12986 // correspond to the enum values of View_outlineProvider 12987 private static final int PROVIDER_BACKGROUND = 0; 12988 private static final int PROVIDER_NONE = 1; 12989 private static final int PROVIDER_BOUNDS = 2; 12990 private static final int PROVIDER_PADDED_BOUNDS = 3; 12991 private void setOutlineProviderFromAttribute(int providerInt) { 12992 switch (providerInt) { 12993 case PROVIDER_BACKGROUND: 12994 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12995 break; 12996 case PROVIDER_NONE: 12997 setOutlineProvider(null); 12998 break; 12999 case PROVIDER_BOUNDS: 13000 setOutlineProvider(ViewOutlineProvider.BOUNDS); 13001 break; 13002 case PROVIDER_PADDED_BOUNDS: 13003 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 13004 break; 13005 } 13006 } 13007 13008 /** 13009 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 13010 * the shape of the shadow it casts, and enables outline clipping. 13011 * <p> 13012 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 13013 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 13014 * outline provider with this method allows this behavior to be overridden. 13015 * <p> 13016 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 13017 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 13018 * <p> 13019 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 13020 * 13021 * @see #setClipToOutline(boolean) 13022 * @see #getClipToOutline() 13023 * @see #getOutlineProvider() 13024 */ 13025 public void setOutlineProvider(ViewOutlineProvider provider) { 13026 mOutlineProvider = provider; 13027 invalidateOutline(); 13028 } 13029 13030 /** 13031 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 13032 * that defines the shape of the shadow it casts, and enables outline clipping. 13033 * 13034 * @see #setOutlineProvider(ViewOutlineProvider) 13035 */ 13036 public ViewOutlineProvider getOutlineProvider() { 13037 return mOutlineProvider; 13038 } 13039 13040 /** 13041 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 13042 * 13043 * @see #setOutlineProvider(ViewOutlineProvider) 13044 */ 13045 public void invalidateOutline() { 13046 rebuildOutline(); 13047 13048 notifySubtreeAccessibilityStateChangedIfNeeded(); 13049 invalidateViewProperty(false, false); 13050 } 13051 13052 /** 13053 * Internal version of {@link #invalidateOutline()} which invalidates the 13054 * outline without invalidating the view itself. This is intended to be called from 13055 * within methods in the View class itself which are the result of the view being 13056 * invalidated already. For example, when we are drawing the background of a View, 13057 * we invalidate the outline in case it changed in the meantime, but we do not 13058 * need to invalidate the view because we're already drawing the background as part 13059 * of drawing the view in response to an earlier invalidation of the view. 13060 */ 13061 private void rebuildOutline() { 13062 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 13063 if (mAttachInfo == null) return; 13064 13065 if (mOutlineProvider == null) { 13066 // no provider, remove outline 13067 mRenderNode.setOutline(null); 13068 } else { 13069 final Outline outline = mAttachInfo.mTmpOutline; 13070 outline.setEmpty(); 13071 outline.setAlpha(1.0f); 13072 13073 mOutlineProvider.getOutline(this, outline); 13074 mRenderNode.setOutline(outline); 13075 } 13076 } 13077 13078 /** 13079 * HierarchyViewer only 13080 * 13081 * @hide 13082 */ 13083 @ViewDebug.ExportedProperty(category = "drawing") 13084 public boolean hasShadow() { 13085 return mRenderNode.hasShadow(); 13086 } 13087 13088 13089 /** @hide */ 13090 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13091 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13092 invalidateViewProperty(false, false); 13093 } 13094 13095 /** 13096 * Hit rectangle in parent's coordinates 13097 * 13098 * @param outRect The hit rectangle of the view. 13099 */ 13100 public void getHitRect(Rect outRect) { 13101 if (hasIdentityMatrix() || mAttachInfo == null) { 13102 outRect.set(mLeft, mTop, mRight, mBottom); 13103 } else { 13104 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13105 tmpRect.set(0, 0, getWidth(), getHeight()); 13106 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13107 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13108 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13109 } 13110 } 13111 13112 /** 13113 * Determines whether the given point, in local coordinates is inside the view. 13114 */ 13115 /*package*/ final boolean pointInView(float localX, float localY) { 13116 return pointInView(localX, localY, 0); 13117 } 13118 13119 /** 13120 * Utility method to determine whether the given point, in local coordinates, 13121 * is inside the view, where the area of the view is expanded by the slop factor. 13122 * This method is called while processing touch-move events to determine if the event 13123 * is still within the view. 13124 * 13125 * @hide 13126 */ 13127 public boolean pointInView(float localX, float localY, float slop) { 13128 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13129 localY < ((mBottom - mTop) + slop); 13130 } 13131 13132 /** 13133 * When a view has focus and the user navigates away from it, the next view is searched for 13134 * starting from the rectangle filled in by this method. 13135 * 13136 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13137 * of the view. However, if your view maintains some idea of internal selection, 13138 * such as a cursor, or a selected row or column, you should override this method and 13139 * fill in a more specific rectangle. 13140 * 13141 * @param r The rectangle to fill in, in this view's coordinates. 13142 */ 13143 public void getFocusedRect(Rect r) { 13144 getDrawingRect(r); 13145 } 13146 13147 /** 13148 * If some part of this view is not clipped by any of its parents, then 13149 * return that area in r in global (root) coordinates. To convert r to local 13150 * coordinates (without taking possible View rotations into account), offset 13151 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13152 * If the view is completely clipped or translated out, return false. 13153 * 13154 * @param r If true is returned, r holds the global coordinates of the 13155 * visible portion of this view. 13156 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13157 * between this view and its root. globalOffet may be null. 13158 * @return true if r is non-empty (i.e. part of the view is visible at the 13159 * root level. 13160 */ 13161 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13162 int width = mRight - mLeft; 13163 int height = mBottom - mTop; 13164 if (width > 0 && height > 0) { 13165 r.set(0, 0, width, height); 13166 if (globalOffset != null) { 13167 globalOffset.set(-mScrollX, -mScrollY); 13168 } 13169 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13170 } 13171 return false; 13172 } 13173 13174 public final boolean getGlobalVisibleRect(Rect r) { 13175 return getGlobalVisibleRect(r, null); 13176 } 13177 13178 public final boolean getLocalVisibleRect(Rect r) { 13179 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13180 if (getGlobalVisibleRect(r, offset)) { 13181 r.offset(-offset.x, -offset.y); // make r local 13182 return true; 13183 } 13184 return false; 13185 } 13186 13187 /** 13188 * Offset this view's vertical location by the specified number of pixels. 13189 * 13190 * @param offset the number of pixels to offset the view by 13191 */ 13192 public void offsetTopAndBottom(int offset) { 13193 if (offset != 0) { 13194 final boolean matrixIsIdentity = hasIdentityMatrix(); 13195 if (matrixIsIdentity) { 13196 if (isHardwareAccelerated()) { 13197 invalidateViewProperty(false, false); 13198 } else { 13199 final ViewParent p = mParent; 13200 if (p != null && mAttachInfo != null) { 13201 final Rect r = mAttachInfo.mTmpInvalRect; 13202 int minTop; 13203 int maxBottom; 13204 int yLoc; 13205 if (offset < 0) { 13206 minTop = mTop + offset; 13207 maxBottom = mBottom; 13208 yLoc = offset; 13209 } else { 13210 minTop = mTop; 13211 maxBottom = mBottom + offset; 13212 yLoc = 0; 13213 } 13214 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13215 p.invalidateChild(this, r); 13216 } 13217 } 13218 } else { 13219 invalidateViewProperty(false, false); 13220 } 13221 13222 mTop += offset; 13223 mBottom += offset; 13224 mRenderNode.offsetTopAndBottom(offset); 13225 if (isHardwareAccelerated()) { 13226 invalidateViewProperty(false, false); 13227 invalidateParentIfNeededAndWasQuickRejected(); 13228 } else { 13229 if (!matrixIsIdentity) { 13230 invalidateViewProperty(false, true); 13231 } 13232 invalidateParentIfNeeded(); 13233 } 13234 notifySubtreeAccessibilityStateChangedIfNeeded(); 13235 } 13236 } 13237 13238 /** 13239 * Offset this view's horizontal location by the specified amount of pixels. 13240 * 13241 * @param offset the number of pixels to offset the view by 13242 */ 13243 public void offsetLeftAndRight(int offset) { 13244 if (offset != 0) { 13245 final boolean matrixIsIdentity = hasIdentityMatrix(); 13246 if (matrixIsIdentity) { 13247 if (isHardwareAccelerated()) { 13248 invalidateViewProperty(false, false); 13249 } else { 13250 final ViewParent p = mParent; 13251 if (p != null && mAttachInfo != null) { 13252 final Rect r = mAttachInfo.mTmpInvalRect; 13253 int minLeft; 13254 int maxRight; 13255 if (offset < 0) { 13256 minLeft = mLeft + offset; 13257 maxRight = mRight; 13258 } else { 13259 minLeft = mLeft; 13260 maxRight = mRight + offset; 13261 } 13262 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13263 p.invalidateChild(this, r); 13264 } 13265 } 13266 } else { 13267 invalidateViewProperty(false, false); 13268 } 13269 13270 mLeft += offset; 13271 mRight += offset; 13272 mRenderNode.offsetLeftAndRight(offset); 13273 if (isHardwareAccelerated()) { 13274 invalidateViewProperty(false, false); 13275 invalidateParentIfNeededAndWasQuickRejected(); 13276 } else { 13277 if (!matrixIsIdentity) { 13278 invalidateViewProperty(false, true); 13279 } 13280 invalidateParentIfNeeded(); 13281 } 13282 notifySubtreeAccessibilityStateChangedIfNeeded(); 13283 } 13284 } 13285 13286 /** 13287 * Get the LayoutParams associated with this view. All views should have 13288 * layout parameters. These supply parameters to the <i>parent</i> of this 13289 * view specifying how it should be arranged. There are many subclasses of 13290 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13291 * of ViewGroup that are responsible for arranging their children. 13292 * 13293 * This method may return null if this View is not attached to a parent 13294 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13295 * was not invoked successfully. When a View is attached to a parent 13296 * ViewGroup, this method must not return null. 13297 * 13298 * @return The LayoutParams associated with this view, or null if no 13299 * parameters have been set yet 13300 */ 13301 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13302 public ViewGroup.LayoutParams getLayoutParams() { 13303 return mLayoutParams; 13304 } 13305 13306 /** 13307 * Set the layout parameters associated with this view. These supply 13308 * parameters to the <i>parent</i> of this view specifying how it should be 13309 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13310 * correspond to the different subclasses of ViewGroup that are responsible 13311 * for arranging their children. 13312 * 13313 * @param params The layout parameters for this view, cannot be null 13314 */ 13315 public void setLayoutParams(ViewGroup.LayoutParams params) { 13316 if (params == null) { 13317 throw new NullPointerException("Layout parameters cannot be null"); 13318 } 13319 mLayoutParams = params; 13320 resolveLayoutParams(); 13321 if (mParent instanceof ViewGroup) { 13322 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13323 } 13324 requestLayout(); 13325 } 13326 13327 /** 13328 * Resolve the layout parameters depending on the resolved layout direction 13329 * 13330 * @hide 13331 */ 13332 public void resolveLayoutParams() { 13333 if (mLayoutParams != null) { 13334 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13335 } 13336 } 13337 13338 /** 13339 * Set the scrolled position of your view. This will cause a call to 13340 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13341 * invalidated. 13342 * @param x the x position to scroll to 13343 * @param y the y position to scroll to 13344 */ 13345 public void scrollTo(int x, int y) { 13346 if (mScrollX != x || mScrollY != y) { 13347 int oldX = mScrollX; 13348 int oldY = mScrollY; 13349 mScrollX = x; 13350 mScrollY = y; 13351 invalidateParentCaches(); 13352 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13353 if (!awakenScrollBars()) { 13354 postInvalidateOnAnimation(); 13355 } 13356 } 13357 } 13358 13359 /** 13360 * Move the scrolled position of your view. This will cause a call to 13361 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13362 * invalidated. 13363 * @param x the amount of pixels to scroll by horizontally 13364 * @param y the amount of pixels to scroll by vertically 13365 */ 13366 public void scrollBy(int x, int y) { 13367 scrollTo(mScrollX + x, mScrollY + y); 13368 } 13369 13370 /** 13371 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13372 * animation to fade the scrollbars out after a default delay. If a subclass 13373 * provides animated scrolling, the start delay should equal the duration 13374 * of the scrolling animation.</p> 13375 * 13376 * <p>The animation starts only if at least one of the scrollbars is 13377 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13378 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13379 * this method returns true, and false otherwise. If the animation is 13380 * started, this method calls {@link #invalidate()}; in that case the 13381 * caller should not call {@link #invalidate()}.</p> 13382 * 13383 * <p>This method should be invoked every time a subclass directly updates 13384 * the scroll parameters.</p> 13385 * 13386 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13387 * and {@link #scrollTo(int, int)}.</p> 13388 * 13389 * @return true if the animation is played, false otherwise 13390 * 13391 * @see #awakenScrollBars(int) 13392 * @see #scrollBy(int, int) 13393 * @see #scrollTo(int, int) 13394 * @see #isHorizontalScrollBarEnabled() 13395 * @see #isVerticalScrollBarEnabled() 13396 * @see #setHorizontalScrollBarEnabled(boolean) 13397 * @see #setVerticalScrollBarEnabled(boolean) 13398 */ 13399 protected boolean awakenScrollBars() { 13400 return mScrollCache != null && 13401 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13402 } 13403 13404 /** 13405 * Trigger the scrollbars to draw. 13406 * This method differs from awakenScrollBars() only in its default duration. 13407 * initialAwakenScrollBars() will show the scroll bars for longer than 13408 * usual to give the user more of a chance to notice them. 13409 * 13410 * @return true if the animation is played, false otherwise. 13411 */ 13412 private boolean initialAwakenScrollBars() { 13413 return mScrollCache != null && 13414 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13415 } 13416 13417 /** 13418 * <p> 13419 * Trigger the scrollbars to draw. When invoked this method starts an 13420 * animation to fade the scrollbars out after a fixed delay. If a subclass 13421 * provides animated scrolling, the start delay should equal the duration of 13422 * the scrolling animation. 13423 * </p> 13424 * 13425 * <p> 13426 * The animation starts only if at least one of the scrollbars is enabled, 13427 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13428 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13429 * this method returns true, and false otherwise. If the animation is 13430 * started, this method calls {@link #invalidate()}; in that case the caller 13431 * should not call {@link #invalidate()}. 13432 * </p> 13433 * 13434 * <p> 13435 * This method should be invoked every time a subclass directly updates the 13436 * scroll parameters. 13437 * </p> 13438 * 13439 * @param startDelay the delay, in milliseconds, after which the animation 13440 * should start; when the delay is 0, the animation starts 13441 * immediately 13442 * @return true if the animation is played, false otherwise 13443 * 13444 * @see #scrollBy(int, int) 13445 * @see #scrollTo(int, int) 13446 * @see #isHorizontalScrollBarEnabled() 13447 * @see #isVerticalScrollBarEnabled() 13448 * @see #setHorizontalScrollBarEnabled(boolean) 13449 * @see #setVerticalScrollBarEnabled(boolean) 13450 */ 13451 protected boolean awakenScrollBars(int startDelay) { 13452 return awakenScrollBars(startDelay, true); 13453 } 13454 13455 /** 13456 * <p> 13457 * Trigger the scrollbars to draw. When invoked this method starts an 13458 * animation to fade the scrollbars out after a fixed delay. If a subclass 13459 * provides animated scrolling, the start delay should equal the duration of 13460 * the scrolling animation. 13461 * </p> 13462 * 13463 * <p> 13464 * The animation starts only if at least one of the scrollbars is enabled, 13465 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13466 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13467 * this method returns true, and false otherwise. If the animation is 13468 * started, this method calls {@link #invalidate()} if the invalidate parameter 13469 * is set to true; in that case the caller 13470 * should not call {@link #invalidate()}. 13471 * </p> 13472 * 13473 * <p> 13474 * This method should be invoked every time a subclass directly updates the 13475 * scroll parameters. 13476 * </p> 13477 * 13478 * @param startDelay the delay, in milliseconds, after which the animation 13479 * should start; when the delay is 0, the animation starts 13480 * immediately 13481 * 13482 * @param invalidate Whether this method should call invalidate 13483 * 13484 * @return true if the animation is played, false otherwise 13485 * 13486 * @see #scrollBy(int, int) 13487 * @see #scrollTo(int, int) 13488 * @see #isHorizontalScrollBarEnabled() 13489 * @see #isVerticalScrollBarEnabled() 13490 * @see #setHorizontalScrollBarEnabled(boolean) 13491 * @see #setVerticalScrollBarEnabled(boolean) 13492 */ 13493 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13494 final ScrollabilityCache scrollCache = mScrollCache; 13495 13496 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13497 return false; 13498 } 13499 13500 if (scrollCache.scrollBar == null) { 13501 scrollCache.scrollBar = new ScrollBarDrawable(); 13502 scrollCache.scrollBar.setState(getDrawableState()); 13503 scrollCache.scrollBar.setCallback(this); 13504 } 13505 13506 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13507 13508 if (invalidate) { 13509 // Invalidate to show the scrollbars 13510 postInvalidateOnAnimation(); 13511 } 13512 13513 if (scrollCache.state == ScrollabilityCache.OFF) { 13514 // FIXME: this is copied from WindowManagerService. 13515 // We should get this value from the system when it 13516 // is possible to do so. 13517 final int KEY_REPEAT_FIRST_DELAY = 750; 13518 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13519 } 13520 13521 // Tell mScrollCache when we should start fading. This may 13522 // extend the fade start time if one was already scheduled 13523 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13524 scrollCache.fadeStartTime = fadeStartTime; 13525 scrollCache.state = ScrollabilityCache.ON; 13526 13527 // Schedule our fader to run, unscheduling any old ones first 13528 if (mAttachInfo != null) { 13529 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13530 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13531 } 13532 13533 return true; 13534 } 13535 13536 return false; 13537 } 13538 13539 /** 13540 * Do not invalidate views which are not visible and which are not running an animation. They 13541 * will not get drawn and they should not set dirty flags as if they will be drawn 13542 */ 13543 private boolean skipInvalidate() { 13544 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13545 (!(mParent instanceof ViewGroup) || 13546 !((ViewGroup) mParent).isViewTransitioning(this)); 13547 } 13548 13549 /** 13550 * Mark the area defined by dirty as needing to be drawn. If the view is 13551 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13552 * point in the future. 13553 * <p> 13554 * This must be called from a UI thread. To call from a non-UI thread, call 13555 * {@link #postInvalidate()}. 13556 * <p> 13557 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13558 * {@code dirty}. 13559 * 13560 * @param dirty the rectangle representing the bounds of the dirty region 13561 */ 13562 public void invalidate(Rect dirty) { 13563 final int scrollX = mScrollX; 13564 final int scrollY = mScrollY; 13565 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13566 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13567 } 13568 13569 /** 13570 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13571 * coordinates of the dirty rect are relative to the view. If the view is 13572 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13573 * point in the future. 13574 * <p> 13575 * This must be called from a UI thread. To call from a non-UI thread, call 13576 * {@link #postInvalidate()}. 13577 * 13578 * @param l the left position of the dirty region 13579 * @param t the top position of the dirty region 13580 * @param r the right position of the dirty region 13581 * @param b the bottom position of the dirty region 13582 */ 13583 public void invalidate(int l, int t, int r, int b) { 13584 final int scrollX = mScrollX; 13585 final int scrollY = mScrollY; 13586 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13587 } 13588 13589 /** 13590 * Invalidate the whole view. If the view is visible, 13591 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13592 * the future. 13593 * <p> 13594 * This must be called from a UI thread. To call from a non-UI thread, call 13595 * {@link #postInvalidate()}. 13596 */ 13597 public void invalidate() { 13598 invalidate(true); 13599 } 13600 13601 /** 13602 * This is where the invalidate() work actually happens. A full invalidate() 13603 * causes the drawing cache to be invalidated, but this function can be 13604 * called with invalidateCache set to false to skip that invalidation step 13605 * for cases that do not need it (for example, a component that remains at 13606 * the same dimensions with the same content). 13607 * 13608 * @param invalidateCache Whether the drawing cache for this view should be 13609 * invalidated as well. This is usually true for a full 13610 * invalidate, but may be set to false if the View's contents or 13611 * dimensions have not changed. 13612 */ 13613 void invalidate(boolean invalidateCache) { 13614 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13615 } 13616 13617 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13618 boolean fullInvalidate) { 13619 if (mGhostView != null) { 13620 mGhostView.invalidate(true); 13621 return; 13622 } 13623 13624 if (skipInvalidate()) { 13625 return; 13626 } 13627 13628 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13629 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13630 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13631 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13632 if (fullInvalidate) { 13633 mLastIsOpaque = isOpaque(); 13634 mPrivateFlags &= ~PFLAG_DRAWN; 13635 } 13636 13637 mPrivateFlags |= PFLAG_DIRTY; 13638 13639 if (invalidateCache) { 13640 mPrivateFlags |= PFLAG_INVALIDATED; 13641 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13642 } 13643 13644 // Propagate the damage rectangle to the parent view. 13645 final AttachInfo ai = mAttachInfo; 13646 final ViewParent p = mParent; 13647 if (p != null && ai != null && l < r && t < b) { 13648 final Rect damage = ai.mTmpInvalRect; 13649 damage.set(l, t, r, b); 13650 p.invalidateChild(this, damage); 13651 } 13652 13653 // Damage the entire projection receiver, if necessary. 13654 if (mBackground != null && mBackground.isProjected()) { 13655 final View receiver = getProjectionReceiver(); 13656 if (receiver != null) { 13657 receiver.damageInParent(); 13658 } 13659 } 13660 13661 // Damage the entire IsolatedZVolume receiving this view's shadow. 13662 if (isHardwareAccelerated() && getZ() != 0) { 13663 damageShadowReceiver(); 13664 } 13665 } 13666 } 13667 13668 /** 13669 * @return this view's projection receiver, or {@code null} if none exists 13670 */ 13671 private View getProjectionReceiver() { 13672 ViewParent p = getParent(); 13673 while (p != null && p instanceof View) { 13674 final View v = (View) p; 13675 if (v.isProjectionReceiver()) { 13676 return v; 13677 } 13678 p = p.getParent(); 13679 } 13680 13681 return null; 13682 } 13683 13684 /** 13685 * @return whether the view is a projection receiver 13686 */ 13687 private boolean isProjectionReceiver() { 13688 return mBackground != null; 13689 } 13690 13691 /** 13692 * Damage area of the screen that can be covered by this View's shadow. 13693 * 13694 * This method will guarantee that any changes to shadows cast by a View 13695 * are damaged on the screen for future redraw. 13696 */ 13697 private void damageShadowReceiver() { 13698 final AttachInfo ai = mAttachInfo; 13699 if (ai != null) { 13700 ViewParent p = getParent(); 13701 if (p != null && p instanceof ViewGroup) { 13702 final ViewGroup vg = (ViewGroup) p; 13703 vg.damageInParent(); 13704 } 13705 } 13706 } 13707 13708 /** 13709 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13710 * set any flags or handle all of the cases handled by the default invalidation methods. 13711 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13712 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13713 * walk up the hierarchy, transforming the dirty rect as necessary. 13714 * 13715 * The method also handles normal invalidation logic if display list properties are not 13716 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13717 * backup approach, to handle these cases used in the various property-setting methods. 13718 * 13719 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13720 * are not being used in this view 13721 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13722 * list properties are not being used in this view 13723 */ 13724 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13725 if (!isHardwareAccelerated() 13726 || !mRenderNode.isValid() 13727 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13728 if (invalidateParent) { 13729 invalidateParentCaches(); 13730 } 13731 if (forceRedraw) { 13732 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13733 } 13734 invalidate(false); 13735 } else { 13736 damageInParent(); 13737 } 13738 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13739 damageShadowReceiver(); 13740 } 13741 } 13742 13743 /** 13744 * Tells the parent view to damage this view's bounds. 13745 * 13746 * @hide 13747 */ 13748 protected void damageInParent() { 13749 final AttachInfo ai = mAttachInfo; 13750 final ViewParent p = mParent; 13751 if (p != null && ai != null) { 13752 final Rect r = ai.mTmpInvalRect; 13753 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13754 if (mParent instanceof ViewGroup) { 13755 ((ViewGroup) mParent).damageChild(this, r); 13756 } else { 13757 mParent.invalidateChild(this, r); 13758 } 13759 } 13760 } 13761 13762 /** 13763 * Utility method to transform a given Rect by the current matrix of this view. 13764 */ 13765 void transformRect(final Rect rect) { 13766 if (!getMatrix().isIdentity()) { 13767 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13768 boundingRect.set(rect); 13769 getMatrix().mapRect(boundingRect); 13770 rect.set((int) Math.floor(boundingRect.left), 13771 (int) Math.floor(boundingRect.top), 13772 (int) Math.ceil(boundingRect.right), 13773 (int) Math.ceil(boundingRect.bottom)); 13774 } 13775 } 13776 13777 /** 13778 * Used to indicate that the parent of this view should clear its caches. This functionality 13779 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13780 * which is necessary when various parent-managed properties of the view change, such as 13781 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13782 * clears the parent caches and does not causes an invalidate event. 13783 * 13784 * @hide 13785 */ 13786 protected void invalidateParentCaches() { 13787 if (mParent instanceof View) { 13788 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13789 } 13790 } 13791 13792 /** 13793 * Used to indicate that the parent of this view should be invalidated. This functionality 13794 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13795 * which is necessary when various parent-managed properties of the view change, such as 13796 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13797 * an invalidation event to the parent. 13798 * 13799 * @hide 13800 */ 13801 protected void invalidateParentIfNeeded() { 13802 if (isHardwareAccelerated() && mParent instanceof View) { 13803 ((View) mParent).invalidate(true); 13804 } 13805 } 13806 13807 /** 13808 * @hide 13809 */ 13810 protected void invalidateParentIfNeededAndWasQuickRejected() { 13811 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13812 // View was rejected last time it was drawn by its parent; this may have changed 13813 invalidateParentIfNeeded(); 13814 } 13815 } 13816 13817 /** 13818 * Indicates whether this View is opaque. An opaque View guarantees that it will 13819 * draw all the pixels overlapping its bounds using a fully opaque color. 13820 * 13821 * Subclasses of View should override this method whenever possible to indicate 13822 * whether an instance is opaque. Opaque Views are treated in a special way by 13823 * the View hierarchy, possibly allowing it to perform optimizations during 13824 * invalidate/draw passes. 13825 * 13826 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13827 */ 13828 @ViewDebug.ExportedProperty(category = "drawing") 13829 public boolean isOpaque() { 13830 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13831 getFinalAlpha() >= 1.0f; 13832 } 13833 13834 /** 13835 * @hide 13836 */ 13837 protected void computeOpaqueFlags() { 13838 // Opaque if: 13839 // - Has a background 13840 // - Background is opaque 13841 // - Doesn't have scrollbars or scrollbars overlay 13842 13843 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13844 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13845 } else { 13846 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13847 } 13848 13849 final int flags = mViewFlags; 13850 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13851 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13852 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13853 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13854 } else { 13855 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13856 } 13857 } 13858 13859 /** 13860 * @hide 13861 */ 13862 protected boolean hasOpaqueScrollbars() { 13863 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13864 } 13865 13866 /** 13867 * @return A handler associated with the thread running the View. This 13868 * handler can be used to pump events in the UI events queue. 13869 */ 13870 public Handler getHandler() { 13871 final AttachInfo attachInfo = mAttachInfo; 13872 if (attachInfo != null) { 13873 return attachInfo.mHandler; 13874 } 13875 return null; 13876 } 13877 13878 /** 13879 * Returns the queue of runnable for this view. 13880 * 13881 * @return the queue of runnables for this view 13882 */ 13883 private HandlerActionQueue getRunQueue() { 13884 if (mRunQueue == null) { 13885 mRunQueue = new HandlerActionQueue(); 13886 } 13887 return mRunQueue; 13888 } 13889 13890 /** 13891 * Gets the view root associated with the View. 13892 * @return The view root, or null if none. 13893 * @hide 13894 */ 13895 public ViewRootImpl getViewRootImpl() { 13896 if (mAttachInfo != null) { 13897 return mAttachInfo.mViewRootImpl; 13898 } 13899 return null; 13900 } 13901 13902 /** 13903 * @hide 13904 */ 13905 public ThreadedRenderer getThreadedRenderer() { 13906 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 13907 } 13908 13909 /** 13910 * <p>Causes the Runnable to be added to the message queue. 13911 * The runnable will be run on the user interface thread.</p> 13912 * 13913 * @param action The Runnable that will be executed. 13914 * 13915 * @return Returns true if the Runnable was successfully placed in to the 13916 * message queue. Returns false on failure, usually because the 13917 * looper processing the message queue is exiting. 13918 * 13919 * @see #postDelayed 13920 * @see #removeCallbacks 13921 */ 13922 public boolean post(Runnable action) { 13923 final AttachInfo attachInfo = mAttachInfo; 13924 if (attachInfo != null) { 13925 return attachInfo.mHandler.post(action); 13926 } 13927 13928 // Postpone the runnable until we know on which thread it needs to run. 13929 // Assume that the runnable will be successfully placed after attach. 13930 getRunQueue().post(action); 13931 return true; 13932 } 13933 13934 /** 13935 * <p>Causes the Runnable to be added to the message queue, to be run 13936 * after the specified amount of time elapses. 13937 * The runnable will be run on the user interface thread.</p> 13938 * 13939 * @param action The Runnable that will be executed. 13940 * @param delayMillis The delay (in milliseconds) until the Runnable 13941 * will be executed. 13942 * 13943 * @return true if the Runnable was successfully placed in to the 13944 * message queue. Returns false on failure, usually because the 13945 * looper processing the message queue is exiting. Note that a 13946 * result of true does not mean the Runnable will be processed -- 13947 * if the looper is quit before the delivery time of the message 13948 * occurs then the message will be dropped. 13949 * 13950 * @see #post 13951 * @see #removeCallbacks 13952 */ 13953 public boolean postDelayed(Runnable action, long delayMillis) { 13954 final AttachInfo attachInfo = mAttachInfo; 13955 if (attachInfo != null) { 13956 return attachInfo.mHandler.postDelayed(action, delayMillis); 13957 } 13958 13959 // Postpone the runnable until we know on which thread it needs to run. 13960 // Assume that the runnable will be successfully placed after attach. 13961 getRunQueue().postDelayed(action, delayMillis); 13962 return true; 13963 } 13964 13965 /** 13966 * <p>Causes the Runnable to execute on the next animation time step. 13967 * The runnable will be run on the user interface thread.</p> 13968 * 13969 * @param action The Runnable that will be executed. 13970 * 13971 * @see #postOnAnimationDelayed 13972 * @see #removeCallbacks 13973 */ 13974 public void postOnAnimation(Runnable action) { 13975 final AttachInfo attachInfo = mAttachInfo; 13976 if (attachInfo != null) { 13977 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13978 Choreographer.CALLBACK_ANIMATION, action, null); 13979 } else { 13980 // Postpone the runnable until we know 13981 // on which thread it needs to run. 13982 getRunQueue().post(action); 13983 } 13984 } 13985 13986 /** 13987 * <p>Causes the Runnable to execute on the next animation time step, 13988 * after the specified amount of time elapses. 13989 * The runnable will be run on the user interface thread.</p> 13990 * 13991 * @param action The Runnable that will be executed. 13992 * @param delayMillis The delay (in milliseconds) until the Runnable 13993 * will be executed. 13994 * 13995 * @see #postOnAnimation 13996 * @see #removeCallbacks 13997 */ 13998 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13999 final AttachInfo attachInfo = mAttachInfo; 14000 if (attachInfo != null) { 14001 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 14002 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 14003 } else { 14004 // Postpone the runnable until we know 14005 // on which thread it needs to run. 14006 getRunQueue().postDelayed(action, delayMillis); 14007 } 14008 } 14009 14010 /** 14011 * <p>Removes the specified Runnable from the message queue.</p> 14012 * 14013 * @param action The Runnable to remove from the message handling queue 14014 * 14015 * @return true if this view could ask the Handler to remove the Runnable, 14016 * false otherwise. When the returned value is true, the Runnable 14017 * may or may not have been actually removed from the message queue 14018 * (for instance, if the Runnable was not in the queue already.) 14019 * 14020 * @see #post 14021 * @see #postDelayed 14022 * @see #postOnAnimation 14023 * @see #postOnAnimationDelayed 14024 */ 14025 public boolean removeCallbacks(Runnable action) { 14026 if (action != null) { 14027 final AttachInfo attachInfo = mAttachInfo; 14028 if (attachInfo != null) { 14029 attachInfo.mHandler.removeCallbacks(action); 14030 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 14031 Choreographer.CALLBACK_ANIMATION, action, null); 14032 } 14033 getRunQueue().removeCallbacks(action); 14034 } 14035 return true; 14036 } 14037 14038 /** 14039 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 14040 * Use this to invalidate the View from a non-UI thread.</p> 14041 * 14042 * <p>This method can be invoked from outside of the UI thread 14043 * only when this View is attached to a window.</p> 14044 * 14045 * @see #invalidate() 14046 * @see #postInvalidateDelayed(long) 14047 */ 14048 public void postInvalidate() { 14049 postInvalidateDelayed(0); 14050 } 14051 14052 /** 14053 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14054 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 14055 * 14056 * <p>This method can be invoked from outside of the UI thread 14057 * only when this View is attached to a window.</p> 14058 * 14059 * @param left The left coordinate of the rectangle to invalidate. 14060 * @param top The top coordinate of the rectangle to invalidate. 14061 * @param right The right coordinate of the rectangle to invalidate. 14062 * @param bottom The bottom coordinate of the rectangle to invalidate. 14063 * 14064 * @see #invalidate(int, int, int, int) 14065 * @see #invalidate(Rect) 14066 * @see #postInvalidateDelayed(long, int, int, int, int) 14067 */ 14068 public void postInvalidate(int left, int top, int right, int bottom) { 14069 postInvalidateDelayed(0, left, top, right, bottom); 14070 } 14071 14072 /** 14073 * <p>Cause an invalidate to happen on a subsequent cycle through the event 14074 * loop. Waits for the specified amount of time.</p> 14075 * 14076 * <p>This method can be invoked from outside of the UI thread 14077 * only when this View is attached to a window.</p> 14078 * 14079 * @param delayMilliseconds the duration in milliseconds to delay the 14080 * invalidation by 14081 * 14082 * @see #invalidate() 14083 * @see #postInvalidate() 14084 */ 14085 public void postInvalidateDelayed(long delayMilliseconds) { 14086 // We try only with the AttachInfo because there's no point in invalidating 14087 // if we are not attached to our window 14088 final AttachInfo attachInfo = mAttachInfo; 14089 if (attachInfo != null) { 14090 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14091 } 14092 } 14093 14094 /** 14095 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14096 * through the event loop. Waits for the specified amount of time.</p> 14097 * 14098 * <p>This method can be invoked from outside of the UI thread 14099 * only when this View is attached to a window.</p> 14100 * 14101 * @param delayMilliseconds the duration in milliseconds to delay the 14102 * invalidation by 14103 * @param left The left coordinate of the rectangle to invalidate. 14104 * @param top The top coordinate of the rectangle to invalidate. 14105 * @param right The right coordinate of the rectangle to invalidate. 14106 * @param bottom The bottom coordinate of the rectangle to invalidate. 14107 * 14108 * @see #invalidate(int, int, int, int) 14109 * @see #invalidate(Rect) 14110 * @see #postInvalidate(int, int, int, int) 14111 */ 14112 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14113 int right, int bottom) { 14114 14115 // We try only with the AttachInfo because there's no point in invalidating 14116 // if we are not attached to our window 14117 final AttachInfo attachInfo = mAttachInfo; 14118 if (attachInfo != null) { 14119 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14120 info.target = this; 14121 info.left = left; 14122 info.top = top; 14123 info.right = right; 14124 info.bottom = bottom; 14125 14126 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14127 } 14128 } 14129 14130 /** 14131 * <p>Cause an invalidate to happen on the next animation time step, typically the 14132 * next display frame.</p> 14133 * 14134 * <p>This method can be invoked from outside of the UI thread 14135 * only when this View is attached to a window.</p> 14136 * 14137 * @see #invalidate() 14138 */ 14139 public void postInvalidateOnAnimation() { 14140 // We try only with the AttachInfo because there's no point in invalidating 14141 // if we are not attached to our window 14142 final AttachInfo attachInfo = mAttachInfo; 14143 if (attachInfo != null) { 14144 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14145 } 14146 } 14147 14148 /** 14149 * <p>Cause an invalidate of the specified area to happen on the next animation 14150 * time step, typically the next display frame.</p> 14151 * 14152 * <p>This method can be invoked from outside of the UI thread 14153 * only when this View is attached to a window.</p> 14154 * 14155 * @param left The left coordinate of the rectangle to invalidate. 14156 * @param top The top coordinate of the rectangle to invalidate. 14157 * @param right The right coordinate of the rectangle to invalidate. 14158 * @param bottom The bottom coordinate of the rectangle to invalidate. 14159 * 14160 * @see #invalidate(int, int, int, int) 14161 * @see #invalidate(Rect) 14162 */ 14163 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14164 // We try only with the AttachInfo because there's no point in invalidating 14165 // if we are not attached to our window 14166 final AttachInfo attachInfo = mAttachInfo; 14167 if (attachInfo != null) { 14168 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14169 info.target = this; 14170 info.left = left; 14171 info.top = top; 14172 info.right = right; 14173 info.bottom = bottom; 14174 14175 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14176 } 14177 } 14178 14179 /** 14180 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14181 * This event is sent at most once every 14182 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14183 */ 14184 private void postSendViewScrolledAccessibilityEventCallback() { 14185 if (mSendViewScrolledAccessibilityEvent == null) { 14186 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14187 } 14188 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14189 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14190 postDelayed(mSendViewScrolledAccessibilityEvent, 14191 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14192 } 14193 } 14194 14195 /** 14196 * Called by a parent to request that a child update its values for mScrollX 14197 * and mScrollY if necessary. This will typically be done if the child is 14198 * animating a scroll using a {@link android.widget.Scroller Scroller} 14199 * object. 14200 */ 14201 public void computeScroll() { 14202 } 14203 14204 /** 14205 * <p>Indicate whether the horizontal edges are faded when the view is 14206 * scrolled horizontally.</p> 14207 * 14208 * @return true if the horizontal edges should are faded on scroll, false 14209 * otherwise 14210 * 14211 * @see #setHorizontalFadingEdgeEnabled(boolean) 14212 * 14213 * @attr ref android.R.styleable#View_requiresFadingEdge 14214 */ 14215 public boolean isHorizontalFadingEdgeEnabled() { 14216 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14217 } 14218 14219 /** 14220 * <p>Define whether the horizontal edges should be faded when this view 14221 * is scrolled horizontally.</p> 14222 * 14223 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14224 * be faded when the view is scrolled 14225 * horizontally 14226 * 14227 * @see #isHorizontalFadingEdgeEnabled() 14228 * 14229 * @attr ref android.R.styleable#View_requiresFadingEdge 14230 */ 14231 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14232 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14233 if (horizontalFadingEdgeEnabled) { 14234 initScrollCache(); 14235 } 14236 14237 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14238 } 14239 } 14240 14241 /** 14242 * <p>Indicate whether the vertical edges are faded when the view is 14243 * scrolled horizontally.</p> 14244 * 14245 * @return true if the vertical edges should are faded on scroll, false 14246 * otherwise 14247 * 14248 * @see #setVerticalFadingEdgeEnabled(boolean) 14249 * 14250 * @attr ref android.R.styleable#View_requiresFadingEdge 14251 */ 14252 public boolean isVerticalFadingEdgeEnabled() { 14253 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14254 } 14255 14256 /** 14257 * <p>Define whether the vertical edges should be faded when this view 14258 * is scrolled vertically.</p> 14259 * 14260 * @param verticalFadingEdgeEnabled true if the vertical edges should 14261 * be faded when the view is scrolled 14262 * vertically 14263 * 14264 * @see #isVerticalFadingEdgeEnabled() 14265 * 14266 * @attr ref android.R.styleable#View_requiresFadingEdge 14267 */ 14268 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14269 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14270 if (verticalFadingEdgeEnabled) { 14271 initScrollCache(); 14272 } 14273 14274 mViewFlags ^= FADING_EDGE_VERTICAL; 14275 } 14276 } 14277 14278 /** 14279 * Returns the strength, or intensity, of the top faded edge. The strength is 14280 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14281 * returns 0.0 or 1.0 but no value in between. 14282 * 14283 * Subclasses should override this method to provide a smoother fade transition 14284 * when scrolling occurs. 14285 * 14286 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14287 */ 14288 protected float getTopFadingEdgeStrength() { 14289 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14290 } 14291 14292 /** 14293 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14294 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14295 * returns 0.0 or 1.0 but no value in between. 14296 * 14297 * Subclasses should override this method to provide a smoother fade transition 14298 * when scrolling occurs. 14299 * 14300 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14301 */ 14302 protected float getBottomFadingEdgeStrength() { 14303 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14304 computeVerticalScrollRange() ? 1.0f : 0.0f; 14305 } 14306 14307 /** 14308 * Returns the strength, or intensity, of the left faded edge. The strength is 14309 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14310 * returns 0.0 or 1.0 but no value in between. 14311 * 14312 * Subclasses should override this method to provide a smoother fade transition 14313 * when scrolling occurs. 14314 * 14315 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14316 */ 14317 protected float getLeftFadingEdgeStrength() { 14318 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14319 } 14320 14321 /** 14322 * Returns the strength, or intensity, of the right faded edge. The strength is 14323 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14324 * returns 0.0 or 1.0 but no value in between. 14325 * 14326 * Subclasses should override this method to provide a smoother fade transition 14327 * when scrolling occurs. 14328 * 14329 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14330 */ 14331 protected float getRightFadingEdgeStrength() { 14332 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14333 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14334 } 14335 14336 /** 14337 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14338 * scrollbar is not drawn by default.</p> 14339 * 14340 * @return true if the horizontal scrollbar should be painted, false 14341 * otherwise 14342 * 14343 * @see #setHorizontalScrollBarEnabled(boolean) 14344 */ 14345 public boolean isHorizontalScrollBarEnabled() { 14346 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14347 } 14348 14349 /** 14350 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14351 * scrollbar is not drawn by default.</p> 14352 * 14353 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14354 * be painted 14355 * 14356 * @see #isHorizontalScrollBarEnabled() 14357 */ 14358 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14359 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14360 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14361 computeOpaqueFlags(); 14362 resolvePadding(); 14363 } 14364 } 14365 14366 /** 14367 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14368 * scrollbar is not drawn by default.</p> 14369 * 14370 * @return true if the vertical scrollbar should be painted, false 14371 * otherwise 14372 * 14373 * @see #setVerticalScrollBarEnabled(boolean) 14374 */ 14375 public boolean isVerticalScrollBarEnabled() { 14376 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14377 } 14378 14379 /** 14380 * <p>Define whether the vertical scrollbar should be drawn or not. The 14381 * scrollbar is not drawn by default.</p> 14382 * 14383 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14384 * be painted 14385 * 14386 * @see #isVerticalScrollBarEnabled() 14387 */ 14388 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14389 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14390 mViewFlags ^= SCROLLBARS_VERTICAL; 14391 computeOpaqueFlags(); 14392 resolvePadding(); 14393 } 14394 } 14395 14396 /** 14397 * @hide 14398 */ 14399 protected void recomputePadding() { 14400 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14401 } 14402 14403 /** 14404 * Define whether scrollbars will fade when the view is not scrolling. 14405 * 14406 * @param fadeScrollbars whether to enable fading 14407 * 14408 * @attr ref android.R.styleable#View_fadeScrollbars 14409 */ 14410 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14411 initScrollCache(); 14412 final ScrollabilityCache scrollabilityCache = mScrollCache; 14413 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14414 if (fadeScrollbars) { 14415 scrollabilityCache.state = ScrollabilityCache.OFF; 14416 } else { 14417 scrollabilityCache.state = ScrollabilityCache.ON; 14418 } 14419 } 14420 14421 /** 14422 * 14423 * Returns true if scrollbars will fade when this view is not scrolling 14424 * 14425 * @return true if scrollbar fading is enabled 14426 * 14427 * @attr ref android.R.styleable#View_fadeScrollbars 14428 */ 14429 public boolean isScrollbarFadingEnabled() { 14430 return mScrollCache != null && mScrollCache.fadeScrollBars; 14431 } 14432 14433 /** 14434 * 14435 * Returns the delay before scrollbars fade. 14436 * 14437 * @return the delay before scrollbars fade 14438 * 14439 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14440 */ 14441 public int getScrollBarDefaultDelayBeforeFade() { 14442 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14443 mScrollCache.scrollBarDefaultDelayBeforeFade; 14444 } 14445 14446 /** 14447 * Define the delay before scrollbars fade. 14448 * 14449 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14450 * 14451 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14452 */ 14453 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14454 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14455 } 14456 14457 /** 14458 * 14459 * Returns the scrollbar fade duration. 14460 * 14461 * @return the scrollbar fade duration, in milliseconds 14462 * 14463 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14464 */ 14465 public int getScrollBarFadeDuration() { 14466 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14467 mScrollCache.scrollBarFadeDuration; 14468 } 14469 14470 /** 14471 * Define the scrollbar fade duration. 14472 * 14473 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 14474 * 14475 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14476 */ 14477 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14478 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14479 } 14480 14481 /** 14482 * 14483 * Returns the scrollbar size. 14484 * 14485 * @return the scrollbar size 14486 * 14487 * @attr ref android.R.styleable#View_scrollbarSize 14488 */ 14489 public int getScrollBarSize() { 14490 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14491 mScrollCache.scrollBarSize; 14492 } 14493 14494 /** 14495 * Define the scrollbar size. 14496 * 14497 * @param scrollBarSize - the scrollbar size 14498 * 14499 * @attr ref android.R.styleable#View_scrollbarSize 14500 */ 14501 public void setScrollBarSize(int scrollBarSize) { 14502 getScrollCache().scrollBarSize = scrollBarSize; 14503 } 14504 14505 /** 14506 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14507 * inset. When inset, they add to the padding of the view. And the scrollbars 14508 * can be drawn inside the padding area or on the edge of the view. For example, 14509 * if a view has a background drawable and you want to draw the scrollbars 14510 * inside the padding specified by the drawable, you can use 14511 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14512 * appear at the edge of the view, ignoring the padding, then you can use 14513 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14514 * @param style the style of the scrollbars. Should be one of 14515 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14516 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14517 * @see #SCROLLBARS_INSIDE_OVERLAY 14518 * @see #SCROLLBARS_INSIDE_INSET 14519 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14520 * @see #SCROLLBARS_OUTSIDE_INSET 14521 * 14522 * @attr ref android.R.styleable#View_scrollbarStyle 14523 */ 14524 public void setScrollBarStyle(@ScrollBarStyle int style) { 14525 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14526 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14527 computeOpaqueFlags(); 14528 resolvePadding(); 14529 } 14530 } 14531 14532 /** 14533 * <p>Returns the current scrollbar style.</p> 14534 * @return the current scrollbar style 14535 * @see #SCROLLBARS_INSIDE_OVERLAY 14536 * @see #SCROLLBARS_INSIDE_INSET 14537 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14538 * @see #SCROLLBARS_OUTSIDE_INSET 14539 * 14540 * @attr ref android.R.styleable#View_scrollbarStyle 14541 */ 14542 @ViewDebug.ExportedProperty(mapping = { 14543 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14544 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14545 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14546 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14547 }) 14548 @ScrollBarStyle 14549 public int getScrollBarStyle() { 14550 return mViewFlags & SCROLLBARS_STYLE_MASK; 14551 } 14552 14553 /** 14554 * <p>Compute the horizontal range that the horizontal scrollbar 14555 * represents.</p> 14556 * 14557 * <p>The range is expressed in arbitrary units that must be the same as the 14558 * units used by {@link #computeHorizontalScrollExtent()} and 14559 * {@link #computeHorizontalScrollOffset()}.</p> 14560 * 14561 * <p>The default range is the drawing width of this view.</p> 14562 * 14563 * @return the total horizontal range represented by the horizontal 14564 * scrollbar 14565 * 14566 * @see #computeHorizontalScrollExtent() 14567 * @see #computeHorizontalScrollOffset() 14568 * @see android.widget.ScrollBarDrawable 14569 */ 14570 protected int computeHorizontalScrollRange() { 14571 return getWidth(); 14572 } 14573 14574 /** 14575 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14576 * within the horizontal range. This value is used to compute the position 14577 * of the thumb within the scrollbar's track.</p> 14578 * 14579 * <p>The range is expressed in arbitrary units that must be the same as the 14580 * units used by {@link #computeHorizontalScrollRange()} and 14581 * {@link #computeHorizontalScrollExtent()}.</p> 14582 * 14583 * <p>The default offset is the scroll offset of this view.</p> 14584 * 14585 * @return the horizontal offset of the scrollbar's thumb 14586 * 14587 * @see #computeHorizontalScrollRange() 14588 * @see #computeHorizontalScrollExtent() 14589 * @see android.widget.ScrollBarDrawable 14590 */ 14591 protected int computeHorizontalScrollOffset() { 14592 return mScrollX; 14593 } 14594 14595 /** 14596 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14597 * within the horizontal range. This value is used to compute the length 14598 * of the thumb within the scrollbar's track.</p> 14599 * 14600 * <p>The range is expressed in arbitrary units that must be the same as the 14601 * units used by {@link #computeHorizontalScrollRange()} and 14602 * {@link #computeHorizontalScrollOffset()}.</p> 14603 * 14604 * <p>The default extent is the drawing width of this view.</p> 14605 * 14606 * @return the horizontal extent of the scrollbar's thumb 14607 * 14608 * @see #computeHorizontalScrollRange() 14609 * @see #computeHorizontalScrollOffset() 14610 * @see android.widget.ScrollBarDrawable 14611 */ 14612 protected int computeHorizontalScrollExtent() { 14613 return getWidth(); 14614 } 14615 14616 /** 14617 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14618 * 14619 * <p>The range is expressed in arbitrary units that must be the same as the 14620 * units used by {@link #computeVerticalScrollExtent()} and 14621 * {@link #computeVerticalScrollOffset()}.</p> 14622 * 14623 * @return the total vertical range represented by the vertical scrollbar 14624 * 14625 * <p>The default range is the drawing height of this view.</p> 14626 * 14627 * @see #computeVerticalScrollExtent() 14628 * @see #computeVerticalScrollOffset() 14629 * @see android.widget.ScrollBarDrawable 14630 */ 14631 protected int computeVerticalScrollRange() { 14632 return getHeight(); 14633 } 14634 14635 /** 14636 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14637 * within the horizontal range. This value is used to compute the position 14638 * of the thumb within the scrollbar's track.</p> 14639 * 14640 * <p>The range is expressed in arbitrary units that must be the same as the 14641 * units used by {@link #computeVerticalScrollRange()} and 14642 * {@link #computeVerticalScrollExtent()}.</p> 14643 * 14644 * <p>The default offset is the scroll offset of this view.</p> 14645 * 14646 * @return the vertical offset of the scrollbar's thumb 14647 * 14648 * @see #computeVerticalScrollRange() 14649 * @see #computeVerticalScrollExtent() 14650 * @see android.widget.ScrollBarDrawable 14651 */ 14652 protected int computeVerticalScrollOffset() { 14653 return mScrollY; 14654 } 14655 14656 /** 14657 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14658 * within the vertical range. This value is used to compute the length 14659 * of the thumb within the scrollbar's track.</p> 14660 * 14661 * <p>The range is expressed in arbitrary units that must be the same as the 14662 * units used by {@link #computeVerticalScrollRange()} and 14663 * {@link #computeVerticalScrollOffset()}.</p> 14664 * 14665 * <p>The default extent is the drawing height of this view.</p> 14666 * 14667 * @return the vertical extent of the scrollbar's thumb 14668 * 14669 * @see #computeVerticalScrollRange() 14670 * @see #computeVerticalScrollOffset() 14671 * @see android.widget.ScrollBarDrawable 14672 */ 14673 protected int computeVerticalScrollExtent() { 14674 return getHeight(); 14675 } 14676 14677 /** 14678 * Check if this view can be scrolled horizontally in a certain direction. 14679 * 14680 * @param direction Negative to check scrolling left, positive to check scrolling right. 14681 * @return true if this view can be scrolled in the specified direction, false otherwise. 14682 */ 14683 public boolean canScrollHorizontally(int direction) { 14684 final int offset = computeHorizontalScrollOffset(); 14685 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14686 if (range == 0) return false; 14687 if (direction < 0) { 14688 return offset > 0; 14689 } else { 14690 return offset < range - 1; 14691 } 14692 } 14693 14694 /** 14695 * Check if this view can be scrolled vertically in a certain direction. 14696 * 14697 * @param direction Negative to check scrolling up, positive to check scrolling down. 14698 * @return true if this view can be scrolled in the specified direction, false otherwise. 14699 */ 14700 public boolean canScrollVertically(int direction) { 14701 final int offset = computeVerticalScrollOffset(); 14702 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14703 if (range == 0) return false; 14704 if (direction < 0) { 14705 return offset > 0; 14706 } else { 14707 return offset < range - 1; 14708 } 14709 } 14710 14711 void getScrollIndicatorBounds(@NonNull Rect out) { 14712 out.left = mScrollX; 14713 out.right = mScrollX + mRight - mLeft; 14714 out.top = mScrollY; 14715 out.bottom = mScrollY + mBottom - mTop; 14716 } 14717 14718 private void onDrawScrollIndicators(Canvas c) { 14719 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14720 // No scroll indicators enabled. 14721 return; 14722 } 14723 14724 final Drawable dr = mScrollIndicatorDrawable; 14725 if (dr == null) { 14726 // Scroll indicators aren't supported here. 14727 return; 14728 } 14729 14730 final int h = dr.getIntrinsicHeight(); 14731 final int w = dr.getIntrinsicWidth(); 14732 final Rect rect = mAttachInfo.mTmpInvalRect; 14733 getScrollIndicatorBounds(rect); 14734 14735 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14736 final boolean canScrollUp = canScrollVertically(-1); 14737 if (canScrollUp) { 14738 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14739 dr.draw(c); 14740 } 14741 } 14742 14743 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14744 final boolean canScrollDown = canScrollVertically(1); 14745 if (canScrollDown) { 14746 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14747 dr.draw(c); 14748 } 14749 } 14750 14751 final int leftRtl; 14752 final int rightRtl; 14753 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14754 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14755 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14756 } else { 14757 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14758 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14759 } 14760 14761 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14762 if ((mPrivateFlags3 & leftMask) != 0) { 14763 final boolean canScrollLeft = canScrollHorizontally(-1); 14764 if (canScrollLeft) { 14765 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14766 dr.draw(c); 14767 } 14768 } 14769 14770 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14771 if ((mPrivateFlags3 & rightMask) != 0) { 14772 final boolean canScrollRight = canScrollHorizontally(1); 14773 if (canScrollRight) { 14774 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14775 dr.draw(c); 14776 } 14777 } 14778 } 14779 14780 private void getHorizontalScrollBarBounds(Rect bounds) { 14781 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14782 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14783 && !isVerticalScrollBarHidden(); 14784 final int size = getHorizontalScrollbarHeight(); 14785 final int verticalScrollBarGap = drawVerticalScrollBar ? 14786 getVerticalScrollbarWidth() : 0; 14787 final int width = mRight - mLeft; 14788 final int height = mBottom - mTop; 14789 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14790 bounds.left = mScrollX + (mPaddingLeft & inside); 14791 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14792 bounds.bottom = bounds.top + size; 14793 } 14794 14795 private void getVerticalScrollBarBounds(Rect bounds) { 14796 if (mRoundScrollbarRenderer == null) { 14797 getStraightVerticalScrollBarBounds(bounds); 14798 } else { 14799 getRoundVerticalScrollBarBounds(bounds); 14800 } 14801 } 14802 14803 private void getRoundVerticalScrollBarBounds(Rect bounds) { 14804 final int width = mRight - mLeft; 14805 final int height = mBottom - mTop; 14806 // Do not take padding into account as we always want the scrollbars 14807 // to hug the screen for round wearable devices. 14808 bounds.left = mScrollX; 14809 bounds.top = mScrollY; 14810 bounds.right = bounds.left + width; 14811 bounds.bottom = mScrollY + height; 14812 } 14813 14814 private void getStraightVerticalScrollBarBounds(Rect bounds) { 14815 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14816 final int size = getVerticalScrollbarWidth(); 14817 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14818 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14819 verticalScrollbarPosition = isLayoutRtl() ? 14820 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14821 } 14822 final int width = mRight - mLeft; 14823 final int height = mBottom - mTop; 14824 switch (verticalScrollbarPosition) { 14825 default: 14826 case SCROLLBAR_POSITION_RIGHT: 14827 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14828 break; 14829 case SCROLLBAR_POSITION_LEFT: 14830 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14831 break; 14832 } 14833 bounds.top = mScrollY + (mPaddingTop & inside); 14834 bounds.right = bounds.left + size; 14835 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14836 } 14837 14838 /** 14839 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14840 * scrollbars are painted only if they have been awakened first.</p> 14841 * 14842 * @param canvas the canvas on which to draw the scrollbars 14843 * 14844 * @see #awakenScrollBars(int) 14845 */ 14846 protected final void onDrawScrollBars(Canvas canvas) { 14847 // scrollbars are drawn only when the animation is running 14848 final ScrollabilityCache cache = mScrollCache; 14849 14850 if (cache != null) { 14851 14852 int state = cache.state; 14853 14854 if (state == ScrollabilityCache.OFF) { 14855 return; 14856 } 14857 14858 boolean invalidate = false; 14859 14860 if (state == ScrollabilityCache.FADING) { 14861 // We're fading -- get our fade interpolation 14862 if (cache.interpolatorValues == null) { 14863 cache.interpolatorValues = new float[1]; 14864 } 14865 14866 float[] values = cache.interpolatorValues; 14867 14868 // Stops the animation if we're done 14869 if (cache.scrollBarInterpolator.timeToValues(values) == 14870 Interpolator.Result.FREEZE_END) { 14871 cache.state = ScrollabilityCache.OFF; 14872 } else { 14873 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14874 } 14875 14876 // This will make the scroll bars inval themselves after 14877 // drawing. We only want this when we're fading so that 14878 // we prevent excessive redraws 14879 invalidate = true; 14880 } else { 14881 // We're just on -- but we may have been fading before so 14882 // reset alpha 14883 cache.scrollBar.mutate().setAlpha(255); 14884 } 14885 14886 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14887 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14888 && !isVerticalScrollBarHidden(); 14889 14890 // Fork out the scroll bar drawing for round wearable devices. 14891 if (mRoundScrollbarRenderer != null) { 14892 if (drawVerticalScrollBar) { 14893 final Rect bounds = cache.mScrollBarBounds; 14894 getVerticalScrollBarBounds(bounds); 14895 mRoundScrollbarRenderer.drawRoundScrollbars( 14896 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 14897 if (invalidate) { 14898 invalidate(); 14899 } 14900 } 14901 // Do not draw horizontal scroll bars for round wearable devices. 14902 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14903 final ScrollBarDrawable scrollBar = cache.scrollBar; 14904 14905 if (drawHorizontalScrollBar) { 14906 scrollBar.setParameters(computeHorizontalScrollRange(), 14907 computeHorizontalScrollOffset(), 14908 computeHorizontalScrollExtent(), false); 14909 final Rect bounds = cache.mScrollBarBounds; 14910 getHorizontalScrollBarBounds(bounds); 14911 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14912 bounds.right, bounds.bottom); 14913 if (invalidate) { 14914 invalidate(bounds); 14915 } 14916 } 14917 14918 if (drawVerticalScrollBar) { 14919 scrollBar.setParameters(computeVerticalScrollRange(), 14920 computeVerticalScrollOffset(), 14921 computeVerticalScrollExtent(), true); 14922 final Rect bounds = cache.mScrollBarBounds; 14923 getVerticalScrollBarBounds(bounds); 14924 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14925 bounds.right, bounds.bottom); 14926 if (invalidate) { 14927 invalidate(bounds); 14928 } 14929 } 14930 } 14931 } 14932 } 14933 14934 /** 14935 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14936 * FastScroller is visible. 14937 * @return whether to temporarily hide the vertical scrollbar 14938 * @hide 14939 */ 14940 protected boolean isVerticalScrollBarHidden() { 14941 return false; 14942 } 14943 14944 /** 14945 * <p>Draw the horizontal scrollbar if 14946 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14947 * 14948 * @param canvas the canvas on which to draw the scrollbar 14949 * @param scrollBar the scrollbar's drawable 14950 * 14951 * @see #isHorizontalScrollBarEnabled() 14952 * @see #computeHorizontalScrollRange() 14953 * @see #computeHorizontalScrollExtent() 14954 * @see #computeHorizontalScrollOffset() 14955 * @see android.widget.ScrollBarDrawable 14956 * @hide 14957 */ 14958 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14959 int l, int t, int r, int b) { 14960 scrollBar.setBounds(l, t, r, b); 14961 scrollBar.draw(canvas); 14962 } 14963 14964 /** 14965 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14966 * returns true.</p> 14967 * 14968 * @param canvas the canvas on which to draw the scrollbar 14969 * @param scrollBar the scrollbar's drawable 14970 * 14971 * @see #isVerticalScrollBarEnabled() 14972 * @see #computeVerticalScrollRange() 14973 * @see #computeVerticalScrollExtent() 14974 * @see #computeVerticalScrollOffset() 14975 * @see android.widget.ScrollBarDrawable 14976 * @hide 14977 */ 14978 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14979 int l, int t, int r, int b) { 14980 scrollBar.setBounds(l, t, r, b); 14981 scrollBar.draw(canvas); 14982 } 14983 14984 /** 14985 * Implement this to do your drawing. 14986 * 14987 * @param canvas the canvas on which the background will be drawn 14988 */ 14989 protected void onDraw(Canvas canvas) { 14990 } 14991 14992 /* 14993 * Caller is responsible for calling requestLayout if necessary. 14994 * (This allows addViewInLayout to not request a new layout.) 14995 */ 14996 void assignParent(ViewParent parent) { 14997 if (mParent == null) { 14998 mParent = parent; 14999 } else if (parent == null) { 15000 mParent = null; 15001 } else { 15002 throw new RuntimeException("view " + this + " being added, but" 15003 + " it already has a parent"); 15004 } 15005 } 15006 15007 /** 15008 * This is called when the view is attached to a window. At this point it 15009 * has a Surface and will start drawing. Note that this function is 15010 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 15011 * however it may be called any time before the first onDraw -- including 15012 * before or after {@link #onMeasure(int, int)}. 15013 * 15014 * @see #onDetachedFromWindow() 15015 */ 15016 @CallSuper 15017 protected void onAttachedToWindow() { 15018 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 15019 mParent.requestTransparentRegion(this); 15020 } 15021 15022 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15023 15024 jumpDrawablesToCurrentState(); 15025 15026 resetSubtreeAccessibilityStateChanged(); 15027 15028 // rebuild, since Outline not maintained while View is detached 15029 rebuildOutline(); 15030 15031 if (isFocused()) { 15032 InputMethodManager imm = InputMethodManager.peekInstance(); 15033 if (imm != null) { 15034 imm.focusIn(this); 15035 } 15036 } 15037 } 15038 15039 /** 15040 * Resolve all RTL related properties. 15041 * 15042 * @return true if resolution of RTL properties has been done 15043 * 15044 * @hide 15045 */ 15046 public boolean resolveRtlPropertiesIfNeeded() { 15047 if (!needRtlPropertiesResolution()) return false; 15048 15049 // Order is important here: LayoutDirection MUST be resolved first 15050 if (!isLayoutDirectionResolved()) { 15051 resolveLayoutDirection(); 15052 resolveLayoutParams(); 15053 } 15054 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 15055 if (!isTextDirectionResolved()) { 15056 resolveTextDirection(); 15057 } 15058 if (!isTextAlignmentResolved()) { 15059 resolveTextAlignment(); 15060 } 15061 // Should resolve Drawables before Padding because we need the layout direction of the 15062 // Drawable to correctly resolve Padding. 15063 if (!areDrawablesResolved()) { 15064 resolveDrawables(); 15065 } 15066 if (!isPaddingResolved()) { 15067 resolvePadding(); 15068 } 15069 onRtlPropertiesChanged(getLayoutDirection()); 15070 return true; 15071 } 15072 15073 /** 15074 * Reset resolution of all RTL related properties. 15075 * 15076 * @hide 15077 */ 15078 public void resetRtlProperties() { 15079 resetResolvedLayoutDirection(); 15080 resetResolvedTextDirection(); 15081 resetResolvedTextAlignment(); 15082 resetResolvedPadding(); 15083 resetResolvedDrawables(); 15084 } 15085 15086 /** 15087 * @see #onScreenStateChanged(int) 15088 */ 15089 void dispatchScreenStateChanged(int screenState) { 15090 onScreenStateChanged(screenState); 15091 } 15092 15093 /** 15094 * This method is called whenever the state of the screen this view is 15095 * attached to changes. A state change will usually occurs when the screen 15096 * turns on or off (whether it happens automatically or the user does it 15097 * manually.) 15098 * 15099 * @param screenState The new state of the screen. Can be either 15100 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 15101 */ 15102 public void onScreenStateChanged(int screenState) { 15103 } 15104 15105 /** 15106 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 15107 */ 15108 private boolean hasRtlSupport() { 15109 return mContext.getApplicationInfo().hasRtlSupport(); 15110 } 15111 15112 /** 15113 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 15114 * RTL not supported) 15115 */ 15116 private boolean isRtlCompatibilityMode() { 15117 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 15118 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 15119 } 15120 15121 /** 15122 * @return true if RTL properties need resolution. 15123 * 15124 */ 15125 private boolean needRtlPropertiesResolution() { 15126 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15127 } 15128 15129 /** 15130 * Called when any RTL property (layout direction or text direction or text alignment) has 15131 * been changed. 15132 * 15133 * Subclasses need to override this method to take care of cached information that depends on the 15134 * resolved layout direction, or to inform child views that inherit their layout direction. 15135 * 15136 * The default implementation does nothing. 15137 * 15138 * @param layoutDirection the direction of the layout 15139 * 15140 * @see #LAYOUT_DIRECTION_LTR 15141 * @see #LAYOUT_DIRECTION_RTL 15142 */ 15143 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15144 } 15145 15146 /** 15147 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15148 * that the parent directionality can and will be resolved before its children. 15149 * 15150 * @return true if resolution has been done, false otherwise. 15151 * 15152 * @hide 15153 */ 15154 public boolean resolveLayoutDirection() { 15155 // Clear any previous layout direction resolution 15156 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15157 15158 if (hasRtlSupport()) { 15159 // Set resolved depending on layout direction 15160 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15161 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15162 case LAYOUT_DIRECTION_INHERIT: 15163 // We cannot resolve yet. LTR is by default and let the resolution happen again 15164 // later to get the correct resolved value 15165 if (!canResolveLayoutDirection()) return false; 15166 15167 // Parent has not yet resolved, LTR is still the default 15168 try { 15169 if (!mParent.isLayoutDirectionResolved()) return false; 15170 15171 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15172 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15173 } 15174 } catch (AbstractMethodError e) { 15175 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15176 " does not fully implement ViewParent", e); 15177 } 15178 break; 15179 case LAYOUT_DIRECTION_RTL: 15180 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15181 break; 15182 case LAYOUT_DIRECTION_LOCALE: 15183 if((LAYOUT_DIRECTION_RTL == 15184 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15185 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15186 } 15187 break; 15188 default: 15189 // Nothing to do, LTR by default 15190 } 15191 } 15192 15193 // Set to resolved 15194 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15195 return true; 15196 } 15197 15198 /** 15199 * Check if layout direction resolution can be done. 15200 * 15201 * @return true if layout direction resolution can be done otherwise return false. 15202 */ 15203 public boolean canResolveLayoutDirection() { 15204 switch (getRawLayoutDirection()) { 15205 case LAYOUT_DIRECTION_INHERIT: 15206 if (mParent != null) { 15207 try { 15208 return mParent.canResolveLayoutDirection(); 15209 } catch (AbstractMethodError e) { 15210 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15211 " does not fully implement ViewParent", e); 15212 } 15213 } 15214 return false; 15215 15216 default: 15217 return true; 15218 } 15219 } 15220 15221 /** 15222 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15223 * {@link #onMeasure(int, int)}. 15224 * 15225 * @hide 15226 */ 15227 public void resetResolvedLayoutDirection() { 15228 // Reset the current resolved bits 15229 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15230 } 15231 15232 /** 15233 * @return true if the layout direction is inherited. 15234 * 15235 * @hide 15236 */ 15237 public boolean isLayoutDirectionInherited() { 15238 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15239 } 15240 15241 /** 15242 * @return true if layout direction has been resolved. 15243 */ 15244 public boolean isLayoutDirectionResolved() { 15245 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15246 } 15247 15248 /** 15249 * Return if padding has been resolved 15250 * 15251 * @hide 15252 */ 15253 boolean isPaddingResolved() { 15254 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15255 } 15256 15257 /** 15258 * Resolves padding depending on layout direction, if applicable, and 15259 * recomputes internal padding values to adjust for scroll bars. 15260 * 15261 * @hide 15262 */ 15263 public void resolvePadding() { 15264 final int resolvedLayoutDirection = getLayoutDirection(); 15265 15266 if (!isRtlCompatibilityMode()) { 15267 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15268 // If start / end padding are defined, they will be resolved (hence overriding) to 15269 // left / right or right / left depending on the resolved layout direction. 15270 // If start / end padding are not defined, use the left / right ones. 15271 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15272 Rect padding = sThreadLocal.get(); 15273 if (padding == null) { 15274 padding = new Rect(); 15275 sThreadLocal.set(padding); 15276 } 15277 mBackground.getPadding(padding); 15278 if (!mLeftPaddingDefined) { 15279 mUserPaddingLeftInitial = padding.left; 15280 } 15281 if (!mRightPaddingDefined) { 15282 mUserPaddingRightInitial = padding.right; 15283 } 15284 } 15285 switch (resolvedLayoutDirection) { 15286 case LAYOUT_DIRECTION_RTL: 15287 if (mUserPaddingStart != UNDEFINED_PADDING) { 15288 mUserPaddingRight = mUserPaddingStart; 15289 } else { 15290 mUserPaddingRight = mUserPaddingRightInitial; 15291 } 15292 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15293 mUserPaddingLeft = mUserPaddingEnd; 15294 } else { 15295 mUserPaddingLeft = mUserPaddingLeftInitial; 15296 } 15297 break; 15298 case LAYOUT_DIRECTION_LTR: 15299 default: 15300 if (mUserPaddingStart != UNDEFINED_PADDING) { 15301 mUserPaddingLeft = mUserPaddingStart; 15302 } else { 15303 mUserPaddingLeft = mUserPaddingLeftInitial; 15304 } 15305 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15306 mUserPaddingRight = mUserPaddingEnd; 15307 } else { 15308 mUserPaddingRight = mUserPaddingRightInitial; 15309 } 15310 } 15311 15312 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15313 } 15314 15315 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15316 onRtlPropertiesChanged(resolvedLayoutDirection); 15317 15318 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15319 } 15320 15321 /** 15322 * Reset the resolved layout direction. 15323 * 15324 * @hide 15325 */ 15326 public void resetResolvedPadding() { 15327 resetResolvedPaddingInternal(); 15328 } 15329 15330 /** 15331 * Used when we only want to reset *this* view's padding and not trigger overrides 15332 * in ViewGroup that reset children too. 15333 */ 15334 void resetResolvedPaddingInternal() { 15335 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15336 } 15337 15338 /** 15339 * This is called when the view is detached from a window. At this point it 15340 * no longer has a surface for drawing. 15341 * 15342 * @see #onAttachedToWindow() 15343 */ 15344 @CallSuper 15345 protected void onDetachedFromWindow() { 15346 } 15347 15348 /** 15349 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15350 * after onDetachedFromWindow(). 15351 * 15352 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15353 * The super method should be called at the end of the overridden method to ensure 15354 * subclasses are destroyed first 15355 * 15356 * @hide 15357 */ 15358 @CallSuper 15359 protected void onDetachedFromWindowInternal() { 15360 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15361 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15362 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15363 15364 removeUnsetPressCallback(); 15365 removeLongPressCallback(); 15366 removePerformClickCallback(); 15367 removeSendViewScrolledAccessibilityEventCallback(); 15368 stopNestedScroll(); 15369 15370 // Anything that started animating right before detach should already 15371 // be in its final state when re-attached. 15372 jumpDrawablesToCurrentState(); 15373 15374 destroyDrawingCache(); 15375 15376 cleanupDraw(); 15377 mCurrentAnimation = null; 15378 } 15379 15380 private void cleanupDraw() { 15381 resetDisplayList(); 15382 if (mAttachInfo != null) { 15383 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15384 } 15385 } 15386 15387 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15388 } 15389 15390 /** 15391 * @return The number of times this view has been attached to a window 15392 */ 15393 protected int getWindowAttachCount() { 15394 return mWindowAttachCount; 15395 } 15396 15397 /** 15398 * Retrieve a unique token identifying the window this view is attached to. 15399 * @return Return the window's token for use in 15400 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15401 */ 15402 public IBinder getWindowToken() { 15403 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15404 } 15405 15406 /** 15407 * Retrieve the {@link WindowId} for the window this view is 15408 * currently attached to. 15409 */ 15410 public WindowId getWindowId() { 15411 if (mAttachInfo == null) { 15412 return null; 15413 } 15414 if (mAttachInfo.mWindowId == null) { 15415 try { 15416 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15417 mAttachInfo.mWindowToken); 15418 mAttachInfo.mWindowId = new WindowId( 15419 mAttachInfo.mIWindowId); 15420 } catch (RemoteException e) { 15421 } 15422 } 15423 return mAttachInfo.mWindowId; 15424 } 15425 15426 /** 15427 * Retrieve a unique token identifying the top-level "real" window of 15428 * the window that this view is attached to. That is, this is like 15429 * {@link #getWindowToken}, except if the window this view in is a panel 15430 * window (attached to another containing window), then the token of 15431 * the containing window is returned instead. 15432 * 15433 * @return Returns the associated window token, either 15434 * {@link #getWindowToken()} or the containing window's token. 15435 */ 15436 public IBinder getApplicationWindowToken() { 15437 AttachInfo ai = mAttachInfo; 15438 if (ai != null) { 15439 IBinder appWindowToken = ai.mPanelParentWindowToken; 15440 if (appWindowToken == null) { 15441 appWindowToken = ai.mWindowToken; 15442 } 15443 return appWindowToken; 15444 } 15445 return null; 15446 } 15447 15448 /** 15449 * Gets the logical display to which the view's window has been attached. 15450 * 15451 * @return The logical display, or null if the view is not currently attached to a window. 15452 */ 15453 public Display getDisplay() { 15454 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15455 } 15456 15457 /** 15458 * Retrieve private session object this view hierarchy is using to 15459 * communicate with the window manager. 15460 * @return the session object to communicate with the window manager 15461 */ 15462 /*package*/ IWindowSession getWindowSession() { 15463 return mAttachInfo != null ? mAttachInfo.mSession : null; 15464 } 15465 15466 /** 15467 * Return the visibility value of the least visible component passed. 15468 */ 15469 int combineVisibility(int vis1, int vis2) { 15470 // This works because VISIBLE < INVISIBLE < GONE. 15471 return Math.max(vis1, vis2); 15472 } 15473 15474 /** 15475 * @param info the {@link android.view.View.AttachInfo} to associated with 15476 * this view 15477 */ 15478 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15479 mAttachInfo = info; 15480 if (mOverlay != null) { 15481 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15482 } 15483 mWindowAttachCount++; 15484 // We will need to evaluate the drawable state at least once. 15485 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15486 if (mFloatingTreeObserver != null) { 15487 info.mTreeObserver.merge(mFloatingTreeObserver); 15488 mFloatingTreeObserver = null; 15489 } 15490 15491 registerPendingFrameMetricsObservers(); 15492 15493 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15494 mAttachInfo.mScrollContainers.add(this); 15495 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15496 } 15497 // Transfer all pending runnables. 15498 if (mRunQueue != null) { 15499 mRunQueue.executeActions(info.mHandler); 15500 mRunQueue = null; 15501 } 15502 performCollectViewAttributes(mAttachInfo, visibility); 15503 onAttachedToWindow(); 15504 15505 ListenerInfo li = mListenerInfo; 15506 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15507 li != null ? li.mOnAttachStateChangeListeners : null; 15508 if (listeners != null && listeners.size() > 0) { 15509 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15510 // perform the dispatching. The iterator is a safe guard against listeners that 15511 // could mutate the list by calling the various add/remove methods. This prevents 15512 // the array from being modified while we iterate it. 15513 for (OnAttachStateChangeListener listener : listeners) { 15514 listener.onViewAttachedToWindow(this); 15515 } 15516 } 15517 15518 int vis = info.mWindowVisibility; 15519 if (vis != GONE) { 15520 onWindowVisibilityChanged(vis); 15521 if (isShown()) { 15522 // Calling onVisibilityAggregated directly here since the subtree will also 15523 // receive dispatchAttachedToWindow and this same call 15524 onVisibilityAggregated(vis == VISIBLE); 15525 } 15526 } 15527 15528 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15529 // As all views in the subtree will already receive dispatchAttachedToWindow 15530 // traversing the subtree again here is not desired. 15531 onVisibilityChanged(this, visibility); 15532 15533 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15534 // If nobody has evaluated the drawable state yet, then do it now. 15535 refreshDrawableState(); 15536 } 15537 needGlobalAttributesUpdate(false); 15538 } 15539 15540 void dispatchDetachedFromWindow() { 15541 AttachInfo info = mAttachInfo; 15542 if (info != null) { 15543 int vis = info.mWindowVisibility; 15544 if (vis != GONE) { 15545 onWindowVisibilityChanged(GONE); 15546 if (isShown()) { 15547 // Invoking onVisibilityAggregated directly here since the subtree 15548 // will also receive detached from window 15549 onVisibilityAggregated(false); 15550 } 15551 } 15552 } 15553 15554 onDetachedFromWindow(); 15555 onDetachedFromWindowInternal(); 15556 15557 InputMethodManager imm = InputMethodManager.peekInstance(); 15558 if (imm != null) { 15559 imm.onViewDetachedFromWindow(this); 15560 } 15561 15562 ListenerInfo li = mListenerInfo; 15563 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15564 li != null ? li.mOnAttachStateChangeListeners : null; 15565 if (listeners != null && listeners.size() > 0) { 15566 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15567 // perform the dispatching. The iterator is a safe guard against listeners that 15568 // could mutate the list by calling the various add/remove methods. This prevents 15569 // the array from being modified while we iterate it. 15570 for (OnAttachStateChangeListener listener : listeners) { 15571 listener.onViewDetachedFromWindow(this); 15572 } 15573 } 15574 15575 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15576 mAttachInfo.mScrollContainers.remove(this); 15577 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15578 } 15579 15580 mAttachInfo = null; 15581 if (mOverlay != null) { 15582 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15583 } 15584 } 15585 15586 /** 15587 * Cancel any deferred high-level input events that were previously posted to the event queue. 15588 * 15589 * <p>Many views post high-level events such as click handlers to the event queue 15590 * to run deferred in order to preserve a desired user experience - clearing visible 15591 * pressed states before executing, etc. This method will abort any events of this nature 15592 * that are currently in flight.</p> 15593 * 15594 * <p>Custom views that generate their own high-level deferred input events should override 15595 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15596 * 15597 * <p>This will also cancel pending input events for any child views.</p> 15598 * 15599 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15600 * This will not impact newer events posted after this call that may occur as a result of 15601 * lower-level input events still waiting in the queue. If you are trying to prevent 15602 * double-submitted events for the duration of some sort of asynchronous transaction 15603 * you should also take other steps to protect against unexpected double inputs e.g. calling 15604 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15605 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15606 */ 15607 public final void cancelPendingInputEvents() { 15608 dispatchCancelPendingInputEvents(); 15609 } 15610 15611 /** 15612 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15613 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15614 */ 15615 void dispatchCancelPendingInputEvents() { 15616 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15617 onCancelPendingInputEvents(); 15618 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15619 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15620 " did not call through to super.onCancelPendingInputEvents()"); 15621 } 15622 } 15623 15624 /** 15625 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15626 * a parent view. 15627 * 15628 * <p>This method is responsible for removing any pending high-level input events that were 15629 * posted to the event queue to run later. Custom view classes that post their own deferred 15630 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15631 * {@link android.os.Handler} should override this method, call 15632 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15633 * </p> 15634 */ 15635 public void onCancelPendingInputEvents() { 15636 removePerformClickCallback(); 15637 cancelLongPress(); 15638 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15639 } 15640 15641 /** 15642 * Store this view hierarchy's frozen state into the given container. 15643 * 15644 * @param container The SparseArray in which to save the view's state. 15645 * 15646 * @see #restoreHierarchyState(android.util.SparseArray) 15647 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15648 * @see #onSaveInstanceState() 15649 */ 15650 public void saveHierarchyState(SparseArray<Parcelable> container) { 15651 dispatchSaveInstanceState(container); 15652 } 15653 15654 /** 15655 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15656 * this view and its children. May be overridden to modify how freezing happens to a 15657 * view's children; for example, some views may want to not store state for their children. 15658 * 15659 * @param container The SparseArray in which to save the view's state. 15660 * 15661 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15662 * @see #saveHierarchyState(android.util.SparseArray) 15663 * @see #onSaveInstanceState() 15664 */ 15665 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15666 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15667 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15668 Parcelable state = onSaveInstanceState(); 15669 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15670 throw new IllegalStateException( 15671 "Derived class did not call super.onSaveInstanceState()"); 15672 } 15673 if (state != null) { 15674 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15675 // + ": " + state); 15676 container.put(mID, state); 15677 } 15678 } 15679 } 15680 15681 /** 15682 * Hook allowing a view to generate a representation of its internal state 15683 * that can later be used to create a new instance with that same state. 15684 * This state should only contain information that is not persistent or can 15685 * not be reconstructed later. For example, you will never store your 15686 * current position on screen because that will be computed again when a 15687 * new instance of the view is placed in its view hierarchy. 15688 * <p> 15689 * Some examples of things you may store here: the current cursor position 15690 * in a text view (but usually not the text itself since that is stored in a 15691 * content provider or other persistent storage), the currently selected 15692 * item in a list view. 15693 * 15694 * @return Returns a Parcelable object containing the view's current dynamic 15695 * state, or null if there is nothing interesting to save. The 15696 * default implementation returns null. 15697 * @see #onRestoreInstanceState(android.os.Parcelable) 15698 * @see #saveHierarchyState(android.util.SparseArray) 15699 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15700 * @see #setSaveEnabled(boolean) 15701 */ 15702 @CallSuper 15703 protected Parcelable onSaveInstanceState() { 15704 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15705 if (mStartActivityRequestWho != null) { 15706 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15707 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15708 return state; 15709 } 15710 return BaseSavedState.EMPTY_STATE; 15711 } 15712 15713 /** 15714 * Restore this view hierarchy's frozen state from the given container. 15715 * 15716 * @param container The SparseArray which holds previously frozen states. 15717 * 15718 * @see #saveHierarchyState(android.util.SparseArray) 15719 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15720 * @see #onRestoreInstanceState(android.os.Parcelable) 15721 */ 15722 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15723 dispatchRestoreInstanceState(container); 15724 } 15725 15726 /** 15727 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15728 * state for this view and its children. May be overridden to modify how restoring 15729 * happens to a view's children; for example, some views may want to not store state 15730 * for their children. 15731 * 15732 * @param container The SparseArray which holds previously saved state. 15733 * 15734 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15735 * @see #restoreHierarchyState(android.util.SparseArray) 15736 * @see #onRestoreInstanceState(android.os.Parcelable) 15737 */ 15738 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15739 if (mID != NO_ID) { 15740 Parcelable state = container.get(mID); 15741 if (state != null) { 15742 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15743 // + ": " + state); 15744 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15745 onRestoreInstanceState(state); 15746 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15747 throw new IllegalStateException( 15748 "Derived class did not call super.onRestoreInstanceState()"); 15749 } 15750 } 15751 } 15752 } 15753 15754 /** 15755 * Hook allowing a view to re-apply a representation of its internal state that had previously 15756 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15757 * null state. 15758 * 15759 * @param state The frozen state that had previously been returned by 15760 * {@link #onSaveInstanceState}. 15761 * 15762 * @see #onSaveInstanceState() 15763 * @see #restoreHierarchyState(android.util.SparseArray) 15764 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15765 */ 15766 @CallSuper 15767 protected void onRestoreInstanceState(Parcelable state) { 15768 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15769 if (state != null && !(state instanceof AbsSavedState)) { 15770 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15771 + "received " + state.getClass().toString() + " instead. This usually happens " 15772 + "when two views of different type have the same id in the same hierarchy. " 15773 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15774 + "other views do not use the same id."); 15775 } 15776 if (state != null && state instanceof BaseSavedState) { 15777 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15778 } 15779 } 15780 15781 /** 15782 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15783 * 15784 * @return the drawing start time in milliseconds 15785 */ 15786 public long getDrawingTime() { 15787 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15788 } 15789 15790 /** 15791 * <p>Enables or disables the duplication of the parent's state into this view. When 15792 * duplication is enabled, this view gets its drawable state from its parent rather 15793 * than from its own internal properties.</p> 15794 * 15795 * <p>Note: in the current implementation, setting this property to true after the 15796 * view was added to a ViewGroup might have no effect at all. This property should 15797 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15798 * 15799 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15800 * property is enabled, an exception will be thrown.</p> 15801 * 15802 * <p>Note: if the child view uses and updates additional states which are unknown to the 15803 * parent, these states should not be affected by this method.</p> 15804 * 15805 * @param enabled True to enable duplication of the parent's drawable state, false 15806 * to disable it. 15807 * 15808 * @see #getDrawableState() 15809 * @see #isDuplicateParentStateEnabled() 15810 */ 15811 public void setDuplicateParentStateEnabled(boolean enabled) { 15812 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15813 } 15814 15815 /** 15816 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15817 * 15818 * @return True if this view's drawable state is duplicated from the parent, 15819 * false otherwise 15820 * 15821 * @see #getDrawableState() 15822 * @see #setDuplicateParentStateEnabled(boolean) 15823 */ 15824 public boolean isDuplicateParentStateEnabled() { 15825 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15826 } 15827 15828 /** 15829 * <p>Specifies the type of layer backing this view. The layer can be 15830 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15831 * {@link #LAYER_TYPE_HARDWARE}.</p> 15832 * 15833 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15834 * instance that controls how the layer is composed on screen. The following 15835 * properties of the paint are taken into account when composing the layer:</p> 15836 * <ul> 15837 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15838 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15839 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15840 * </ul> 15841 * 15842 * <p>If this view has an alpha value set to < 1.0 by calling 15843 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15844 * by this view's alpha value.</p> 15845 * 15846 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15847 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15848 * for more information on when and how to use layers.</p> 15849 * 15850 * @param layerType The type of layer to use with this view, must be one of 15851 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15852 * {@link #LAYER_TYPE_HARDWARE} 15853 * @param paint The paint used to compose the layer. This argument is optional 15854 * and can be null. It is ignored when the layer type is 15855 * {@link #LAYER_TYPE_NONE} 15856 * 15857 * @see #getLayerType() 15858 * @see #LAYER_TYPE_NONE 15859 * @see #LAYER_TYPE_SOFTWARE 15860 * @see #LAYER_TYPE_HARDWARE 15861 * @see #setAlpha(float) 15862 * 15863 * @attr ref android.R.styleable#View_layerType 15864 */ 15865 public void setLayerType(int layerType, @Nullable Paint paint) { 15866 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15867 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15868 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15869 } 15870 15871 boolean typeChanged = mRenderNode.setLayerType(layerType); 15872 15873 if (!typeChanged) { 15874 setLayerPaint(paint); 15875 return; 15876 } 15877 15878 if (layerType != LAYER_TYPE_SOFTWARE) { 15879 // Destroy any previous software drawing cache if present 15880 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 15881 // drawing cache created in View#draw when drawing to a SW canvas. 15882 destroyDrawingCache(); 15883 } 15884 15885 mLayerType = layerType; 15886 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15887 mRenderNode.setLayerPaint(mLayerPaint); 15888 15889 // draw() behaves differently if we are on a layer, so we need to 15890 // invalidate() here 15891 invalidateParentCaches(); 15892 invalidate(true); 15893 } 15894 15895 /** 15896 * Updates the {@link Paint} object used with the current layer (used only if the current 15897 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15898 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15899 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15900 * ensure that the view gets redrawn immediately. 15901 * 15902 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15903 * instance that controls how the layer is composed on screen. The following 15904 * properties of the paint are taken into account when composing the layer:</p> 15905 * <ul> 15906 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15907 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15908 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15909 * </ul> 15910 * 15911 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15912 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15913 * 15914 * @param paint The paint used to compose the layer. This argument is optional 15915 * and can be null. It is ignored when the layer type is 15916 * {@link #LAYER_TYPE_NONE} 15917 * 15918 * @see #setLayerType(int, android.graphics.Paint) 15919 */ 15920 public void setLayerPaint(@Nullable Paint paint) { 15921 int layerType = getLayerType(); 15922 if (layerType != LAYER_TYPE_NONE) { 15923 mLayerPaint = paint; 15924 if (layerType == LAYER_TYPE_HARDWARE) { 15925 if (mRenderNode.setLayerPaint(paint)) { 15926 invalidateViewProperty(false, false); 15927 } 15928 } else { 15929 invalidate(); 15930 } 15931 } 15932 } 15933 15934 /** 15935 * Indicates what type of layer is currently associated with this view. By default 15936 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15937 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15938 * for more information on the different types of layers. 15939 * 15940 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15941 * {@link #LAYER_TYPE_HARDWARE} 15942 * 15943 * @see #setLayerType(int, android.graphics.Paint) 15944 * @see #buildLayer() 15945 * @see #LAYER_TYPE_NONE 15946 * @see #LAYER_TYPE_SOFTWARE 15947 * @see #LAYER_TYPE_HARDWARE 15948 */ 15949 public int getLayerType() { 15950 return mLayerType; 15951 } 15952 15953 /** 15954 * Forces this view's layer to be created and this view to be rendered 15955 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15956 * invoking this method will have no effect. 15957 * 15958 * This method can for instance be used to render a view into its layer before 15959 * starting an animation. If this view is complex, rendering into the layer 15960 * before starting the animation will avoid skipping frames. 15961 * 15962 * @throws IllegalStateException If this view is not attached to a window 15963 * 15964 * @see #setLayerType(int, android.graphics.Paint) 15965 */ 15966 public void buildLayer() { 15967 if (mLayerType == LAYER_TYPE_NONE) return; 15968 15969 final AttachInfo attachInfo = mAttachInfo; 15970 if (attachInfo == null) { 15971 throw new IllegalStateException("This view must be attached to a window first"); 15972 } 15973 15974 if (getWidth() == 0 || getHeight() == 0) { 15975 return; 15976 } 15977 15978 switch (mLayerType) { 15979 case LAYER_TYPE_HARDWARE: 15980 updateDisplayListIfDirty(); 15981 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 15982 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 15983 } 15984 break; 15985 case LAYER_TYPE_SOFTWARE: 15986 buildDrawingCache(true); 15987 break; 15988 } 15989 } 15990 15991 /** 15992 * Destroys all hardware rendering resources. This method is invoked 15993 * when the system needs to reclaim resources. Upon execution of this 15994 * method, you should free any OpenGL resources created by the view. 15995 * 15996 * Note: you <strong>must</strong> call 15997 * <code>super.destroyHardwareResources()</code> when overriding 15998 * this method. 15999 * 16000 * @hide 16001 */ 16002 @CallSuper 16003 protected void destroyHardwareResources() { 16004 // Although the Layer will be destroyed by RenderNode, we want to release 16005 // the staging display list, which is also a signal to RenderNode that it's 16006 // safe to free its copy of the display list as it knows that we will 16007 // push an updated DisplayList if we try to draw again 16008 resetDisplayList(); 16009 } 16010 16011 /** 16012 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 16013 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 16014 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 16015 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 16016 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 16017 * null.</p> 16018 * 16019 * <p>Enabling the drawing cache is similar to 16020 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 16021 * acceleration is turned off. When hardware acceleration is turned on, enabling the 16022 * drawing cache has no effect on rendering because the system uses a different mechanism 16023 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 16024 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 16025 * for information on how to enable software and hardware layers.</p> 16026 * 16027 * <p>This API can be used to manually generate 16028 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 16029 * {@link #getDrawingCache()}.</p> 16030 * 16031 * @param enabled true to enable the drawing cache, false otherwise 16032 * 16033 * @see #isDrawingCacheEnabled() 16034 * @see #getDrawingCache() 16035 * @see #buildDrawingCache() 16036 * @see #setLayerType(int, android.graphics.Paint) 16037 */ 16038 public void setDrawingCacheEnabled(boolean enabled) { 16039 mCachingFailed = false; 16040 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 16041 } 16042 16043 /** 16044 * <p>Indicates whether the drawing cache is enabled for this view.</p> 16045 * 16046 * @return true if the drawing cache is enabled 16047 * 16048 * @see #setDrawingCacheEnabled(boolean) 16049 * @see #getDrawingCache() 16050 */ 16051 @ViewDebug.ExportedProperty(category = "drawing") 16052 public boolean isDrawingCacheEnabled() { 16053 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 16054 } 16055 16056 /** 16057 * Debugging utility which recursively outputs the dirty state of a view and its 16058 * descendants. 16059 * 16060 * @hide 16061 */ 16062 @SuppressWarnings({"UnusedDeclaration"}) 16063 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 16064 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 16065 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 16066 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 16067 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 16068 if (clear) { 16069 mPrivateFlags &= clearMask; 16070 } 16071 if (this instanceof ViewGroup) { 16072 ViewGroup parent = (ViewGroup) this; 16073 final int count = parent.getChildCount(); 16074 for (int i = 0; i < count; i++) { 16075 final View child = parent.getChildAt(i); 16076 child.outputDirtyFlags(indent + " ", clear, clearMask); 16077 } 16078 } 16079 } 16080 16081 /** 16082 * This method is used by ViewGroup to cause its children to restore or recreate their 16083 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 16084 * to recreate its own display list, which would happen if it went through the normal 16085 * draw/dispatchDraw mechanisms. 16086 * 16087 * @hide 16088 */ 16089 protected void dispatchGetDisplayList() {} 16090 16091 /** 16092 * A view that is not attached or hardware accelerated cannot create a display list. 16093 * This method checks these conditions and returns the appropriate result. 16094 * 16095 * @return true if view has the ability to create a display list, false otherwise. 16096 * 16097 * @hide 16098 */ 16099 public boolean canHaveDisplayList() { 16100 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 16101 } 16102 16103 /** 16104 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 16105 * @hide 16106 */ 16107 @NonNull 16108 public RenderNode updateDisplayListIfDirty() { 16109 final RenderNode renderNode = mRenderNode; 16110 if (!canHaveDisplayList()) { 16111 // can't populate RenderNode, don't try 16112 return renderNode; 16113 } 16114 16115 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 16116 || !renderNode.isValid() 16117 || (mRecreateDisplayList)) { 16118 // Don't need to recreate the display list, just need to tell our 16119 // children to restore/recreate theirs 16120 if (renderNode.isValid() 16121 && !mRecreateDisplayList) { 16122 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16123 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16124 dispatchGetDisplayList(); 16125 16126 return renderNode; // no work needed 16127 } 16128 16129 // If we got here, we're recreating it. Mark it as such to ensure that 16130 // we copy in child display lists into ours in drawChild() 16131 mRecreateDisplayList = true; 16132 16133 int width = mRight - mLeft; 16134 int height = mBottom - mTop; 16135 int layerType = getLayerType(); 16136 16137 final DisplayListCanvas canvas = renderNode.start(width, height); 16138 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16139 16140 try { 16141 if (layerType == LAYER_TYPE_SOFTWARE) { 16142 buildDrawingCache(true); 16143 Bitmap cache = getDrawingCache(true); 16144 if (cache != null) { 16145 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16146 } 16147 } else { 16148 computeScroll(); 16149 16150 canvas.translate(-mScrollX, -mScrollY); 16151 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16152 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16153 16154 // Fast path for layouts with no backgrounds 16155 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16156 dispatchDraw(canvas); 16157 if (mOverlay != null && !mOverlay.isEmpty()) { 16158 mOverlay.getOverlayView().draw(canvas); 16159 } 16160 if (debugDraw()) { 16161 debugDrawFocus(canvas); 16162 } 16163 } else { 16164 draw(canvas); 16165 } 16166 } 16167 } finally { 16168 renderNode.end(canvas); 16169 setDisplayListProperties(renderNode); 16170 } 16171 } else { 16172 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16173 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16174 } 16175 return renderNode; 16176 } 16177 16178 private void resetDisplayList() { 16179 if (mRenderNode.isValid()) { 16180 mRenderNode.discardDisplayList(); 16181 } 16182 16183 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16184 mBackgroundRenderNode.discardDisplayList(); 16185 } 16186 } 16187 16188 /** 16189 * Called when the passed RenderNode is removed from the draw tree 16190 * @hide 16191 */ 16192 public void onRenderNodeDetached(RenderNode renderNode) { 16193 } 16194 16195 /** 16196 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16197 * 16198 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16199 * 16200 * @see #getDrawingCache(boolean) 16201 */ 16202 public Bitmap getDrawingCache() { 16203 return getDrawingCache(false); 16204 } 16205 16206 /** 16207 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16208 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16209 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16210 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16211 * request the drawing cache by calling this method and draw it on screen if the 16212 * returned bitmap is not null.</p> 16213 * 16214 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16215 * this method will create a bitmap of the same size as this view. Because this bitmap 16216 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16217 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16218 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16219 * size than the view. This implies that your application must be able to handle this 16220 * size.</p> 16221 * 16222 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16223 * the current density of the screen when the application is in compatibility 16224 * mode. 16225 * 16226 * @return A bitmap representing this view or null if cache is disabled. 16227 * 16228 * @see #setDrawingCacheEnabled(boolean) 16229 * @see #isDrawingCacheEnabled() 16230 * @see #buildDrawingCache(boolean) 16231 * @see #destroyDrawingCache() 16232 */ 16233 public Bitmap getDrawingCache(boolean autoScale) { 16234 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16235 return null; 16236 } 16237 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16238 buildDrawingCache(autoScale); 16239 } 16240 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16241 } 16242 16243 /** 16244 * <p>Frees the resources used by the drawing cache. If you call 16245 * {@link #buildDrawingCache()} manually without calling 16246 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16247 * should cleanup the cache with this method afterwards.</p> 16248 * 16249 * @see #setDrawingCacheEnabled(boolean) 16250 * @see #buildDrawingCache() 16251 * @see #getDrawingCache() 16252 */ 16253 public void destroyDrawingCache() { 16254 if (mDrawingCache != null) { 16255 mDrawingCache.recycle(); 16256 mDrawingCache = null; 16257 } 16258 if (mUnscaledDrawingCache != null) { 16259 mUnscaledDrawingCache.recycle(); 16260 mUnscaledDrawingCache = null; 16261 } 16262 } 16263 16264 /** 16265 * Setting a solid background color for the drawing cache's bitmaps will improve 16266 * performance and memory usage. Note, though that this should only be used if this 16267 * view will always be drawn on top of a solid color. 16268 * 16269 * @param color The background color to use for the drawing cache's bitmap 16270 * 16271 * @see #setDrawingCacheEnabled(boolean) 16272 * @see #buildDrawingCache() 16273 * @see #getDrawingCache() 16274 */ 16275 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16276 if (color != mDrawingCacheBackgroundColor) { 16277 mDrawingCacheBackgroundColor = color; 16278 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16279 } 16280 } 16281 16282 /** 16283 * @see #setDrawingCacheBackgroundColor(int) 16284 * 16285 * @return The background color to used for the drawing cache's bitmap 16286 */ 16287 @ColorInt 16288 public int getDrawingCacheBackgroundColor() { 16289 return mDrawingCacheBackgroundColor; 16290 } 16291 16292 /** 16293 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16294 * 16295 * @see #buildDrawingCache(boolean) 16296 */ 16297 public void buildDrawingCache() { 16298 buildDrawingCache(false); 16299 } 16300 16301 /** 16302 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16303 * 16304 * <p>If you call {@link #buildDrawingCache()} manually without calling 16305 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16306 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16307 * 16308 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16309 * this method will create a bitmap of the same size as this view. Because this bitmap 16310 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16311 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16312 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16313 * size than the view. This implies that your application must be able to handle this 16314 * size.</p> 16315 * 16316 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16317 * you do not need the drawing cache bitmap, calling this method will increase memory 16318 * usage and cause the view to be rendered in software once, thus negatively impacting 16319 * performance.</p> 16320 * 16321 * @see #getDrawingCache() 16322 * @see #destroyDrawingCache() 16323 */ 16324 public void buildDrawingCache(boolean autoScale) { 16325 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16326 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16327 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16328 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16329 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16330 } 16331 try { 16332 buildDrawingCacheImpl(autoScale); 16333 } finally { 16334 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16335 } 16336 } 16337 } 16338 16339 /** 16340 * private, internal implementation of buildDrawingCache, used to enable tracing 16341 */ 16342 private void buildDrawingCacheImpl(boolean autoScale) { 16343 mCachingFailed = false; 16344 16345 int width = mRight - mLeft; 16346 int height = mBottom - mTop; 16347 16348 final AttachInfo attachInfo = mAttachInfo; 16349 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16350 16351 if (autoScale && scalingRequired) { 16352 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16353 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16354 } 16355 16356 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16357 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16358 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16359 16360 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16361 final long drawingCacheSize = 16362 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16363 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16364 if (width > 0 && height > 0) { 16365 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16366 + " too large to fit into a software layer (or drawing cache), needs " 16367 + projectedBitmapSize + " bytes, only " 16368 + drawingCacheSize + " available"); 16369 } 16370 destroyDrawingCache(); 16371 mCachingFailed = true; 16372 return; 16373 } 16374 16375 boolean clear = true; 16376 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16377 16378 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16379 Bitmap.Config quality; 16380 if (!opaque) { 16381 // Never pick ARGB_4444 because it looks awful 16382 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16383 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16384 case DRAWING_CACHE_QUALITY_AUTO: 16385 case DRAWING_CACHE_QUALITY_LOW: 16386 case DRAWING_CACHE_QUALITY_HIGH: 16387 default: 16388 quality = Bitmap.Config.ARGB_8888; 16389 break; 16390 } 16391 } else { 16392 // Optimization for translucent windows 16393 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16394 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16395 } 16396 16397 // Try to cleanup memory 16398 if (bitmap != null) bitmap.recycle(); 16399 16400 try { 16401 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16402 width, height, quality); 16403 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16404 if (autoScale) { 16405 mDrawingCache = bitmap; 16406 } else { 16407 mUnscaledDrawingCache = bitmap; 16408 } 16409 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16410 } catch (OutOfMemoryError e) { 16411 // If there is not enough memory to create the bitmap cache, just 16412 // ignore the issue as bitmap caches are not required to draw the 16413 // view hierarchy 16414 if (autoScale) { 16415 mDrawingCache = null; 16416 } else { 16417 mUnscaledDrawingCache = null; 16418 } 16419 mCachingFailed = true; 16420 return; 16421 } 16422 16423 clear = drawingCacheBackgroundColor != 0; 16424 } 16425 16426 Canvas canvas; 16427 if (attachInfo != null) { 16428 canvas = attachInfo.mCanvas; 16429 if (canvas == null) { 16430 canvas = new Canvas(); 16431 } 16432 canvas.setBitmap(bitmap); 16433 // Temporarily clobber the cached Canvas in case one of our children 16434 // is also using a drawing cache. Without this, the children would 16435 // steal the canvas by attaching their own bitmap to it and bad, bad 16436 // thing would happen (invisible views, corrupted drawings, etc.) 16437 attachInfo.mCanvas = null; 16438 } else { 16439 // This case should hopefully never or seldom happen 16440 canvas = new Canvas(bitmap); 16441 } 16442 16443 if (clear) { 16444 bitmap.eraseColor(drawingCacheBackgroundColor); 16445 } 16446 16447 computeScroll(); 16448 final int restoreCount = canvas.save(); 16449 16450 if (autoScale && scalingRequired) { 16451 final float scale = attachInfo.mApplicationScale; 16452 canvas.scale(scale, scale); 16453 } 16454 16455 canvas.translate(-mScrollX, -mScrollY); 16456 16457 mPrivateFlags |= PFLAG_DRAWN; 16458 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16459 mLayerType != LAYER_TYPE_NONE) { 16460 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16461 } 16462 16463 // Fast path for layouts with no backgrounds 16464 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16465 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16466 dispatchDraw(canvas); 16467 if (mOverlay != null && !mOverlay.isEmpty()) { 16468 mOverlay.getOverlayView().draw(canvas); 16469 } 16470 } else { 16471 draw(canvas); 16472 } 16473 16474 canvas.restoreToCount(restoreCount); 16475 canvas.setBitmap(null); 16476 16477 if (attachInfo != null) { 16478 // Restore the cached Canvas for our siblings 16479 attachInfo.mCanvas = canvas; 16480 } 16481 } 16482 16483 /** 16484 * Create a snapshot of the view into a bitmap. We should probably make 16485 * some form of this public, but should think about the API. 16486 * 16487 * @hide 16488 */ 16489 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16490 int width = mRight - mLeft; 16491 int height = mBottom - mTop; 16492 16493 final AttachInfo attachInfo = mAttachInfo; 16494 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16495 width = (int) ((width * scale) + 0.5f); 16496 height = (int) ((height * scale) + 0.5f); 16497 16498 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16499 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16500 if (bitmap == null) { 16501 throw new OutOfMemoryError(); 16502 } 16503 16504 Resources resources = getResources(); 16505 if (resources != null) { 16506 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16507 } 16508 16509 Canvas canvas; 16510 if (attachInfo != null) { 16511 canvas = attachInfo.mCanvas; 16512 if (canvas == null) { 16513 canvas = new Canvas(); 16514 } 16515 canvas.setBitmap(bitmap); 16516 // Temporarily clobber the cached Canvas in case one of our children 16517 // is also using a drawing cache. Without this, the children would 16518 // steal the canvas by attaching their own bitmap to it and bad, bad 16519 // things would happen (invisible views, corrupted drawings, etc.) 16520 attachInfo.mCanvas = null; 16521 } else { 16522 // This case should hopefully never or seldom happen 16523 canvas = new Canvas(bitmap); 16524 } 16525 16526 if ((backgroundColor & 0xff000000) != 0) { 16527 bitmap.eraseColor(backgroundColor); 16528 } 16529 16530 computeScroll(); 16531 final int restoreCount = canvas.save(); 16532 canvas.scale(scale, scale); 16533 canvas.translate(-mScrollX, -mScrollY); 16534 16535 // Temporarily remove the dirty mask 16536 int flags = mPrivateFlags; 16537 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16538 16539 // Fast path for layouts with no backgrounds 16540 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16541 dispatchDraw(canvas); 16542 if (mOverlay != null && !mOverlay.isEmpty()) { 16543 mOverlay.getOverlayView().draw(canvas); 16544 } 16545 } else { 16546 draw(canvas); 16547 } 16548 16549 mPrivateFlags = flags; 16550 16551 canvas.restoreToCount(restoreCount); 16552 canvas.setBitmap(null); 16553 16554 if (attachInfo != null) { 16555 // Restore the cached Canvas for our siblings 16556 attachInfo.mCanvas = canvas; 16557 } 16558 16559 return bitmap; 16560 } 16561 16562 /** 16563 * Indicates whether this View is currently in edit mode. A View is usually 16564 * in edit mode when displayed within a developer tool. For instance, if 16565 * this View is being drawn by a visual user interface builder, this method 16566 * should return true. 16567 * 16568 * Subclasses should check the return value of this method to provide 16569 * different behaviors if their normal behavior might interfere with the 16570 * host environment. For instance: the class spawns a thread in its 16571 * constructor, the drawing code relies on device-specific features, etc. 16572 * 16573 * This method is usually checked in the drawing code of custom widgets. 16574 * 16575 * @return True if this View is in edit mode, false otherwise. 16576 */ 16577 public boolean isInEditMode() { 16578 return false; 16579 } 16580 16581 /** 16582 * If the View draws content inside its padding and enables fading edges, 16583 * it needs to support padding offsets. Padding offsets are added to the 16584 * fading edges to extend the length of the fade so that it covers pixels 16585 * drawn inside the padding. 16586 * 16587 * Subclasses of this class should override this method if they need 16588 * to draw content inside the padding. 16589 * 16590 * @return True if padding offset must be applied, false otherwise. 16591 * 16592 * @see #getLeftPaddingOffset() 16593 * @see #getRightPaddingOffset() 16594 * @see #getTopPaddingOffset() 16595 * @see #getBottomPaddingOffset() 16596 * 16597 * @since CURRENT 16598 */ 16599 protected boolean isPaddingOffsetRequired() { 16600 return false; 16601 } 16602 16603 /** 16604 * Amount by which to extend the left fading region. Called only when 16605 * {@link #isPaddingOffsetRequired()} returns true. 16606 * 16607 * @return The left padding offset in pixels. 16608 * 16609 * @see #isPaddingOffsetRequired() 16610 * 16611 * @since CURRENT 16612 */ 16613 protected int getLeftPaddingOffset() { 16614 return 0; 16615 } 16616 16617 /** 16618 * Amount by which to extend the right fading region. Called only when 16619 * {@link #isPaddingOffsetRequired()} returns true. 16620 * 16621 * @return The right padding offset in pixels. 16622 * 16623 * @see #isPaddingOffsetRequired() 16624 * 16625 * @since CURRENT 16626 */ 16627 protected int getRightPaddingOffset() { 16628 return 0; 16629 } 16630 16631 /** 16632 * Amount by which to extend the top fading region. Called only when 16633 * {@link #isPaddingOffsetRequired()} returns true. 16634 * 16635 * @return The top padding offset in pixels. 16636 * 16637 * @see #isPaddingOffsetRequired() 16638 * 16639 * @since CURRENT 16640 */ 16641 protected int getTopPaddingOffset() { 16642 return 0; 16643 } 16644 16645 /** 16646 * Amount by which to extend the bottom fading region. Called only when 16647 * {@link #isPaddingOffsetRequired()} returns true. 16648 * 16649 * @return The bottom padding offset in pixels. 16650 * 16651 * @see #isPaddingOffsetRequired() 16652 * 16653 * @since CURRENT 16654 */ 16655 protected int getBottomPaddingOffset() { 16656 return 0; 16657 } 16658 16659 /** 16660 * @hide 16661 * @param offsetRequired 16662 */ 16663 protected int getFadeTop(boolean offsetRequired) { 16664 int top = mPaddingTop; 16665 if (offsetRequired) top += getTopPaddingOffset(); 16666 return top; 16667 } 16668 16669 /** 16670 * @hide 16671 * @param offsetRequired 16672 */ 16673 protected int getFadeHeight(boolean offsetRequired) { 16674 int padding = mPaddingTop; 16675 if (offsetRequired) padding += getTopPaddingOffset(); 16676 return mBottom - mTop - mPaddingBottom - padding; 16677 } 16678 16679 /** 16680 * <p>Indicates whether this view is attached to a hardware accelerated 16681 * window or not.</p> 16682 * 16683 * <p>Even if this method returns true, it does not mean that every call 16684 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16685 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16686 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16687 * window is hardware accelerated, 16688 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16689 * return false, and this method will return true.</p> 16690 * 16691 * @return True if the view is attached to a window and the window is 16692 * hardware accelerated; false in any other case. 16693 */ 16694 @ViewDebug.ExportedProperty(category = "drawing") 16695 public boolean isHardwareAccelerated() { 16696 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16697 } 16698 16699 /** 16700 * Sets a rectangular area on this view to which the view will be clipped 16701 * when it is drawn. Setting the value to null will remove the clip bounds 16702 * and the view will draw normally, using its full bounds. 16703 * 16704 * @param clipBounds The rectangular area, in the local coordinates of 16705 * this view, to which future drawing operations will be clipped. 16706 */ 16707 public void setClipBounds(Rect clipBounds) { 16708 if (clipBounds == mClipBounds 16709 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16710 return; 16711 } 16712 if (clipBounds != null) { 16713 if (mClipBounds == null) { 16714 mClipBounds = new Rect(clipBounds); 16715 } else { 16716 mClipBounds.set(clipBounds); 16717 } 16718 } else { 16719 mClipBounds = null; 16720 } 16721 mRenderNode.setClipBounds(mClipBounds); 16722 invalidateViewProperty(false, false); 16723 } 16724 16725 /** 16726 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16727 * 16728 * @return A copy of the current clip bounds if clip bounds are set, 16729 * otherwise null. 16730 */ 16731 public Rect getClipBounds() { 16732 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16733 } 16734 16735 16736 /** 16737 * Populates an output rectangle with the clip bounds of the view, 16738 * returning {@code true} if successful or {@code false} if the view's 16739 * clip bounds are {@code null}. 16740 * 16741 * @param outRect rectangle in which to place the clip bounds of the view 16742 * @return {@code true} if successful or {@code false} if the view's 16743 * clip bounds are {@code null} 16744 */ 16745 public boolean getClipBounds(Rect outRect) { 16746 if (mClipBounds != null) { 16747 outRect.set(mClipBounds); 16748 return true; 16749 } 16750 return false; 16751 } 16752 16753 /** 16754 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16755 * case of an active Animation being run on the view. 16756 */ 16757 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16758 Animation a, boolean scalingRequired) { 16759 Transformation invalidationTransform; 16760 final int flags = parent.mGroupFlags; 16761 final boolean initialized = a.isInitialized(); 16762 if (!initialized) { 16763 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16764 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16765 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16766 onAnimationStart(); 16767 } 16768 16769 final Transformation t = parent.getChildTransformation(); 16770 boolean more = a.getTransformation(drawingTime, t, 1f); 16771 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16772 if (parent.mInvalidationTransformation == null) { 16773 parent.mInvalidationTransformation = new Transformation(); 16774 } 16775 invalidationTransform = parent.mInvalidationTransformation; 16776 a.getTransformation(drawingTime, invalidationTransform, 1f); 16777 } else { 16778 invalidationTransform = t; 16779 } 16780 16781 if (more) { 16782 if (!a.willChangeBounds()) { 16783 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16784 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16785 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16786 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16787 // The child need to draw an animation, potentially offscreen, so 16788 // make sure we do not cancel invalidate requests 16789 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16790 parent.invalidate(mLeft, mTop, mRight, mBottom); 16791 } 16792 } else { 16793 if (parent.mInvalidateRegion == null) { 16794 parent.mInvalidateRegion = new RectF(); 16795 } 16796 final RectF region = parent.mInvalidateRegion; 16797 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16798 invalidationTransform); 16799 16800 // The child need to draw an animation, potentially offscreen, so 16801 // make sure we do not cancel invalidate requests 16802 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16803 16804 final int left = mLeft + (int) region.left; 16805 final int top = mTop + (int) region.top; 16806 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16807 top + (int) (region.height() + .5f)); 16808 } 16809 } 16810 return more; 16811 } 16812 16813 /** 16814 * This method is called by getDisplayList() when a display list is recorded for a View. 16815 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16816 */ 16817 void setDisplayListProperties(RenderNode renderNode) { 16818 if (renderNode != null) { 16819 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16820 renderNode.setClipToBounds(mParent instanceof ViewGroup 16821 && ((ViewGroup) mParent).getClipChildren()); 16822 16823 float alpha = 1; 16824 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16825 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16826 ViewGroup parentVG = (ViewGroup) mParent; 16827 final Transformation t = parentVG.getChildTransformation(); 16828 if (parentVG.getChildStaticTransformation(this, t)) { 16829 final int transformType = t.getTransformationType(); 16830 if (transformType != Transformation.TYPE_IDENTITY) { 16831 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16832 alpha = t.getAlpha(); 16833 } 16834 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16835 renderNode.setStaticMatrix(t.getMatrix()); 16836 } 16837 } 16838 } 16839 } 16840 if (mTransformationInfo != null) { 16841 alpha *= getFinalAlpha(); 16842 if (alpha < 1) { 16843 final int multipliedAlpha = (int) (255 * alpha); 16844 if (onSetAlpha(multipliedAlpha)) { 16845 alpha = 1; 16846 } 16847 } 16848 renderNode.setAlpha(alpha); 16849 } else if (alpha < 1) { 16850 renderNode.setAlpha(alpha); 16851 } 16852 } 16853 } 16854 16855 /** 16856 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16857 * 16858 * This is where the View specializes rendering behavior based on layer type, 16859 * and hardware acceleration. 16860 */ 16861 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16862 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16863 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16864 * 16865 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16866 * HW accelerated, it can't handle drawing RenderNodes. 16867 */ 16868 boolean drawingWithRenderNode = mAttachInfo != null 16869 && mAttachInfo.mHardwareAccelerated 16870 && hardwareAcceleratedCanvas; 16871 16872 boolean more = false; 16873 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16874 final int parentFlags = parent.mGroupFlags; 16875 16876 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16877 parent.getChildTransformation().clear(); 16878 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16879 } 16880 16881 Transformation transformToApply = null; 16882 boolean concatMatrix = false; 16883 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16884 final Animation a = getAnimation(); 16885 if (a != null) { 16886 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16887 concatMatrix = a.willChangeTransformationMatrix(); 16888 if (concatMatrix) { 16889 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16890 } 16891 transformToApply = parent.getChildTransformation(); 16892 } else { 16893 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16894 // No longer animating: clear out old animation matrix 16895 mRenderNode.setAnimationMatrix(null); 16896 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16897 } 16898 if (!drawingWithRenderNode 16899 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16900 final Transformation t = parent.getChildTransformation(); 16901 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16902 if (hasTransform) { 16903 final int transformType = t.getTransformationType(); 16904 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16905 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16906 } 16907 } 16908 } 16909 16910 concatMatrix |= !childHasIdentityMatrix; 16911 16912 // Sets the flag as early as possible to allow draw() implementations 16913 // to call invalidate() successfully when doing animations 16914 mPrivateFlags |= PFLAG_DRAWN; 16915 16916 if (!concatMatrix && 16917 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16918 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16919 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16920 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16921 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16922 return more; 16923 } 16924 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16925 16926 if (hardwareAcceleratedCanvas) { 16927 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16928 // retain the flag's value temporarily in the mRecreateDisplayList flag 16929 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16930 mPrivateFlags &= ~PFLAG_INVALIDATED; 16931 } 16932 16933 RenderNode renderNode = null; 16934 Bitmap cache = null; 16935 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16936 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16937 if (layerType != LAYER_TYPE_NONE) { 16938 // If not drawing with RenderNode, treat HW layers as SW 16939 layerType = LAYER_TYPE_SOFTWARE; 16940 buildDrawingCache(true); 16941 } 16942 cache = getDrawingCache(true); 16943 } 16944 16945 if (drawingWithRenderNode) { 16946 // Delay getting the display list until animation-driven alpha values are 16947 // set up and possibly passed on to the view 16948 renderNode = updateDisplayListIfDirty(); 16949 if (!renderNode.isValid()) { 16950 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16951 // to getDisplayList(), the display list will be marked invalid and we should not 16952 // try to use it again. 16953 renderNode = null; 16954 drawingWithRenderNode = false; 16955 } 16956 } 16957 16958 int sx = 0; 16959 int sy = 0; 16960 if (!drawingWithRenderNode) { 16961 computeScroll(); 16962 sx = mScrollX; 16963 sy = mScrollY; 16964 } 16965 16966 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16967 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16968 16969 int restoreTo = -1; 16970 if (!drawingWithRenderNode || transformToApply != null) { 16971 restoreTo = canvas.save(); 16972 } 16973 if (offsetForScroll) { 16974 canvas.translate(mLeft - sx, mTop - sy); 16975 } else { 16976 if (!drawingWithRenderNode) { 16977 canvas.translate(mLeft, mTop); 16978 } 16979 if (scalingRequired) { 16980 if (drawingWithRenderNode) { 16981 // TODO: Might not need this if we put everything inside the DL 16982 restoreTo = canvas.save(); 16983 } 16984 // mAttachInfo cannot be null, otherwise scalingRequired == false 16985 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16986 canvas.scale(scale, scale); 16987 } 16988 } 16989 16990 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16991 if (transformToApply != null 16992 || alpha < 1 16993 || !hasIdentityMatrix() 16994 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16995 if (transformToApply != null || !childHasIdentityMatrix) { 16996 int transX = 0; 16997 int transY = 0; 16998 16999 if (offsetForScroll) { 17000 transX = -sx; 17001 transY = -sy; 17002 } 17003 17004 if (transformToApply != null) { 17005 if (concatMatrix) { 17006 if (drawingWithRenderNode) { 17007 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 17008 } else { 17009 // Undo the scroll translation, apply the transformation matrix, 17010 // then redo the scroll translate to get the correct result. 17011 canvas.translate(-transX, -transY); 17012 canvas.concat(transformToApply.getMatrix()); 17013 canvas.translate(transX, transY); 17014 } 17015 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17016 } 17017 17018 float transformAlpha = transformToApply.getAlpha(); 17019 if (transformAlpha < 1) { 17020 alpha *= transformAlpha; 17021 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17022 } 17023 } 17024 17025 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 17026 canvas.translate(-transX, -transY); 17027 canvas.concat(getMatrix()); 17028 canvas.translate(transX, transY); 17029 } 17030 } 17031 17032 // Deal with alpha if it is or used to be <1 17033 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 17034 if (alpha < 1) { 17035 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17036 } else { 17037 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 17038 } 17039 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 17040 if (!drawingWithDrawingCache) { 17041 final int multipliedAlpha = (int) (255 * alpha); 17042 if (!onSetAlpha(multipliedAlpha)) { 17043 if (drawingWithRenderNode) { 17044 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 17045 } else if (layerType == LAYER_TYPE_NONE) { 17046 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 17047 multipliedAlpha); 17048 } 17049 } else { 17050 // Alpha is handled by the child directly, clobber the layer's alpha 17051 mPrivateFlags |= PFLAG_ALPHA_SET; 17052 } 17053 } 17054 } 17055 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17056 onSetAlpha(255); 17057 mPrivateFlags &= ~PFLAG_ALPHA_SET; 17058 } 17059 17060 if (!drawingWithRenderNode) { 17061 // apply clips directly, since RenderNode won't do it for this draw 17062 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 17063 if (offsetForScroll) { 17064 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 17065 } else { 17066 if (!scalingRequired || cache == null) { 17067 canvas.clipRect(0, 0, getWidth(), getHeight()); 17068 } else { 17069 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 17070 } 17071 } 17072 } 17073 17074 if (mClipBounds != null) { 17075 // clip bounds ignore scroll 17076 canvas.clipRect(mClipBounds); 17077 } 17078 } 17079 17080 if (!drawingWithDrawingCache) { 17081 if (drawingWithRenderNode) { 17082 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17083 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17084 } else { 17085 // Fast path for layouts with no backgrounds 17086 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17087 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17088 dispatchDraw(canvas); 17089 } else { 17090 draw(canvas); 17091 } 17092 } 17093 } else if (cache != null) { 17094 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17095 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 17096 // no layer paint, use temporary paint to draw bitmap 17097 Paint cachePaint = parent.mCachePaint; 17098 if (cachePaint == null) { 17099 cachePaint = new Paint(); 17100 cachePaint.setDither(false); 17101 parent.mCachePaint = cachePaint; 17102 } 17103 cachePaint.setAlpha((int) (alpha * 255)); 17104 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 17105 } else { 17106 // use layer paint to draw the bitmap, merging the two alphas, but also restore 17107 int layerPaintAlpha = mLayerPaint.getAlpha(); 17108 if (alpha < 1) { 17109 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 17110 } 17111 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17112 if (alpha < 1) { 17113 mLayerPaint.setAlpha(layerPaintAlpha); 17114 } 17115 } 17116 } 17117 17118 if (restoreTo >= 0) { 17119 canvas.restoreToCount(restoreTo); 17120 } 17121 17122 if (a != null && !more) { 17123 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17124 onSetAlpha(255); 17125 } 17126 parent.finishAnimatingView(this, a); 17127 } 17128 17129 if (more && hardwareAcceleratedCanvas) { 17130 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17131 // alpha animations should cause the child to recreate its display list 17132 invalidate(true); 17133 } 17134 } 17135 17136 mRecreateDisplayList = false; 17137 17138 return more; 17139 } 17140 17141 static Paint getDebugPaint() { 17142 if (sDebugPaint == null) { 17143 sDebugPaint = new Paint(); 17144 sDebugPaint.setAntiAlias(false); 17145 } 17146 return sDebugPaint; 17147 } 17148 17149 final int dipsToPixels(int dips) { 17150 float scale = getContext().getResources().getDisplayMetrics().density; 17151 return (int) (dips * scale + 0.5f); 17152 } 17153 17154 final private void debugDrawFocus(Canvas canvas) { 17155 if (isFocused()) { 17156 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 17157 final int l = mScrollX; 17158 final int r = l + mRight - mLeft; 17159 final int t = mScrollY; 17160 final int b = t + mBottom - mTop; 17161 17162 final Paint paint = getDebugPaint(); 17163 paint.setColor(DEBUG_CORNERS_COLOR); 17164 17165 // Draw squares in corners. 17166 paint.setStyle(Paint.Style.FILL); 17167 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 17168 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 17169 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 17170 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 17171 17172 // Draw big X across the view. 17173 paint.setStyle(Paint.Style.STROKE); 17174 canvas.drawLine(l, t, r, b, paint); 17175 canvas.drawLine(l, b, r, t, paint); 17176 } 17177 } 17178 17179 /** 17180 * Manually render this view (and all of its children) to the given Canvas. 17181 * The view must have already done a full layout before this function is 17182 * called. When implementing a view, implement 17183 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17184 * If you do need to override this method, call the superclass version. 17185 * 17186 * @param canvas The Canvas to which the View is rendered. 17187 */ 17188 @CallSuper 17189 public void draw(Canvas canvas) { 17190 final int privateFlags = mPrivateFlags; 17191 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17192 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17193 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17194 17195 /* 17196 * Draw traversal performs several drawing steps which must be executed 17197 * in the appropriate order: 17198 * 17199 * 1. Draw the background 17200 * 2. If necessary, save the canvas' layers to prepare for fading 17201 * 3. Draw view's content 17202 * 4. Draw children 17203 * 5. If necessary, draw the fading edges and restore layers 17204 * 6. Draw decorations (scrollbars for instance) 17205 */ 17206 17207 // Step 1, draw the background, if needed 17208 int saveCount; 17209 17210 if (!dirtyOpaque) { 17211 drawBackground(canvas); 17212 } 17213 17214 // skip step 2 & 5 if possible (common case) 17215 final int viewFlags = mViewFlags; 17216 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17217 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17218 if (!verticalEdges && !horizontalEdges) { 17219 // Step 3, draw the content 17220 if (!dirtyOpaque) onDraw(canvas); 17221 17222 // Step 4, draw the children 17223 dispatchDraw(canvas); 17224 17225 // Overlay is part of the content and draws beneath Foreground 17226 if (mOverlay != null && !mOverlay.isEmpty()) { 17227 mOverlay.getOverlayView().dispatchDraw(canvas); 17228 } 17229 17230 // Step 6, draw decorations (foreground, scrollbars) 17231 onDrawForeground(canvas); 17232 17233 if (debugDraw()) { 17234 debugDrawFocus(canvas); 17235 } 17236 17237 // we're done... 17238 return; 17239 } 17240 17241 /* 17242 * Here we do the full fledged routine... 17243 * (this is an uncommon case where speed matters less, 17244 * this is why we repeat some of the tests that have been 17245 * done above) 17246 */ 17247 17248 boolean drawTop = false; 17249 boolean drawBottom = false; 17250 boolean drawLeft = false; 17251 boolean drawRight = false; 17252 17253 float topFadeStrength = 0.0f; 17254 float bottomFadeStrength = 0.0f; 17255 float leftFadeStrength = 0.0f; 17256 float rightFadeStrength = 0.0f; 17257 17258 // Step 2, save the canvas' layers 17259 int paddingLeft = mPaddingLeft; 17260 17261 final boolean offsetRequired = isPaddingOffsetRequired(); 17262 if (offsetRequired) { 17263 paddingLeft += getLeftPaddingOffset(); 17264 } 17265 17266 int left = mScrollX + paddingLeft; 17267 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17268 int top = mScrollY + getFadeTop(offsetRequired); 17269 int bottom = top + getFadeHeight(offsetRequired); 17270 17271 if (offsetRequired) { 17272 right += getRightPaddingOffset(); 17273 bottom += getBottomPaddingOffset(); 17274 } 17275 17276 final ScrollabilityCache scrollabilityCache = mScrollCache; 17277 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17278 int length = (int) fadeHeight; 17279 17280 // clip the fade length if top and bottom fades overlap 17281 // overlapping fades produce odd-looking artifacts 17282 if (verticalEdges && (top + length > bottom - length)) { 17283 length = (bottom - top) / 2; 17284 } 17285 17286 // also clip horizontal fades if necessary 17287 if (horizontalEdges && (left + length > right - length)) { 17288 length = (right - left) / 2; 17289 } 17290 17291 if (verticalEdges) { 17292 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17293 drawTop = topFadeStrength * fadeHeight > 1.0f; 17294 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17295 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17296 } 17297 17298 if (horizontalEdges) { 17299 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17300 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17301 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17302 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17303 } 17304 17305 saveCount = canvas.getSaveCount(); 17306 17307 int solidColor = getSolidColor(); 17308 if (solidColor == 0) { 17309 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17310 17311 if (drawTop) { 17312 canvas.saveLayer(left, top, right, top + length, null, flags); 17313 } 17314 17315 if (drawBottom) { 17316 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17317 } 17318 17319 if (drawLeft) { 17320 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17321 } 17322 17323 if (drawRight) { 17324 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17325 } 17326 } else { 17327 scrollabilityCache.setFadeColor(solidColor); 17328 } 17329 17330 // Step 3, draw the content 17331 if (!dirtyOpaque) onDraw(canvas); 17332 17333 // Step 4, draw the children 17334 dispatchDraw(canvas); 17335 17336 // Step 5, draw the fade effect and restore layers 17337 final Paint p = scrollabilityCache.paint; 17338 final Matrix matrix = scrollabilityCache.matrix; 17339 final Shader fade = scrollabilityCache.shader; 17340 17341 if (drawTop) { 17342 matrix.setScale(1, fadeHeight * topFadeStrength); 17343 matrix.postTranslate(left, top); 17344 fade.setLocalMatrix(matrix); 17345 p.setShader(fade); 17346 canvas.drawRect(left, top, right, top + length, p); 17347 } 17348 17349 if (drawBottom) { 17350 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17351 matrix.postRotate(180); 17352 matrix.postTranslate(left, bottom); 17353 fade.setLocalMatrix(matrix); 17354 p.setShader(fade); 17355 canvas.drawRect(left, bottom - length, right, bottom, p); 17356 } 17357 17358 if (drawLeft) { 17359 matrix.setScale(1, fadeHeight * leftFadeStrength); 17360 matrix.postRotate(-90); 17361 matrix.postTranslate(left, top); 17362 fade.setLocalMatrix(matrix); 17363 p.setShader(fade); 17364 canvas.drawRect(left, top, left + length, bottom, p); 17365 } 17366 17367 if (drawRight) { 17368 matrix.setScale(1, fadeHeight * rightFadeStrength); 17369 matrix.postRotate(90); 17370 matrix.postTranslate(right, top); 17371 fade.setLocalMatrix(matrix); 17372 p.setShader(fade); 17373 canvas.drawRect(right - length, top, right, bottom, p); 17374 } 17375 17376 canvas.restoreToCount(saveCount); 17377 17378 // Overlay is part of the content and draws beneath Foreground 17379 if (mOverlay != null && !mOverlay.isEmpty()) { 17380 mOverlay.getOverlayView().dispatchDraw(canvas); 17381 } 17382 17383 // Step 6, draw decorations (foreground, scrollbars) 17384 onDrawForeground(canvas); 17385 17386 if (debugDraw()) { 17387 debugDrawFocus(canvas); 17388 } 17389 } 17390 17391 /** 17392 * Draws the background onto the specified canvas. 17393 * 17394 * @param canvas Canvas on which to draw the background 17395 */ 17396 private void drawBackground(Canvas canvas) { 17397 final Drawable background = mBackground; 17398 if (background == null) { 17399 return; 17400 } 17401 17402 setBackgroundBounds(); 17403 17404 // Attempt to use a display list if requested. 17405 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17406 && mAttachInfo.mThreadedRenderer != null) { 17407 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17408 17409 final RenderNode renderNode = mBackgroundRenderNode; 17410 if (renderNode != null && renderNode.isValid()) { 17411 setBackgroundRenderNodeProperties(renderNode); 17412 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17413 return; 17414 } 17415 } 17416 17417 final int scrollX = mScrollX; 17418 final int scrollY = mScrollY; 17419 if ((scrollX | scrollY) == 0) { 17420 background.draw(canvas); 17421 } else { 17422 canvas.translate(scrollX, scrollY); 17423 background.draw(canvas); 17424 canvas.translate(-scrollX, -scrollY); 17425 } 17426 } 17427 17428 /** 17429 * Sets the correct background bounds and rebuilds the outline, if needed. 17430 * <p/> 17431 * This is called by LayoutLib. 17432 */ 17433 void setBackgroundBounds() { 17434 if (mBackgroundSizeChanged && mBackground != null) { 17435 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17436 mBackgroundSizeChanged = false; 17437 rebuildOutline(); 17438 } 17439 } 17440 17441 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17442 renderNode.setTranslationX(mScrollX); 17443 renderNode.setTranslationY(mScrollY); 17444 } 17445 17446 /** 17447 * Creates a new display list or updates the existing display list for the 17448 * specified Drawable. 17449 * 17450 * @param drawable Drawable for which to create a display list 17451 * @param renderNode Existing RenderNode, or {@code null} 17452 * @return A valid display list for the specified drawable 17453 */ 17454 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17455 if (renderNode == null) { 17456 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17457 } 17458 17459 final Rect bounds = drawable.getBounds(); 17460 final int width = bounds.width(); 17461 final int height = bounds.height(); 17462 final DisplayListCanvas canvas = renderNode.start(width, height); 17463 17464 // Reverse left/top translation done by drawable canvas, which will 17465 // instead be applied by rendernode's LTRB bounds below. This way, the 17466 // drawable's bounds match with its rendernode bounds and its content 17467 // will lie within those bounds in the rendernode tree. 17468 canvas.translate(-bounds.left, -bounds.top); 17469 17470 try { 17471 drawable.draw(canvas); 17472 } finally { 17473 renderNode.end(canvas); 17474 } 17475 17476 // Set up drawable properties that are view-independent. 17477 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17478 renderNode.setProjectBackwards(drawable.isProjected()); 17479 renderNode.setProjectionReceiver(true); 17480 renderNode.setClipToBounds(false); 17481 return renderNode; 17482 } 17483 17484 /** 17485 * Returns the overlay for this view, creating it if it does not yet exist. 17486 * Adding drawables to the overlay will cause them to be displayed whenever 17487 * the view itself is redrawn. Objects in the overlay should be actively 17488 * managed: remove them when they should not be displayed anymore. The 17489 * overlay will always have the same size as its host view. 17490 * 17491 * <p>Note: Overlays do not currently work correctly with {@link 17492 * SurfaceView} or {@link TextureView}; contents in overlays for these 17493 * types of views may not display correctly.</p> 17494 * 17495 * @return The ViewOverlay object for this view. 17496 * @see ViewOverlay 17497 */ 17498 public ViewOverlay getOverlay() { 17499 if (mOverlay == null) { 17500 mOverlay = new ViewOverlay(mContext, this); 17501 } 17502 return mOverlay; 17503 } 17504 17505 /** 17506 * Override this if your view is known to always be drawn on top of a solid color background, 17507 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17508 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17509 * should be set to 0xFF. 17510 * 17511 * @see #setVerticalFadingEdgeEnabled(boolean) 17512 * @see #setHorizontalFadingEdgeEnabled(boolean) 17513 * 17514 * @return The known solid color background for this view, or 0 if the color may vary 17515 */ 17516 @ViewDebug.ExportedProperty(category = "drawing") 17517 @ColorInt 17518 public int getSolidColor() { 17519 return 0; 17520 } 17521 17522 /** 17523 * Build a human readable string representation of the specified view flags. 17524 * 17525 * @param flags the view flags to convert to a string 17526 * @return a String representing the supplied flags 17527 */ 17528 private static String printFlags(int flags) { 17529 String output = ""; 17530 int numFlags = 0; 17531 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17532 output += "TAKES_FOCUS"; 17533 numFlags++; 17534 } 17535 17536 switch (flags & VISIBILITY_MASK) { 17537 case INVISIBLE: 17538 if (numFlags > 0) { 17539 output += " "; 17540 } 17541 output += "INVISIBLE"; 17542 // USELESS HERE numFlags++; 17543 break; 17544 case GONE: 17545 if (numFlags > 0) { 17546 output += " "; 17547 } 17548 output += "GONE"; 17549 // USELESS HERE numFlags++; 17550 break; 17551 default: 17552 break; 17553 } 17554 return output; 17555 } 17556 17557 /** 17558 * Build a human readable string representation of the specified private 17559 * view flags. 17560 * 17561 * @param privateFlags the private view flags to convert to a string 17562 * @return a String representing the supplied flags 17563 */ 17564 private static String printPrivateFlags(int privateFlags) { 17565 String output = ""; 17566 int numFlags = 0; 17567 17568 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17569 output += "WANTS_FOCUS"; 17570 numFlags++; 17571 } 17572 17573 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17574 if (numFlags > 0) { 17575 output += " "; 17576 } 17577 output += "FOCUSED"; 17578 numFlags++; 17579 } 17580 17581 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17582 if (numFlags > 0) { 17583 output += " "; 17584 } 17585 output += "SELECTED"; 17586 numFlags++; 17587 } 17588 17589 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17590 if (numFlags > 0) { 17591 output += " "; 17592 } 17593 output += "IS_ROOT_NAMESPACE"; 17594 numFlags++; 17595 } 17596 17597 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17598 if (numFlags > 0) { 17599 output += " "; 17600 } 17601 output += "HAS_BOUNDS"; 17602 numFlags++; 17603 } 17604 17605 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17606 if (numFlags > 0) { 17607 output += " "; 17608 } 17609 output += "DRAWN"; 17610 // USELESS HERE numFlags++; 17611 } 17612 return output; 17613 } 17614 17615 /** 17616 * <p>Indicates whether or not this view's layout will be requested during 17617 * the next hierarchy layout pass.</p> 17618 * 17619 * @return true if the layout will be forced during next layout pass 17620 */ 17621 public boolean isLayoutRequested() { 17622 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17623 } 17624 17625 /** 17626 * Return true if o is a ViewGroup that is laying out using optical bounds. 17627 * @hide 17628 */ 17629 public static boolean isLayoutModeOptical(Object o) { 17630 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17631 } 17632 17633 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17634 Insets parentInsets = mParent instanceof View ? 17635 ((View) mParent).getOpticalInsets() : Insets.NONE; 17636 Insets childInsets = getOpticalInsets(); 17637 return setFrame( 17638 left + parentInsets.left - childInsets.left, 17639 top + parentInsets.top - childInsets.top, 17640 right + parentInsets.left + childInsets.right, 17641 bottom + parentInsets.top + childInsets.bottom); 17642 } 17643 17644 /** 17645 * Assign a size and position to a view and all of its 17646 * descendants 17647 * 17648 * <p>This is the second phase of the layout mechanism. 17649 * (The first is measuring). In this phase, each parent calls 17650 * layout on all of its children to position them. 17651 * This is typically done using the child measurements 17652 * that were stored in the measure pass().</p> 17653 * 17654 * <p>Derived classes should not override this method. 17655 * Derived classes with children should override 17656 * onLayout. In that method, they should 17657 * call layout on each of their children.</p> 17658 * 17659 * @param l Left position, relative to parent 17660 * @param t Top position, relative to parent 17661 * @param r Right position, relative to parent 17662 * @param b Bottom position, relative to parent 17663 */ 17664 @SuppressWarnings({"unchecked"}) 17665 public void layout(int l, int t, int r, int b) { 17666 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17667 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17668 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17669 } 17670 17671 int oldL = mLeft; 17672 int oldT = mTop; 17673 int oldB = mBottom; 17674 int oldR = mRight; 17675 17676 boolean changed = isLayoutModeOptical(mParent) ? 17677 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17678 17679 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17680 onLayout(changed, l, t, r, b); 17681 17682 if (shouldDrawRoundScrollbar()) { 17683 if(mRoundScrollbarRenderer == null) { 17684 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 17685 } 17686 } else { 17687 mRoundScrollbarRenderer = null; 17688 } 17689 17690 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17691 17692 ListenerInfo li = mListenerInfo; 17693 if (li != null && li.mOnLayoutChangeListeners != null) { 17694 ArrayList<OnLayoutChangeListener> listenersCopy = 17695 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17696 int numListeners = listenersCopy.size(); 17697 for (int i = 0; i < numListeners; ++i) { 17698 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17699 } 17700 } 17701 } 17702 17703 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17704 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17705 } 17706 17707 /** 17708 * Called from layout when this view should 17709 * assign a size and position to each of its children. 17710 * 17711 * Derived classes with children should override 17712 * this method and call layout on each of 17713 * their children. 17714 * @param changed This is a new size or position for this view 17715 * @param left Left position, relative to parent 17716 * @param top Top position, relative to parent 17717 * @param right Right position, relative to parent 17718 * @param bottom Bottom position, relative to parent 17719 */ 17720 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17721 } 17722 17723 /** 17724 * Assign a size and position to this view. 17725 * 17726 * This is called from layout. 17727 * 17728 * @param left Left position, relative to parent 17729 * @param top Top position, relative to parent 17730 * @param right Right position, relative to parent 17731 * @param bottom Bottom position, relative to parent 17732 * @return true if the new size and position are different than the 17733 * previous ones 17734 * {@hide} 17735 */ 17736 protected boolean setFrame(int left, int top, int right, int bottom) { 17737 boolean changed = false; 17738 17739 if (DBG) { 17740 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17741 + right + "," + bottom + ")"); 17742 } 17743 17744 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17745 changed = true; 17746 17747 // Remember our drawn bit 17748 int drawn = mPrivateFlags & PFLAG_DRAWN; 17749 17750 int oldWidth = mRight - mLeft; 17751 int oldHeight = mBottom - mTop; 17752 int newWidth = right - left; 17753 int newHeight = bottom - top; 17754 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17755 17756 // Invalidate our old position 17757 invalidate(sizeChanged); 17758 17759 mLeft = left; 17760 mTop = top; 17761 mRight = right; 17762 mBottom = bottom; 17763 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17764 17765 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17766 17767 17768 if (sizeChanged) { 17769 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17770 } 17771 17772 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17773 // If we are visible, force the DRAWN bit to on so that 17774 // this invalidate will go through (at least to our parent). 17775 // This is because someone may have invalidated this view 17776 // before this call to setFrame came in, thereby clearing 17777 // the DRAWN bit. 17778 mPrivateFlags |= PFLAG_DRAWN; 17779 invalidate(sizeChanged); 17780 // parent display list may need to be recreated based on a change in the bounds 17781 // of any child 17782 invalidateParentCaches(); 17783 } 17784 17785 // Reset drawn bit to original value (invalidate turns it off) 17786 mPrivateFlags |= drawn; 17787 17788 mBackgroundSizeChanged = true; 17789 if (mForegroundInfo != null) { 17790 mForegroundInfo.mBoundsChanged = true; 17791 } 17792 17793 notifySubtreeAccessibilityStateChangedIfNeeded(); 17794 } 17795 return changed; 17796 } 17797 17798 /** 17799 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17800 * @hide 17801 */ 17802 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17803 setFrame(left, top, right, bottom); 17804 } 17805 17806 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17807 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17808 if (mOverlay != null) { 17809 mOverlay.getOverlayView().setRight(newWidth); 17810 mOverlay.getOverlayView().setBottom(newHeight); 17811 } 17812 rebuildOutline(); 17813 } 17814 17815 /** 17816 * Finalize inflating a view from XML. This is called as the last phase 17817 * of inflation, after all child views have been added. 17818 * 17819 * <p>Even if the subclass overrides onFinishInflate, they should always be 17820 * sure to call the super method, so that we get called. 17821 */ 17822 @CallSuper 17823 protected void onFinishInflate() { 17824 } 17825 17826 /** 17827 * Returns the resources associated with this view. 17828 * 17829 * @return Resources object. 17830 */ 17831 public Resources getResources() { 17832 return mResources; 17833 } 17834 17835 /** 17836 * Invalidates the specified Drawable. 17837 * 17838 * @param drawable the drawable to invalidate 17839 */ 17840 @Override 17841 public void invalidateDrawable(@NonNull Drawable drawable) { 17842 if (verifyDrawable(drawable)) { 17843 final Rect dirty = drawable.getDirtyBounds(); 17844 final int scrollX = mScrollX; 17845 final int scrollY = mScrollY; 17846 17847 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17848 dirty.right + scrollX, dirty.bottom + scrollY); 17849 rebuildOutline(); 17850 } 17851 } 17852 17853 /** 17854 * Schedules an action on a drawable to occur at a specified time. 17855 * 17856 * @param who the recipient of the action 17857 * @param what the action to run on the drawable 17858 * @param when the time at which the action must occur. Uses the 17859 * {@link SystemClock#uptimeMillis} timebase. 17860 */ 17861 @Override 17862 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17863 if (verifyDrawable(who) && what != null) { 17864 final long delay = when - SystemClock.uptimeMillis(); 17865 if (mAttachInfo != null) { 17866 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17867 Choreographer.CALLBACK_ANIMATION, what, who, 17868 Choreographer.subtractFrameDelay(delay)); 17869 } else { 17870 // Postpone the runnable until we know 17871 // on which thread it needs to run. 17872 getRunQueue().postDelayed(what, delay); 17873 } 17874 } 17875 } 17876 17877 /** 17878 * Cancels a scheduled action on a drawable. 17879 * 17880 * @param who the recipient of the action 17881 * @param what the action to cancel 17882 */ 17883 @Override 17884 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17885 if (verifyDrawable(who) && what != null) { 17886 if (mAttachInfo != null) { 17887 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17888 Choreographer.CALLBACK_ANIMATION, what, who); 17889 } 17890 getRunQueue().removeCallbacks(what); 17891 } 17892 } 17893 17894 /** 17895 * Unschedule any events associated with the given Drawable. This can be 17896 * used when selecting a new Drawable into a view, so that the previous 17897 * one is completely unscheduled. 17898 * 17899 * @param who The Drawable to unschedule. 17900 * 17901 * @see #drawableStateChanged 17902 */ 17903 public void unscheduleDrawable(Drawable who) { 17904 if (mAttachInfo != null && who != null) { 17905 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17906 Choreographer.CALLBACK_ANIMATION, null, who); 17907 } 17908 } 17909 17910 /** 17911 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17912 * that the View directionality can and will be resolved before its Drawables. 17913 * 17914 * Will call {@link View#onResolveDrawables} when resolution is done. 17915 * 17916 * @hide 17917 */ 17918 protected void resolveDrawables() { 17919 // Drawables resolution may need to happen before resolving the layout direction (which is 17920 // done only during the measure() call). 17921 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17922 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17923 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17924 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17925 // direction to be resolved as its resolved value will be the same as its raw value. 17926 if (!isLayoutDirectionResolved() && 17927 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17928 return; 17929 } 17930 17931 final int layoutDirection = isLayoutDirectionResolved() ? 17932 getLayoutDirection() : getRawLayoutDirection(); 17933 17934 if (mBackground != null) { 17935 mBackground.setLayoutDirection(layoutDirection); 17936 } 17937 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17938 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17939 } 17940 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17941 onResolveDrawables(layoutDirection); 17942 } 17943 17944 boolean areDrawablesResolved() { 17945 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17946 } 17947 17948 /** 17949 * Called when layout direction has been resolved. 17950 * 17951 * The default implementation does nothing. 17952 * 17953 * @param layoutDirection The resolved layout direction. 17954 * 17955 * @see #LAYOUT_DIRECTION_LTR 17956 * @see #LAYOUT_DIRECTION_RTL 17957 * 17958 * @hide 17959 */ 17960 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17961 } 17962 17963 /** 17964 * @hide 17965 */ 17966 protected void resetResolvedDrawables() { 17967 resetResolvedDrawablesInternal(); 17968 } 17969 17970 void resetResolvedDrawablesInternal() { 17971 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17972 } 17973 17974 /** 17975 * If your view subclass is displaying its own Drawable objects, it should 17976 * override this function and return true for any Drawable it is 17977 * displaying. This allows animations for those drawables to be 17978 * scheduled. 17979 * 17980 * <p>Be sure to call through to the super class when overriding this 17981 * function. 17982 * 17983 * @param who The Drawable to verify. Return true if it is one you are 17984 * displaying, else return the result of calling through to the 17985 * super class. 17986 * 17987 * @return boolean If true than the Drawable is being displayed in the 17988 * view; else false and it is not allowed to animate. 17989 * 17990 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17991 * @see #drawableStateChanged() 17992 */ 17993 @CallSuper 17994 protected boolean verifyDrawable(@NonNull Drawable who) { 17995 // Avoid verifying the scroll bar drawable so that we don't end up in 17996 // an invalidation loop. This effectively prevents the scroll bar 17997 // drawable from triggering invalidations and scheduling runnables. 17998 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17999 } 18000 18001 /** 18002 * This function is called whenever the state of the view changes in such 18003 * a way that it impacts the state of drawables being shown. 18004 * <p> 18005 * If the View has a StateListAnimator, it will also be called to run necessary state 18006 * change animations. 18007 * <p> 18008 * Be sure to call through to the superclass when overriding this function. 18009 * 18010 * @see Drawable#setState(int[]) 18011 */ 18012 @CallSuper 18013 protected void drawableStateChanged() { 18014 final int[] state = getDrawableState(); 18015 boolean changed = false; 18016 18017 final Drawable bg = mBackground; 18018 if (bg != null && bg.isStateful()) { 18019 changed |= bg.setState(state); 18020 } 18021 18022 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18023 if (fg != null && fg.isStateful()) { 18024 changed |= fg.setState(state); 18025 } 18026 18027 if (mScrollCache != null) { 18028 final Drawable scrollBar = mScrollCache.scrollBar; 18029 if (scrollBar != null && scrollBar.isStateful()) { 18030 changed |= scrollBar.setState(state) 18031 && mScrollCache.state != ScrollabilityCache.OFF; 18032 } 18033 } 18034 18035 if (mStateListAnimator != null) { 18036 mStateListAnimator.setState(state); 18037 } 18038 18039 if (changed) { 18040 invalidate(); 18041 } 18042 } 18043 18044 /** 18045 * This function is called whenever the view hotspot changes and needs to 18046 * be propagated to drawables or child views managed by the view. 18047 * <p> 18048 * Dispatching to child views is handled by 18049 * {@link #dispatchDrawableHotspotChanged(float, float)}. 18050 * <p> 18051 * Be sure to call through to the superclass when overriding this function. 18052 * 18053 * @param x hotspot x coordinate 18054 * @param y hotspot y coordinate 18055 */ 18056 @CallSuper 18057 public void drawableHotspotChanged(float x, float y) { 18058 if (mBackground != null) { 18059 mBackground.setHotspot(x, y); 18060 } 18061 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18062 mForegroundInfo.mDrawable.setHotspot(x, y); 18063 } 18064 18065 dispatchDrawableHotspotChanged(x, y); 18066 } 18067 18068 /** 18069 * Dispatches drawableHotspotChanged to all of this View's children. 18070 * 18071 * @param x hotspot x coordinate 18072 * @param y hotspot y coordinate 18073 * @see #drawableHotspotChanged(float, float) 18074 */ 18075 public void dispatchDrawableHotspotChanged(float x, float y) { 18076 } 18077 18078 /** 18079 * Call this to force a view to update its drawable state. This will cause 18080 * drawableStateChanged to be called on this view. Views that are interested 18081 * in the new state should call getDrawableState. 18082 * 18083 * @see #drawableStateChanged 18084 * @see #getDrawableState 18085 */ 18086 public void refreshDrawableState() { 18087 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 18088 drawableStateChanged(); 18089 18090 ViewParent parent = mParent; 18091 if (parent != null) { 18092 parent.childDrawableStateChanged(this); 18093 } 18094 } 18095 18096 /** 18097 * Return an array of resource IDs of the drawable states representing the 18098 * current state of the view. 18099 * 18100 * @return The current drawable state 18101 * 18102 * @see Drawable#setState(int[]) 18103 * @see #drawableStateChanged() 18104 * @see #onCreateDrawableState(int) 18105 */ 18106 public final int[] getDrawableState() { 18107 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 18108 return mDrawableState; 18109 } else { 18110 mDrawableState = onCreateDrawableState(0); 18111 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 18112 return mDrawableState; 18113 } 18114 } 18115 18116 /** 18117 * Generate the new {@link android.graphics.drawable.Drawable} state for 18118 * this view. This is called by the view 18119 * system when the cached Drawable state is determined to be invalid. To 18120 * retrieve the current state, you should use {@link #getDrawableState}. 18121 * 18122 * @param extraSpace if non-zero, this is the number of extra entries you 18123 * would like in the returned array in which you can place your own 18124 * states. 18125 * 18126 * @return Returns an array holding the current {@link Drawable} state of 18127 * the view. 18128 * 18129 * @see #mergeDrawableStates(int[], int[]) 18130 */ 18131 protected int[] onCreateDrawableState(int extraSpace) { 18132 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 18133 mParent instanceof View) { 18134 return ((View) mParent).onCreateDrawableState(extraSpace); 18135 } 18136 18137 int[] drawableState; 18138 18139 int privateFlags = mPrivateFlags; 18140 18141 int viewStateIndex = 0; 18142 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 18143 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 18144 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 18145 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 18146 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 18147 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 18148 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 18149 ThreadedRenderer.isAvailable()) { 18150 // This is set if HW acceleration is requested, even if the current 18151 // process doesn't allow it. This is just to allow app preview 18152 // windows to better match their app. 18153 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 18154 } 18155 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 18156 18157 final int privateFlags2 = mPrivateFlags2; 18158 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 18159 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 18160 } 18161 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 18162 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 18163 } 18164 18165 drawableState = StateSet.get(viewStateIndex); 18166 18167 //noinspection ConstantIfStatement 18168 if (false) { 18169 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18170 Log.i("View", toString() 18171 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18172 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18173 + " fo=" + hasFocus() 18174 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18175 + " wf=" + hasWindowFocus() 18176 + ": " + Arrays.toString(drawableState)); 18177 } 18178 18179 if (extraSpace == 0) { 18180 return drawableState; 18181 } 18182 18183 final int[] fullState; 18184 if (drawableState != null) { 18185 fullState = new int[drawableState.length + extraSpace]; 18186 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18187 } else { 18188 fullState = new int[extraSpace]; 18189 } 18190 18191 return fullState; 18192 } 18193 18194 /** 18195 * Merge your own state values in <var>additionalState</var> into the base 18196 * state values <var>baseState</var> that were returned by 18197 * {@link #onCreateDrawableState(int)}. 18198 * 18199 * @param baseState The base state values returned by 18200 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18201 * own additional state values. 18202 * 18203 * @param additionalState The additional state values you would like 18204 * added to <var>baseState</var>; this array is not modified. 18205 * 18206 * @return As a convenience, the <var>baseState</var> array you originally 18207 * passed into the function is returned. 18208 * 18209 * @see #onCreateDrawableState(int) 18210 */ 18211 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18212 final int N = baseState.length; 18213 int i = N - 1; 18214 while (i >= 0 && baseState[i] == 0) { 18215 i--; 18216 } 18217 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18218 return baseState; 18219 } 18220 18221 /** 18222 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18223 * on all Drawable objects associated with this view. 18224 * <p> 18225 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18226 * attached to this view. 18227 */ 18228 @CallSuper 18229 public void jumpDrawablesToCurrentState() { 18230 if (mBackground != null) { 18231 mBackground.jumpToCurrentState(); 18232 } 18233 if (mStateListAnimator != null) { 18234 mStateListAnimator.jumpToCurrentState(); 18235 } 18236 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18237 mForegroundInfo.mDrawable.jumpToCurrentState(); 18238 } 18239 } 18240 18241 /** 18242 * Sets the background color for this view. 18243 * @param color the color of the background 18244 */ 18245 @RemotableViewMethod 18246 public void setBackgroundColor(@ColorInt int color) { 18247 if (mBackground instanceof ColorDrawable) { 18248 ((ColorDrawable) mBackground.mutate()).setColor(color); 18249 computeOpaqueFlags(); 18250 mBackgroundResource = 0; 18251 } else { 18252 setBackground(new ColorDrawable(color)); 18253 } 18254 } 18255 18256 /** 18257 * Set the background to a given resource. The resource should refer to 18258 * a Drawable object or 0 to remove the background. 18259 * @param resid The identifier of the resource. 18260 * 18261 * @attr ref android.R.styleable#View_background 18262 */ 18263 @RemotableViewMethod 18264 public void setBackgroundResource(@DrawableRes int resid) { 18265 if (resid != 0 && resid == mBackgroundResource) { 18266 return; 18267 } 18268 18269 Drawable d = null; 18270 if (resid != 0) { 18271 d = mContext.getDrawable(resid); 18272 } 18273 setBackground(d); 18274 18275 mBackgroundResource = resid; 18276 } 18277 18278 /** 18279 * Set the background to a given Drawable, or remove the background. If the 18280 * background has padding, this View's padding is set to the background's 18281 * padding. However, when a background is removed, this View's padding isn't 18282 * touched. If setting the padding is desired, please use 18283 * {@link #setPadding(int, int, int, int)}. 18284 * 18285 * @param background The Drawable to use as the background, or null to remove the 18286 * background 18287 */ 18288 public void setBackground(Drawable background) { 18289 //noinspection deprecation 18290 setBackgroundDrawable(background); 18291 } 18292 18293 /** 18294 * @deprecated use {@link #setBackground(Drawable)} instead 18295 */ 18296 @Deprecated 18297 public void setBackgroundDrawable(Drawable background) { 18298 computeOpaqueFlags(); 18299 18300 if (background == mBackground) { 18301 return; 18302 } 18303 18304 boolean requestLayout = false; 18305 18306 mBackgroundResource = 0; 18307 18308 /* 18309 * Regardless of whether we're setting a new background or not, we want 18310 * to clear the previous drawable. setVisible first while we still have the callback set. 18311 */ 18312 if (mBackground != null) { 18313 if (isAttachedToWindow()) { 18314 mBackground.setVisible(false, false); 18315 } 18316 mBackground.setCallback(null); 18317 unscheduleDrawable(mBackground); 18318 } 18319 18320 if (background != null) { 18321 Rect padding = sThreadLocal.get(); 18322 if (padding == null) { 18323 padding = new Rect(); 18324 sThreadLocal.set(padding); 18325 } 18326 resetResolvedDrawablesInternal(); 18327 background.setLayoutDirection(getLayoutDirection()); 18328 if (background.getPadding(padding)) { 18329 resetResolvedPaddingInternal(); 18330 switch (background.getLayoutDirection()) { 18331 case LAYOUT_DIRECTION_RTL: 18332 mUserPaddingLeftInitial = padding.right; 18333 mUserPaddingRightInitial = padding.left; 18334 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18335 break; 18336 case LAYOUT_DIRECTION_LTR: 18337 default: 18338 mUserPaddingLeftInitial = padding.left; 18339 mUserPaddingRightInitial = padding.right; 18340 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18341 } 18342 mLeftPaddingDefined = false; 18343 mRightPaddingDefined = false; 18344 } 18345 18346 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18347 // if it has a different minimum size, we should layout again 18348 if (mBackground == null 18349 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18350 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18351 requestLayout = true; 18352 } 18353 18354 // Set mBackground before we set this as the callback and start making other 18355 // background drawable state change calls. In particular, the setVisible call below 18356 // can result in drawables attempting to start animations or otherwise invalidate, 18357 // which requires the view set as the callback (us) to recognize the drawable as 18358 // belonging to it as per verifyDrawable. 18359 mBackground = background; 18360 if (background.isStateful()) { 18361 background.setState(getDrawableState()); 18362 } 18363 if (isAttachedToWindow()) { 18364 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18365 } 18366 18367 applyBackgroundTint(); 18368 18369 // Set callback last, since the view may still be initializing. 18370 background.setCallback(this); 18371 18372 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18373 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18374 requestLayout = true; 18375 } 18376 } else { 18377 /* Remove the background */ 18378 mBackground = null; 18379 if ((mViewFlags & WILL_NOT_DRAW) != 0 18380 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18381 mPrivateFlags |= PFLAG_SKIP_DRAW; 18382 } 18383 18384 /* 18385 * When the background is set, we try to apply its padding to this 18386 * View. When the background is removed, we don't touch this View's 18387 * padding. This is noted in the Javadocs. Hence, we don't need to 18388 * requestLayout(), the invalidate() below is sufficient. 18389 */ 18390 18391 // The old background's minimum size could have affected this 18392 // View's layout, so let's requestLayout 18393 requestLayout = true; 18394 } 18395 18396 computeOpaqueFlags(); 18397 18398 if (requestLayout) { 18399 requestLayout(); 18400 } 18401 18402 mBackgroundSizeChanged = true; 18403 invalidate(true); 18404 invalidateOutline(); 18405 } 18406 18407 /** 18408 * Gets the background drawable 18409 * 18410 * @return The drawable used as the background for this view, if any. 18411 * 18412 * @see #setBackground(Drawable) 18413 * 18414 * @attr ref android.R.styleable#View_background 18415 */ 18416 public Drawable getBackground() { 18417 return mBackground; 18418 } 18419 18420 /** 18421 * Applies a tint to the background drawable. Does not modify the current tint 18422 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18423 * <p> 18424 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18425 * mutate the drawable and apply the specified tint and tint mode using 18426 * {@link Drawable#setTintList(ColorStateList)}. 18427 * 18428 * @param tint the tint to apply, may be {@code null} to clear tint 18429 * 18430 * @attr ref android.R.styleable#View_backgroundTint 18431 * @see #getBackgroundTintList() 18432 * @see Drawable#setTintList(ColorStateList) 18433 */ 18434 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18435 if (mBackgroundTint == null) { 18436 mBackgroundTint = new TintInfo(); 18437 } 18438 mBackgroundTint.mTintList = tint; 18439 mBackgroundTint.mHasTintList = true; 18440 18441 applyBackgroundTint(); 18442 } 18443 18444 /** 18445 * Return the tint applied to the background drawable, if specified. 18446 * 18447 * @return the tint applied to the background drawable 18448 * @attr ref android.R.styleable#View_backgroundTint 18449 * @see #setBackgroundTintList(ColorStateList) 18450 */ 18451 @Nullable 18452 public ColorStateList getBackgroundTintList() { 18453 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18454 } 18455 18456 /** 18457 * Specifies the blending mode used to apply the tint specified by 18458 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18459 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18460 * 18461 * @param tintMode the blending mode used to apply the tint, may be 18462 * {@code null} to clear tint 18463 * @attr ref android.R.styleable#View_backgroundTintMode 18464 * @see #getBackgroundTintMode() 18465 * @see Drawable#setTintMode(PorterDuff.Mode) 18466 */ 18467 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18468 if (mBackgroundTint == null) { 18469 mBackgroundTint = new TintInfo(); 18470 } 18471 mBackgroundTint.mTintMode = tintMode; 18472 mBackgroundTint.mHasTintMode = true; 18473 18474 applyBackgroundTint(); 18475 } 18476 18477 /** 18478 * Return the blending mode used to apply the tint to the background 18479 * drawable, if specified. 18480 * 18481 * @return the blending mode used to apply the tint to the background 18482 * drawable 18483 * @attr ref android.R.styleable#View_backgroundTintMode 18484 * @see #setBackgroundTintMode(PorterDuff.Mode) 18485 */ 18486 @Nullable 18487 public PorterDuff.Mode getBackgroundTintMode() { 18488 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18489 } 18490 18491 private void applyBackgroundTint() { 18492 if (mBackground != null && mBackgroundTint != null) { 18493 final TintInfo tintInfo = mBackgroundTint; 18494 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18495 mBackground = mBackground.mutate(); 18496 18497 if (tintInfo.mHasTintList) { 18498 mBackground.setTintList(tintInfo.mTintList); 18499 } 18500 18501 if (tintInfo.mHasTintMode) { 18502 mBackground.setTintMode(tintInfo.mTintMode); 18503 } 18504 18505 // The drawable (or one of its children) may not have been 18506 // stateful before applying the tint, so let's try again. 18507 if (mBackground.isStateful()) { 18508 mBackground.setState(getDrawableState()); 18509 } 18510 } 18511 } 18512 } 18513 18514 /** 18515 * Returns the drawable used as the foreground of this View. The 18516 * foreground drawable, if non-null, is always drawn on top of the view's content. 18517 * 18518 * @return a Drawable or null if no foreground was set 18519 * 18520 * @see #onDrawForeground(Canvas) 18521 */ 18522 public Drawable getForeground() { 18523 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18524 } 18525 18526 /** 18527 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18528 * 18529 * @param foreground the Drawable to be drawn on top of the children 18530 * 18531 * @attr ref android.R.styleable#View_foreground 18532 */ 18533 public void setForeground(Drawable foreground) { 18534 if (mForegroundInfo == null) { 18535 if (foreground == null) { 18536 // Nothing to do. 18537 return; 18538 } 18539 mForegroundInfo = new ForegroundInfo(); 18540 } 18541 18542 if (foreground == mForegroundInfo.mDrawable) { 18543 // Nothing to do 18544 return; 18545 } 18546 18547 if (mForegroundInfo.mDrawable != null) { 18548 if (isAttachedToWindow()) { 18549 mForegroundInfo.mDrawable.setVisible(false, false); 18550 } 18551 mForegroundInfo.mDrawable.setCallback(null); 18552 unscheduleDrawable(mForegroundInfo.mDrawable); 18553 } 18554 18555 mForegroundInfo.mDrawable = foreground; 18556 mForegroundInfo.mBoundsChanged = true; 18557 if (foreground != null) { 18558 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18559 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18560 } 18561 foreground.setLayoutDirection(getLayoutDirection()); 18562 if (foreground.isStateful()) { 18563 foreground.setState(getDrawableState()); 18564 } 18565 applyForegroundTint(); 18566 if (isAttachedToWindow()) { 18567 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18568 } 18569 // Set callback last, since the view may still be initializing. 18570 foreground.setCallback(this); 18571 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18572 mPrivateFlags |= PFLAG_SKIP_DRAW; 18573 } 18574 requestLayout(); 18575 invalidate(); 18576 } 18577 18578 /** 18579 * Magic bit used to support features of framework-internal window decor implementation details. 18580 * This used to live exclusively in FrameLayout. 18581 * 18582 * @return true if the foreground should draw inside the padding region or false 18583 * if it should draw inset by the view's padding 18584 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18585 */ 18586 public boolean isForegroundInsidePadding() { 18587 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18588 } 18589 18590 /** 18591 * Describes how the foreground is positioned. 18592 * 18593 * @return foreground gravity. 18594 * 18595 * @see #setForegroundGravity(int) 18596 * 18597 * @attr ref android.R.styleable#View_foregroundGravity 18598 */ 18599 public int getForegroundGravity() { 18600 return mForegroundInfo != null ? mForegroundInfo.mGravity 18601 : Gravity.START | Gravity.TOP; 18602 } 18603 18604 /** 18605 * Describes how the foreground is positioned. Defaults to START and TOP. 18606 * 18607 * @param gravity see {@link android.view.Gravity} 18608 * 18609 * @see #getForegroundGravity() 18610 * 18611 * @attr ref android.R.styleable#View_foregroundGravity 18612 */ 18613 public void setForegroundGravity(int gravity) { 18614 if (mForegroundInfo == null) { 18615 mForegroundInfo = new ForegroundInfo(); 18616 } 18617 18618 if (mForegroundInfo.mGravity != gravity) { 18619 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18620 gravity |= Gravity.START; 18621 } 18622 18623 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18624 gravity |= Gravity.TOP; 18625 } 18626 18627 mForegroundInfo.mGravity = gravity; 18628 requestLayout(); 18629 } 18630 } 18631 18632 /** 18633 * Applies a tint to the foreground drawable. Does not modify the current tint 18634 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18635 * <p> 18636 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18637 * mutate the drawable and apply the specified tint and tint mode using 18638 * {@link Drawable#setTintList(ColorStateList)}. 18639 * 18640 * @param tint the tint to apply, may be {@code null} to clear tint 18641 * 18642 * @attr ref android.R.styleable#View_foregroundTint 18643 * @see #getForegroundTintList() 18644 * @see Drawable#setTintList(ColorStateList) 18645 */ 18646 public void setForegroundTintList(@Nullable ColorStateList tint) { 18647 if (mForegroundInfo == null) { 18648 mForegroundInfo = new ForegroundInfo(); 18649 } 18650 if (mForegroundInfo.mTintInfo == null) { 18651 mForegroundInfo.mTintInfo = new TintInfo(); 18652 } 18653 mForegroundInfo.mTintInfo.mTintList = tint; 18654 mForegroundInfo.mTintInfo.mHasTintList = true; 18655 18656 applyForegroundTint(); 18657 } 18658 18659 /** 18660 * Return the tint applied to the foreground drawable, if specified. 18661 * 18662 * @return the tint applied to the foreground drawable 18663 * @attr ref android.R.styleable#View_foregroundTint 18664 * @see #setForegroundTintList(ColorStateList) 18665 */ 18666 @Nullable 18667 public ColorStateList getForegroundTintList() { 18668 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18669 ? mForegroundInfo.mTintInfo.mTintList : null; 18670 } 18671 18672 /** 18673 * Specifies the blending mode used to apply the tint specified by 18674 * {@link #setForegroundTintList(ColorStateList)}} to the background 18675 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18676 * 18677 * @param tintMode the blending mode used to apply the tint, may be 18678 * {@code null} to clear tint 18679 * @attr ref android.R.styleable#View_foregroundTintMode 18680 * @see #getForegroundTintMode() 18681 * @see Drawable#setTintMode(PorterDuff.Mode) 18682 */ 18683 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18684 if (mForegroundInfo == null) { 18685 mForegroundInfo = new ForegroundInfo(); 18686 } 18687 if (mForegroundInfo.mTintInfo == null) { 18688 mForegroundInfo.mTintInfo = new TintInfo(); 18689 } 18690 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18691 mForegroundInfo.mTintInfo.mHasTintMode = true; 18692 18693 applyForegroundTint(); 18694 } 18695 18696 /** 18697 * Return the blending mode used to apply the tint to the foreground 18698 * drawable, if specified. 18699 * 18700 * @return the blending mode used to apply the tint to the foreground 18701 * drawable 18702 * @attr ref android.R.styleable#View_foregroundTintMode 18703 * @see #setForegroundTintMode(PorterDuff.Mode) 18704 */ 18705 @Nullable 18706 public PorterDuff.Mode getForegroundTintMode() { 18707 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18708 ? mForegroundInfo.mTintInfo.mTintMode : null; 18709 } 18710 18711 private void applyForegroundTint() { 18712 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18713 && mForegroundInfo.mTintInfo != null) { 18714 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18715 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18716 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18717 18718 if (tintInfo.mHasTintList) { 18719 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18720 } 18721 18722 if (tintInfo.mHasTintMode) { 18723 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18724 } 18725 18726 // The drawable (or one of its children) may not have been 18727 // stateful before applying the tint, so let's try again. 18728 if (mForegroundInfo.mDrawable.isStateful()) { 18729 mForegroundInfo.mDrawable.setState(getDrawableState()); 18730 } 18731 } 18732 } 18733 } 18734 18735 /** 18736 * Draw any foreground content for this view. 18737 * 18738 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18739 * drawable or other view-specific decorations. The foreground is drawn on top of the 18740 * primary view content.</p> 18741 * 18742 * @param canvas canvas to draw into 18743 */ 18744 public void onDrawForeground(Canvas canvas) { 18745 onDrawScrollIndicators(canvas); 18746 onDrawScrollBars(canvas); 18747 18748 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18749 if (foreground != null) { 18750 if (mForegroundInfo.mBoundsChanged) { 18751 mForegroundInfo.mBoundsChanged = false; 18752 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18753 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18754 18755 if (mForegroundInfo.mInsidePadding) { 18756 selfBounds.set(0, 0, getWidth(), getHeight()); 18757 } else { 18758 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18759 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18760 } 18761 18762 final int ld = getLayoutDirection(); 18763 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18764 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18765 foreground.setBounds(overlayBounds); 18766 } 18767 18768 foreground.draw(canvas); 18769 } 18770 } 18771 18772 /** 18773 * Sets the padding. The view may add on the space required to display 18774 * the scrollbars, depending on the style and visibility of the scrollbars. 18775 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18776 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18777 * from the values set in this call. 18778 * 18779 * @attr ref android.R.styleable#View_padding 18780 * @attr ref android.R.styleable#View_paddingBottom 18781 * @attr ref android.R.styleable#View_paddingLeft 18782 * @attr ref android.R.styleable#View_paddingRight 18783 * @attr ref android.R.styleable#View_paddingTop 18784 * @param left the left padding in pixels 18785 * @param top the top padding in pixels 18786 * @param right the right padding in pixels 18787 * @param bottom the bottom padding in pixels 18788 */ 18789 public void setPadding(int left, int top, int right, int bottom) { 18790 resetResolvedPaddingInternal(); 18791 18792 mUserPaddingStart = UNDEFINED_PADDING; 18793 mUserPaddingEnd = UNDEFINED_PADDING; 18794 18795 mUserPaddingLeftInitial = left; 18796 mUserPaddingRightInitial = right; 18797 18798 mLeftPaddingDefined = true; 18799 mRightPaddingDefined = true; 18800 18801 internalSetPadding(left, top, right, bottom); 18802 } 18803 18804 /** 18805 * @hide 18806 */ 18807 protected void internalSetPadding(int left, int top, int right, int bottom) { 18808 mUserPaddingLeft = left; 18809 mUserPaddingRight = right; 18810 mUserPaddingBottom = bottom; 18811 18812 final int viewFlags = mViewFlags; 18813 boolean changed = false; 18814 18815 // Common case is there are no scroll bars. 18816 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18817 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18818 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18819 ? 0 : getVerticalScrollbarWidth(); 18820 switch (mVerticalScrollbarPosition) { 18821 case SCROLLBAR_POSITION_DEFAULT: 18822 if (isLayoutRtl()) { 18823 left += offset; 18824 } else { 18825 right += offset; 18826 } 18827 break; 18828 case SCROLLBAR_POSITION_RIGHT: 18829 right += offset; 18830 break; 18831 case SCROLLBAR_POSITION_LEFT: 18832 left += offset; 18833 break; 18834 } 18835 } 18836 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18837 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18838 ? 0 : getHorizontalScrollbarHeight(); 18839 } 18840 } 18841 18842 if (mPaddingLeft != left) { 18843 changed = true; 18844 mPaddingLeft = left; 18845 } 18846 if (mPaddingTop != top) { 18847 changed = true; 18848 mPaddingTop = top; 18849 } 18850 if (mPaddingRight != right) { 18851 changed = true; 18852 mPaddingRight = right; 18853 } 18854 if (mPaddingBottom != bottom) { 18855 changed = true; 18856 mPaddingBottom = bottom; 18857 } 18858 18859 if (changed) { 18860 requestLayout(); 18861 invalidateOutline(); 18862 } 18863 } 18864 18865 /** 18866 * Sets the relative padding. The view may add on the space required to display 18867 * the scrollbars, depending on the style and visibility of the scrollbars. 18868 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18869 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18870 * from the values set in this call. 18871 * 18872 * @attr ref android.R.styleable#View_padding 18873 * @attr ref android.R.styleable#View_paddingBottom 18874 * @attr ref android.R.styleable#View_paddingStart 18875 * @attr ref android.R.styleable#View_paddingEnd 18876 * @attr ref android.R.styleable#View_paddingTop 18877 * @param start the start padding in pixels 18878 * @param top the top padding in pixels 18879 * @param end the end padding in pixels 18880 * @param bottom the bottom padding in pixels 18881 */ 18882 public void setPaddingRelative(int start, int top, int end, int bottom) { 18883 resetResolvedPaddingInternal(); 18884 18885 mUserPaddingStart = start; 18886 mUserPaddingEnd = end; 18887 mLeftPaddingDefined = true; 18888 mRightPaddingDefined = true; 18889 18890 switch(getLayoutDirection()) { 18891 case LAYOUT_DIRECTION_RTL: 18892 mUserPaddingLeftInitial = end; 18893 mUserPaddingRightInitial = start; 18894 internalSetPadding(end, top, start, bottom); 18895 break; 18896 case LAYOUT_DIRECTION_LTR: 18897 default: 18898 mUserPaddingLeftInitial = start; 18899 mUserPaddingRightInitial = end; 18900 internalSetPadding(start, top, end, bottom); 18901 } 18902 } 18903 18904 /** 18905 * Returns the top padding of this view. 18906 * 18907 * @return the top padding in pixels 18908 */ 18909 public int getPaddingTop() { 18910 return mPaddingTop; 18911 } 18912 18913 /** 18914 * Returns the bottom padding of this view. If there are inset and enabled 18915 * scrollbars, this value may include the space required to display the 18916 * scrollbars as well. 18917 * 18918 * @return the bottom padding in pixels 18919 */ 18920 public int getPaddingBottom() { 18921 return mPaddingBottom; 18922 } 18923 18924 /** 18925 * Returns the left padding of this view. If there are inset and enabled 18926 * scrollbars, this value may include the space required to display the 18927 * scrollbars as well. 18928 * 18929 * @return the left padding in pixels 18930 */ 18931 public int getPaddingLeft() { 18932 if (!isPaddingResolved()) { 18933 resolvePadding(); 18934 } 18935 return mPaddingLeft; 18936 } 18937 18938 /** 18939 * Returns the start padding of this view depending on its resolved layout direction. 18940 * If there are inset and enabled scrollbars, this value may include the space 18941 * required to display the scrollbars as well. 18942 * 18943 * @return the start padding in pixels 18944 */ 18945 public int getPaddingStart() { 18946 if (!isPaddingResolved()) { 18947 resolvePadding(); 18948 } 18949 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18950 mPaddingRight : mPaddingLeft; 18951 } 18952 18953 /** 18954 * Returns the right padding of this view. If there are inset and enabled 18955 * scrollbars, this value may include the space required to display the 18956 * scrollbars as well. 18957 * 18958 * @return the right padding in pixels 18959 */ 18960 public int getPaddingRight() { 18961 if (!isPaddingResolved()) { 18962 resolvePadding(); 18963 } 18964 return mPaddingRight; 18965 } 18966 18967 /** 18968 * Returns the end padding of this view depending on its resolved layout direction. 18969 * If there are inset and enabled scrollbars, this value may include the space 18970 * required to display the scrollbars as well. 18971 * 18972 * @return the end padding in pixels 18973 */ 18974 public int getPaddingEnd() { 18975 if (!isPaddingResolved()) { 18976 resolvePadding(); 18977 } 18978 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18979 mPaddingLeft : mPaddingRight; 18980 } 18981 18982 /** 18983 * Return if the padding has been set through relative values 18984 * {@link #setPaddingRelative(int, int, int, int)} or through 18985 * @attr ref android.R.styleable#View_paddingStart or 18986 * @attr ref android.R.styleable#View_paddingEnd 18987 * 18988 * @return true if the padding is relative or false if it is not. 18989 */ 18990 public boolean isPaddingRelative() { 18991 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18992 } 18993 18994 Insets computeOpticalInsets() { 18995 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18996 } 18997 18998 /** 18999 * @hide 19000 */ 19001 public void resetPaddingToInitialValues() { 19002 if (isRtlCompatibilityMode()) { 19003 mPaddingLeft = mUserPaddingLeftInitial; 19004 mPaddingRight = mUserPaddingRightInitial; 19005 return; 19006 } 19007 if (isLayoutRtl()) { 19008 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 19009 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 19010 } else { 19011 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 19012 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 19013 } 19014 } 19015 19016 /** 19017 * @hide 19018 */ 19019 public Insets getOpticalInsets() { 19020 if (mLayoutInsets == null) { 19021 mLayoutInsets = computeOpticalInsets(); 19022 } 19023 return mLayoutInsets; 19024 } 19025 19026 /** 19027 * Set this view's optical insets. 19028 * 19029 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 19030 * property. Views that compute their own optical insets should call it as part of measurement. 19031 * This method does not request layout. If you are setting optical insets outside of 19032 * measure/layout itself you will want to call requestLayout() yourself. 19033 * </p> 19034 * @hide 19035 */ 19036 public void setOpticalInsets(Insets insets) { 19037 mLayoutInsets = insets; 19038 } 19039 19040 /** 19041 * Changes the selection state of this view. A view can be selected or not. 19042 * Note that selection is not the same as focus. Views are typically 19043 * selected in the context of an AdapterView like ListView or GridView; 19044 * the selected view is the view that is highlighted. 19045 * 19046 * @param selected true if the view must be selected, false otherwise 19047 */ 19048 public void setSelected(boolean selected) { 19049 //noinspection DoubleNegation 19050 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 19051 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 19052 if (!selected) resetPressedState(); 19053 invalidate(true); 19054 refreshDrawableState(); 19055 dispatchSetSelected(selected); 19056 if (selected) { 19057 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 19058 } else { 19059 notifyViewAccessibilityStateChangedIfNeeded( 19060 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 19061 } 19062 } 19063 } 19064 19065 /** 19066 * Dispatch setSelected to all of this View's children. 19067 * 19068 * @see #setSelected(boolean) 19069 * 19070 * @param selected The new selected state 19071 */ 19072 protected void dispatchSetSelected(boolean selected) { 19073 } 19074 19075 /** 19076 * Indicates the selection state of this view. 19077 * 19078 * @return true if the view is selected, false otherwise 19079 */ 19080 @ViewDebug.ExportedProperty 19081 public boolean isSelected() { 19082 return (mPrivateFlags & PFLAG_SELECTED) != 0; 19083 } 19084 19085 /** 19086 * Changes the activated state of this view. A view can be activated or not. 19087 * Note that activation is not the same as selection. Selection is 19088 * a transient property, representing the view (hierarchy) the user is 19089 * currently interacting with. Activation is a longer-term state that the 19090 * user can move views in and out of. For example, in a list view with 19091 * single or multiple selection enabled, the views in the current selection 19092 * set are activated. (Um, yeah, we are deeply sorry about the terminology 19093 * here.) The activated state is propagated down to children of the view it 19094 * is set on. 19095 * 19096 * @param activated true if the view must be activated, false otherwise 19097 */ 19098 public void setActivated(boolean activated) { 19099 //noinspection DoubleNegation 19100 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 19101 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 19102 invalidate(true); 19103 refreshDrawableState(); 19104 dispatchSetActivated(activated); 19105 } 19106 } 19107 19108 /** 19109 * Dispatch setActivated to all of this View's children. 19110 * 19111 * @see #setActivated(boolean) 19112 * 19113 * @param activated The new activated state 19114 */ 19115 protected void dispatchSetActivated(boolean activated) { 19116 } 19117 19118 /** 19119 * Indicates the activation state of this view. 19120 * 19121 * @return true if the view is activated, false otherwise 19122 */ 19123 @ViewDebug.ExportedProperty 19124 public boolean isActivated() { 19125 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 19126 } 19127 19128 /** 19129 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 19130 * observer can be used to get notifications when global events, like 19131 * layout, happen. 19132 * 19133 * The returned ViewTreeObserver observer is not guaranteed to remain 19134 * valid for the lifetime of this View. If the caller of this method keeps 19135 * a long-lived reference to ViewTreeObserver, it should always check for 19136 * the return value of {@link ViewTreeObserver#isAlive()}. 19137 * 19138 * @return The ViewTreeObserver for this view's hierarchy. 19139 */ 19140 public ViewTreeObserver getViewTreeObserver() { 19141 if (mAttachInfo != null) { 19142 return mAttachInfo.mTreeObserver; 19143 } 19144 if (mFloatingTreeObserver == null) { 19145 mFloatingTreeObserver = new ViewTreeObserver(mContext); 19146 } 19147 return mFloatingTreeObserver; 19148 } 19149 19150 /** 19151 * <p>Finds the topmost view in the current view hierarchy.</p> 19152 * 19153 * @return the topmost view containing this view 19154 */ 19155 public View getRootView() { 19156 if (mAttachInfo != null) { 19157 final View v = mAttachInfo.mRootView; 19158 if (v != null) { 19159 return v; 19160 } 19161 } 19162 19163 View parent = this; 19164 19165 while (parent.mParent != null && parent.mParent instanceof View) { 19166 parent = (View) parent.mParent; 19167 } 19168 19169 return parent; 19170 } 19171 19172 /** 19173 * Transforms a motion event from view-local coordinates to on-screen 19174 * coordinates. 19175 * 19176 * @param ev the view-local motion event 19177 * @return false if the transformation could not be applied 19178 * @hide 19179 */ 19180 public boolean toGlobalMotionEvent(MotionEvent ev) { 19181 final AttachInfo info = mAttachInfo; 19182 if (info == null) { 19183 return false; 19184 } 19185 19186 final Matrix m = info.mTmpMatrix; 19187 m.set(Matrix.IDENTITY_MATRIX); 19188 transformMatrixToGlobal(m); 19189 ev.transform(m); 19190 return true; 19191 } 19192 19193 /** 19194 * Transforms a motion event from on-screen coordinates to view-local 19195 * coordinates. 19196 * 19197 * @param ev the on-screen motion event 19198 * @return false if the transformation could not be applied 19199 * @hide 19200 */ 19201 public boolean toLocalMotionEvent(MotionEvent ev) { 19202 final AttachInfo info = mAttachInfo; 19203 if (info == null) { 19204 return false; 19205 } 19206 19207 final Matrix m = info.mTmpMatrix; 19208 m.set(Matrix.IDENTITY_MATRIX); 19209 transformMatrixToLocal(m); 19210 ev.transform(m); 19211 return true; 19212 } 19213 19214 /** 19215 * Modifies the input matrix such that it maps view-local coordinates to 19216 * on-screen coordinates. 19217 * 19218 * @param m input matrix to modify 19219 * @hide 19220 */ 19221 public void transformMatrixToGlobal(Matrix m) { 19222 final ViewParent parent = mParent; 19223 if (parent instanceof View) { 19224 final View vp = (View) parent; 19225 vp.transformMatrixToGlobal(m); 19226 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19227 } else if (parent instanceof ViewRootImpl) { 19228 final ViewRootImpl vr = (ViewRootImpl) parent; 19229 vr.transformMatrixToGlobal(m); 19230 m.preTranslate(0, -vr.mCurScrollY); 19231 } 19232 19233 m.preTranslate(mLeft, mTop); 19234 19235 if (!hasIdentityMatrix()) { 19236 m.preConcat(getMatrix()); 19237 } 19238 } 19239 19240 /** 19241 * Modifies the input matrix such that it maps on-screen coordinates to 19242 * view-local coordinates. 19243 * 19244 * @param m input matrix to modify 19245 * @hide 19246 */ 19247 public void transformMatrixToLocal(Matrix m) { 19248 final ViewParent parent = mParent; 19249 if (parent instanceof View) { 19250 final View vp = (View) parent; 19251 vp.transformMatrixToLocal(m); 19252 m.postTranslate(vp.mScrollX, vp.mScrollY); 19253 } else if (parent instanceof ViewRootImpl) { 19254 final ViewRootImpl vr = (ViewRootImpl) parent; 19255 vr.transformMatrixToLocal(m); 19256 m.postTranslate(0, vr.mCurScrollY); 19257 } 19258 19259 m.postTranslate(-mLeft, -mTop); 19260 19261 if (!hasIdentityMatrix()) { 19262 m.postConcat(getInverseMatrix()); 19263 } 19264 } 19265 19266 /** 19267 * @hide 19268 */ 19269 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19270 @ViewDebug.IntToString(from = 0, to = "x"), 19271 @ViewDebug.IntToString(from = 1, to = "y") 19272 }) 19273 public int[] getLocationOnScreen() { 19274 int[] location = new int[2]; 19275 getLocationOnScreen(location); 19276 return location; 19277 } 19278 19279 /** 19280 * <p>Computes the coordinates of this view on the screen. The argument 19281 * must be an array of two integers. After the method returns, the array 19282 * contains the x and y location in that order.</p> 19283 * 19284 * @param outLocation an array of two integers in which to hold the coordinates 19285 */ 19286 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19287 getLocationInWindow(outLocation); 19288 19289 final AttachInfo info = mAttachInfo; 19290 if (info != null) { 19291 outLocation[0] += info.mWindowLeft; 19292 outLocation[1] += info.mWindowTop; 19293 } 19294 } 19295 19296 /** 19297 * <p>Computes the coordinates of this view in its window. The argument 19298 * must be an array of two integers. After the method returns, the array 19299 * contains the x and y location in that order.</p> 19300 * 19301 * @param outLocation an array of two integers in which to hold the coordinates 19302 */ 19303 public void getLocationInWindow(@Size(2) int[] outLocation) { 19304 if (outLocation == null || outLocation.length < 2) { 19305 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19306 } 19307 19308 outLocation[0] = 0; 19309 outLocation[1] = 0; 19310 19311 transformFromViewToWindowSpace(outLocation); 19312 } 19313 19314 /** @hide */ 19315 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19316 if (inOutLocation == null || inOutLocation.length < 2) { 19317 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19318 } 19319 19320 if (mAttachInfo == null) { 19321 // When the view is not attached to a window, this method does not make sense 19322 inOutLocation[0] = inOutLocation[1] = 0; 19323 return; 19324 } 19325 19326 float position[] = mAttachInfo.mTmpTransformLocation; 19327 position[0] = inOutLocation[0]; 19328 position[1] = inOutLocation[1]; 19329 19330 if (!hasIdentityMatrix()) { 19331 getMatrix().mapPoints(position); 19332 } 19333 19334 position[0] += mLeft; 19335 position[1] += mTop; 19336 19337 ViewParent viewParent = mParent; 19338 while (viewParent instanceof View) { 19339 final View view = (View) viewParent; 19340 19341 position[0] -= view.mScrollX; 19342 position[1] -= view.mScrollY; 19343 19344 if (!view.hasIdentityMatrix()) { 19345 view.getMatrix().mapPoints(position); 19346 } 19347 19348 position[0] += view.mLeft; 19349 position[1] += view.mTop; 19350 19351 viewParent = view.mParent; 19352 } 19353 19354 if (viewParent instanceof ViewRootImpl) { 19355 // *cough* 19356 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19357 position[1] -= vr.mCurScrollY; 19358 } 19359 19360 inOutLocation[0] = Math.round(position[0]); 19361 inOutLocation[1] = Math.round(position[1]); 19362 } 19363 19364 /** 19365 * {@hide} 19366 * @param id the id of the view to be found 19367 * @return the view of the specified id, null if cannot be found 19368 */ 19369 protected View findViewTraversal(@IdRes int id) { 19370 if (id == mID) { 19371 return this; 19372 } 19373 return null; 19374 } 19375 19376 /** 19377 * {@hide} 19378 * @param tag the tag of the view to be found 19379 * @return the view of specified tag, null if cannot be found 19380 */ 19381 protected View findViewWithTagTraversal(Object tag) { 19382 if (tag != null && tag.equals(mTag)) { 19383 return this; 19384 } 19385 return null; 19386 } 19387 19388 /** 19389 * {@hide} 19390 * @param predicate The predicate to evaluate. 19391 * @param childToSkip If not null, ignores this child during the recursive traversal. 19392 * @return The first view that matches the predicate or null. 19393 */ 19394 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19395 if (predicate.apply(this)) { 19396 return this; 19397 } 19398 return null; 19399 } 19400 19401 /** 19402 * Look for a child view with the given id. If this view has the given 19403 * id, return this view. 19404 * 19405 * @param id The id to search for. 19406 * @return The view that has the given id in the hierarchy or null 19407 */ 19408 @Nullable 19409 public final View findViewById(@IdRes int id) { 19410 if (id < 0) { 19411 return null; 19412 } 19413 return findViewTraversal(id); 19414 } 19415 19416 /** 19417 * Finds a view by its unuque and stable accessibility id. 19418 * 19419 * @param accessibilityId The searched accessibility id. 19420 * @return The found view. 19421 */ 19422 final View findViewByAccessibilityId(int accessibilityId) { 19423 if (accessibilityId < 0) { 19424 return null; 19425 } 19426 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19427 if (view != null) { 19428 return view.includeForAccessibility() ? view : null; 19429 } 19430 return null; 19431 } 19432 19433 /** 19434 * Performs the traversal to find a view by its unuque and stable accessibility id. 19435 * 19436 * <strong>Note:</strong>This method does not stop at the root namespace 19437 * boundary since the user can touch the screen at an arbitrary location 19438 * potentially crossing the root namespace bounday which will send an 19439 * accessibility event to accessibility services and they should be able 19440 * to obtain the event source. Also accessibility ids are guaranteed to be 19441 * unique in the window. 19442 * 19443 * @param accessibilityId The accessibility id. 19444 * @return The found view. 19445 * 19446 * @hide 19447 */ 19448 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19449 if (getAccessibilityViewId() == accessibilityId) { 19450 return this; 19451 } 19452 return null; 19453 } 19454 19455 /** 19456 * Look for a child view with the given tag. If this view has the given 19457 * tag, return this view. 19458 * 19459 * @param tag The tag to search for, using "tag.equals(getTag())". 19460 * @return The View that has the given tag in the hierarchy or null 19461 */ 19462 public final View findViewWithTag(Object tag) { 19463 if (tag == null) { 19464 return null; 19465 } 19466 return findViewWithTagTraversal(tag); 19467 } 19468 19469 /** 19470 * {@hide} 19471 * Look for a child view that matches the specified predicate. 19472 * If this view matches the predicate, return this view. 19473 * 19474 * @param predicate The predicate to evaluate. 19475 * @return The first view that matches the predicate or null. 19476 */ 19477 public final View findViewByPredicate(Predicate<View> predicate) { 19478 return findViewByPredicateTraversal(predicate, null); 19479 } 19480 19481 /** 19482 * {@hide} 19483 * Look for a child view that matches the specified predicate, 19484 * starting with the specified view and its descendents and then 19485 * recusively searching the ancestors and siblings of that view 19486 * until this view is reached. 19487 * 19488 * This method is useful in cases where the predicate does not match 19489 * a single unique view (perhaps multiple views use the same id) 19490 * and we are trying to find the view that is "closest" in scope to the 19491 * starting view. 19492 * 19493 * @param start The view to start from. 19494 * @param predicate The predicate to evaluate. 19495 * @return The first view that matches the predicate or null. 19496 */ 19497 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19498 View childToSkip = null; 19499 for (;;) { 19500 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19501 if (view != null || start == this) { 19502 return view; 19503 } 19504 19505 ViewParent parent = start.getParent(); 19506 if (parent == null || !(parent instanceof View)) { 19507 return null; 19508 } 19509 19510 childToSkip = start; 19511 start = (View) parent; 19512 } 19513 } 19514 19515 /** 19516 * Sets the identifier for this view. The identifier does not have to be 19517 * unique in this view's hierarchy. The identifier should be a positive 19518 * number. 19519 * 19520 * @see #NO_ID 19521 * @see #getId() 19522 * @see #findViewById(int) 19523 * 19524 * @param id a number used to identify the view 19525 * 19526 * @attr ref android.R.styleable#View_id 19527 */ 19528 public void setId(@IdRes int id) { 19529 mID = id; 19530 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19531 mID = generateViewId(); 19532 } 19533 } 19534 19535 /** 19536 * {@hide} 19537 * 19538 * @param isRoot true if the view belongs to the root namespace, false 19539 * otherwise 19540 */ 19541 public void setIsRootNamespace(boolean isRoot) { 19542 if (isRoot) { 19543 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19544 } else { 19545 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19546 } 19547 } 19548 19549 /** 19550 * {@hide} 19551 * 19552 * @return true if the view belongs to the root namespace, false otherwise 19553 */ 19554 public boolean isRootNamespace() { 19555 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19556 } 19557 19558 /** 19559 * Returns this view's identifier. 19560 * 19561 * @return a positive integer used to identify the view or {@link #NO_ID} 19562 * if the view has no ID 19563 * 19564 * @see #setId(int) 19565 * @see #findViewById(int) 19566 * @attr ref android.R.styleable#View_id 19567 */ 19568 @IdRes 19569 @ViewDebug.CapturedViewProperty 19570 public int getId() { 19571 return mID; 19572 } 19573 19574 /** 19575 * Returns this view's tag. 19576 * 19577 * @return the Object stored in this view as a tag, or {@code null} if not 19578 * set 19579 * 19580 * @see #setTag(Object) 19581 * @see #getTag(int) 19582 */ 19583 @ViewDebug.ExportedProperty 19584 public Object getTag() { 19585 return mTag; 19586 } 19587 19588 /** 19589 * Sets the tag associated with this view. A tag can be used to mark 19590 * a view in its hierarchy and does not have to be unique within the 19591 * hierarchy. Tags can also be used to store data within a view without 19592 * resorting to another data structure. 19593 * 19594 * @param tag an Object to tag the view with 19595 * 19596 * @see #getTag() 19597 * @see #setTag(int, Object) 19598 */ 19599 public void setTag(final Object tag) { 19600 mTag = tag; 19601 } 19602 19603 /** 19604 * Returns the tag associated with this view and the specified key. 19605 * 19606 * @param key The key identifying the tag 19607 * 19608 * @return the Object stored in this view as a tag, or {@code null} if not 19609 * set 19610 * 19611 * @see #setTag(int, Object) 19612 * @see #getTag() 19613 */ 19614 public Object getTag(int key) { 19615 if (mKeyedTags != null) return mKeyedTags.get(key); 19616 return null; 19617 } 19618 19619 /** 19620 * Sets a tag associated with this view and a key. A tag can be used 19621 * to mark a view in its hierarchy and does not have to be unique within 19622 * the hierarchy. Tags can also be used to store data within a view 19623 * without resorting to another data structure. 19624 * 19625 * The specified key should be an id declared in the resources of the 19626 * application to ensure it is unique (see the <a 19627 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19628 * Keys identified as belonging to 19629 * the Android framework or not associated with any package will cause 19630 * an {@link IllegalArgumentException} to be thrown. 19631 * 19632 * @param key The key identifying the tag 19633 * @param tag An Object to tag the view with 19634 * 19635 * @throws IllegalArgumentException If they specified key is not valid 19636 * 19637 * @see #setTag(Object) 19638 * @see #getTag(int) 19639 */ 19640 public void setTag(int key, final Object tag) { 19641 // If the package id is 0x00 or 0x01, it's either an undefined package 19642 // or a framework id 19643 if ((key >>> 24) < 2) { 19644 throw new IllegalArgumentException("The key must be an application-specific " 19645 + "resource id."); 19646 } 19647 19648 setKeyedTag(key, tag); 19649 } 19650 19651 /** 19652 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19653 * framework id. 19654 * 19655 * @hide 19656 */ 19657 public void setTagInternal(int key, Object tag) { 19658 if ((key >>> 24) != 0x1) { 19659 throw new IllegalArgumentException("The key must be a framework-specific " 19660 + "resource id."); 19661 } 19662 19663 setKeyedTag(key, tag); 19664 } 19665 19666 private void setKeyedTag(int key, Object tag) { 19667 if (mKeyedTags == null) { 19668 mKeyedTags = new SparseArray<Object>(2); 19669 } 19670 19671 mKeyedTags.put(key, tag); 19672 } 19673 19674 /** 19675 * Prints information about this view in the log output, with the tag 19676 * {@link #VIEW_LOG_TAG}. 19677 * 19678 * @hide 19679 */ 19680 public void debug() { 19681 debug(0); 19682 } 19683 19684 /** 19685 * Prints information about this view in the log output, with the tag 19686 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19687 * indentation defined by the <code>depth</code>. 19688 * 19689 * @param depth the indentation level 19690 * 19691 * @hide 19692 */ 19693 protected void debug(int depth) { 19694 String output = debugIndent(depth - 1); 19695 19696 output += "+ " + this; 19697 int id = getId(); 19698 if (id != -1) { 19699 output += " (id=" + id + ")"; 19700 } 19701 Object tag = getTag(); 19702 if (tag != null) { 19703 output += " (tag=" + tag + ")"; 19704 } 19705 Log.d(VIEW_LOG_TAG, output); 19706 19707 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19708 output = debugIndent(depth) + " FOCUSED"; 19709 Log.d(VIEW_LOG_TAG, output); 19710 } 19711 19712 output = debugIndent(depth); 19713 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19714 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19715 + "} "; 19716 Log.d(VIEW_LOG_TAG, output); 19717 19718 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19719 || mPaddingBottom != 0) { 19720 output = debugIndent(depth); 19721 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19722 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19723 Log.d(VIEW_LOG_TAG, output); 19724 } 19725 19726 output = debugIndent(depth); 19727 output += "mMeasureWidth=" + mMeasuredWidth + 19728 " mMeasureHeight=" + mMeasuredHeight; 19729 Log.d(VIEW_LOG_TAG, output); 19730 19731 output = debugIndent(depth); 19732 if (mLayoutParams == null) { 19733 output += "BAD! no layout params"; 19734 } else { 19735 output = mLayoutParams.debug(output); 19736 } 19737 Log.d(VIEW_LOG_TAG, output); 19738 19739 output = debugIndent(depth); 19740 output += "flags={"; 19741 output += View.printFlags(mViewFlags); 19742 output += "}"; 19743 Log.d(VIEW_LOG_TAG, output); 19744 19745 output = debugIndent(depth); 19746 output += "privateFlags={"; 19747 output += View.printPrivateFlags(mPrivateFlags); 19748 output += "}"; 19749 Log.d(VIEW_LOG_TAG, output); 19750 } 19751 19752 /** 19753 * Creates a string of whitespaces used for indentation. 19754 * 19755 * @param depth the indentation level 19756 * @return a String containing (depth * 2 + 3) * 2 white spaces 19757 * 19758 * @hide 19759 */ 19760 protected static String debugIndent(int depth) { 19761 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19762 for (int i = 0; i < (depth * 2) + 3; i++) { 19763 spaces.append(' ').append(' '); 19764 } 19765 return spaces.toString(); 19766 } 19767 19768 /** 19769 * <p>Return the offset of the widget's text baseline from the widget's top 19770 * boundary. If this widget does not support baseline alignment, this 19771 * method returns -1. </p> 19772 * 19773 * @return the offset of the baseline within the widget's bounds or -1 19774 * if baseline alignment is not supported 19775 */ 19776 @ViewDebug.ExportedProperty(category = "layout") 19777 public int getBaseline() { 19778 return -1; 19779 } 19780 19781 /** 19782 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19783 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19784 * a layout pass. 19785 * 19786 * @return whether the view hierarchy is currently undergoing a layout pass 19787 */ 19788 public boolean isInLayout() { 19789 ViewRootImpl viewRoot = getViewRootImpl(); 19790 return (viewRoot != null && viewRoot.isInLayout()); 19791 } 19792 19793 /** 19794 * Call this when something has changed which has invalidated the 19795 * layout of this view. This will schedule a layout pass of the view 19796 * tree. This should not be called while the view hierarchy is currently in a layout 19797 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19798 * end of the current layout pass (and then layout will run again) or after the current 19799 * frame is drawn and the next layout occurs. 19800 * 19801 * <p>Subclasses which override this method should call the superclass method to 19802 * handle possible request-during-layout errors correctly.</p> 19803 */ 19804 @CallSuper 19805 public void requestLayout() { 19806 if (mMeasureCache != null) mMeasureCache.clear(); 19807 19808 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19809 // Only trigger request-during-layout logic if this is the view requesting it, 19810 // not the views in its parent hierarchy 19811 ViewRootImpl viewRoot = getViewRootImpl(); 19812 if (viewRoot != null && viewRoot.isInLayout()) { 19813 if (!viewRoot.requestLayoutDuringLayout(this)) { 19814 return; 19815 } 19816 } 19817 mAttachInfo.mViewRequestingLayout = this; 19818 } 19819 19820 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19821 mPrivateFlags |= PFLAG_INVALIDATED; 19822 19823 if (mParent != null && !mParent.isLayoutRequested()) { 19824 mParent.requestLayout(); 19825 } 19826 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19827 mAttachInfo.mViewRequestingLayout = null; 19828 } 19829 } 19830 19831 /** 19832 * Forces this view to be laid out during the next layout pass. 19833 * This method does not call requestLayout() or forceLayout() 19834 * on the parent. 19835 */ 19836 public void forceLayout() { 19837 if (mMeasureCache != null) mMeasureCache.clear(); 19838 19839 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19840 mPrivateFlags |= PFLAG_INVALIDATED; 19841 } 19842 19843 /** 19844 * <p> 19845 * This is called to find out how big a view should be. The parent 19846 * supplies constraint information in the width and height parameters. 19847 * </p> 19848 * 19849 * <p> 19850 * The actual measurement work of a view is performed in 19851 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19852 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19853 * </p> 19854 * 19855 * 19856 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19857 * parent 19858 * @param heightMeasureSpec Vertical space requirements as imposed by the 19859 * parent 19860 * 19861 * @see #onMeasure(int, int) 19862 */ 19863 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19864 boolean optical = isLayoutModeOptical(this); 19865 if (optical != isLayoutModeOptical(mParent)) { 19866 Insets insets = getOpticalInsets(); 19867 int oWidth = insets.left + insets.right; 19868 int oHeight = insets.top + insets.bottom; 19869 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19870 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19871 } 19872 19873 // Suppress sign extension for the low bytes 19874 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19875 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19876 19877 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19878 19879 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19880 // already measured as the correct size. In API 23 and below, this 19881 // extra pass is required to make LinearLayout re-distribute weight. 19882 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19883 || heightMeasureSpec != mOldHeightMeasureSpec; 19884 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19885 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19886 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19887 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19888 final boolean needsLayout = specChanged 19889 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19890 19891 if (forceLayout || needsLayout) { 19892 // first clears the measured dimension flag 19893 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19894 19895 resolveRtlPropertiesIfNeeded(); 19896 19897 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19898 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19899 // measure ourselves, this should set the measured dimension flag back 19900 onMeasure(widthMeasureSpec, heightMeasureSpec); 19901 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19902 } else { 19903 long value = mMeasureCache.valueAt(cacheIndex); 19904 // Casting a long to int drops the high 32 bits, no mask needed 19905 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19906 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19907 } 19908 19909 // flag not set, setMeasuredDimension() was not invoked, we raise 19910 // an exception to warn the developer 19911 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19912 throw new IllegalStateException("View with id " + getId() + ": " 19913 + getClass().getName() + "#onMeasure() did not set the" 19914 + " measured dimension by calling" 19915 + " setMeasuredDimension()"); 19916 } 19917 19918 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19919 } 19920 19921 mOldWidthMeasureSpec = widthMeasureSpec; 19922 mOldHeightMeasureSpec = heightMeasureSpec; 19923 19924 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19925 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19926 } 19927 19928 /** 19929 * <p> 19930 * Measure the view and its content to determine the measured width and the 19931 * measured height. This method is invoked by {@link #measure(int, int)} and 19932 * should be overridden by subclasses to provide accurate and efficient 19933 * measurement of their contents. 19934 * </p> 19935 * 19936 * <p> 19937 * <strong>CONTRACT:</strong> When overriding this method, you 19938 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19939 * measured width and height of this view. Failure to do so will trigger an 19940 * <code>IllegalStateException</code>, thrown by 19941 * {@link #measure(int, int)}. Calling the superclass' 19942 * {@link #onMeasure(int, int)} is a valid use. 19943 * </p> 19944 * 19945 * <p> 19946 * The base class implementation of measure defaults to the background size, 19947 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19948 * override {@link #onMeasure(int, int)} to provide better measurements of 19949 * their content. 19950 * </p> 19951 * 19952 * <p> 19953 * If this method is overridden, it is the subclass's responsibility to make 19954 * sure the measured height and width are at least the view's minimum height 19955 * and width ({@link #getSuggestedMinimumHeight()} and 19956 * {@link #getSuggestedMinimumWidth()}). 19957 * </p> 19958 * 19959 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19960 * The requirements are encoded with 19961 * {@link android.view.View.MeasureSpec}. 19962 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19963 * The requirements are encoded with 19964 * {@link android.view.View.MeasureSpec}. 19965 * 19966 * @see #getMeasuredWidth() 19967 * @see #getMeasuredHeight() 19968 * @see #setMeasuredDimension(int, int) 19969 * @see #getSuggestedMinimumHeight() 19970 * @see #getSuggestedMinimumWidth() 19971 * @see android.view.View.MeasureSpec#getMode(int) 19972 * @see android.view.View.MeasureSpec#getSize(int) 19973 */ 19974 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19975 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19976 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19977 } 19978 19979 /** 19980 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19981 * measured width and measured height. Failing to do so will trigger an 19982 * exception at measurement time.</p> 19983 * 19984 * @param measuredWidth The measured width of this view. May be a complex 19985 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19986 * {@link #MEASURED_STATE_TOO_SMALL}. 19987 * @param measuredHeight The measured height of this view. May be a complex 19988 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19989 * {@link #MEASURED_STATE_TOO_SMALL}. 19990 */ 19991 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19992 boolean optical = isLayoutModeOptical(this); 19993 if (optical != isLayoutModeOptical(mParent)) { 19994 Insets insets = getOpticalInsets(); 19995 int opticalWidth = insets.left + insets.right; 19996 int opticalHeight = insets.top + insets.bottom; 19997 19998 measuredWidth += optical ? opticalWidth : -opticalWidth; 19999 measuredHeight += optical ? opticalHeight : -opticalHeight; 20000 } 20001 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 20002 } 20003 20004 /** 20005 * Sets the measured dimension without extra processing for things like optical bounds. 20006 * Useful for reapplying consistent values that have already been cooked with adjustments 20007 * for optical bounds, etc. such as those from the measurement cache. 20008 * 20009 * @param measuredWidth The measured width of this view. May be a complex 20010 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20011 * {@link #MEASURED_STATE_TOO_SMALL}. 20012 * @param measuredHeight The measured height of this view. May be a complex 20013 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 20014 * {@link #MEASURED_STATE_TOO_SMALL}. 20015 */ 20016 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 20017 mMeasuredWidth = measuredWidth; 20018 mMeasuredHeight = measuredHeight; 20019 20020 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 20021 } 20022 20023 /** 20024 * Merge two states as returned by {@link #getMeasuredState()}. 20025 * @param curState The current state as returned from a view or the result 20026 * of combining multiple views. 20027 * @param newState The new view state to combine. 20028 * @return Returns a new integer reflecting the combination of the two 20029 * states. 20030 */ 20031 public static int combineMeasuredStates(int curState, int newState) { 20032 return curState | newState; 20033 } 20034 20035 /** 20036 * Version of {@link #resolveSizeAndState(int, int, int)} 20037 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 20038 */ 20039 public static int resolveSize(int size, int measureSpec) { 20040 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 20041 } 20042 20043 /** 20044 * Utility to reconcile a desired size and state, with constraints imposed 20045 * by a MeasureSpec. Will take the desired size, unless a different size 20046 * is imposed by the constraints. The returned value is a compound integer, 20047 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 20048 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 20049 * resulting size is smaller than the size the view wants to be. 20050 * 20051 * @param size How big the view wants to be. 20052 * @param measureSpec Constraints imposed by the parent. 20053 * @param childMeasuredState Size information bit mask for the view's 20054 * children. 20055 * @return Size information bit mask as defined by 20056 * {@link #MEASURED_SIZE_MASK} and 20057 * {@link #MEASURED_STATE_TOO_SMALL}. 20058 */ 20059 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 20060 final int specMode = MeasureSpec.getMode(measureSpec); 20061 final int specSize = MeasureSpec.getSize(measureSpec); 20062 final int result; 20063 switch (specMode) { 20064 case MeasureSpec.AT_MOST: 20065 if (specSize < size) { 20066 result = specSize | MEASURED_STATE_TOO_SMALL; 20067 } else { 20068 result = size; 20069 } 20070 break; 20071 case MeasureSpec.EXACTLY: 20072 result = specSize; 20073 break; 20074 case MeasureSpec.UNSPECIFIED: 20075 default: 20076 result = size; 20077 } 20078 return result | (childMeasuredState & MEASURED_STATE_MASK); 20079 } 20080 20081 /** 20082 * Utility to return a default size. Uses the supplied size if the 20083 * MeasureSpec imposed no constraints. Will get larger if allowed 20084 * by the MeasureSpec. 20085 * 20086 * @param size Default size for this view 20087 * @param measureSpec Constraints imposed by the parent 20088 * @return The size this view should be. 20089 */ 20090 public static int getDefaultSize(int size, int measureSpec) { 20091 int result = size; 20092 int specMode = MeasureSpec.getMode(measureSpec); 20093 int specSize = MeasureSpec.getSize(measureSpec); 20094 20095 switch (specMode) { 20096 case MeasureSpec.UNSPECIFIED: 20097 result = size; 20098 break; 20099 case MeasureSpec.AT_MOST: 20100 case MeasureSpec.EXACTLY: 20101 result = specSize; 20102 break; 20103 } 20104 return result; 20105 } 20106 20107 /** 20108 * Returns the suggested minimum height that the view should use. This 20109 * returns the maximum of the view's minimum height 20110 * and the background's minimum height 20111 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 20112 * <p> 20113 * When being used in {@link #onMeasure(int, int)}, the caller should still 20114 * ensure the returned height is within the requirements of the parent. 20115 * 20116 * @return The suggested minimum height of the view. 20117 */ 20118 protected int getSuggestedMinimumHeight() { 20119 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 20120 20121 } 20122 20123 /** 20124 * Returns the suggested minimum width that the view should use. This 20125 * returns the maximum of the view's minimum width 20126 * and the background's minimum width 20127 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 20128 * <p> 20129 * When being used in {@link #onMeasure(int, int)}, the caller should still 20130 * ensure the returned width is within the requirements of the parent. 20131 * 20132 * @return The suggested minimum width of the view. 20133 */ 20134 protected int getSuggestedMinimumWidth() { 20135 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 20136 } 20137 20138 /** 20139 * Returns the minimum height of the view. 20140 * 20141 * @return the minimum height the view will try to be, in pixels 20142 * 20143 * @see #setMinimumHeight(int) 20144 * 20145 * @attr ref android.R.styleable#View_minHeight 20146 */ 20147 public int getMinimumHeight() { 20148 return mMinHeight; 20149 } 20150 20151 /** 20152 * Sets the minimum height of the view. It is not guaranteed the view will 20153 * be able to achieve this minimum height (for example, if its parent layout 20154 * constrains it with less available height). 20155 * 20156 * @param minHeight The minimum height the view will try to be, in pixels 20157 * 20158 * @see #getMinimumHeight() 20159 * 20160 * @attr ref android.R.styleable#View_minHeight 20161 */ 20162 @RemotableViewMethod 20163 public void setMinimumHeight(int minHeight) { 20164 mMinHeight = minHeight; 20165 requestLayout(); 20166 } 20167 20168 /** 20169 * Returns the minimum width of the view. 20170 * 20171 * @return the minimum width the view will try to be, in pixels 20172 * 20173 * @see #setMinimumWidth(int) 20174 * 20175 * @attr ref android.R.styleable#View_minWidth 20176 */ 20177 public int getMinimumWidth() { 20178 return mMinWidth; 20179 } 20180 20181 /** 20182 * Sets the minimum width of the view. It is not guaranteed the view will 20183 * be able to achieve this minimum width (for example, if its parent layout 20184 * constrains it with less available width). 20185 * 20186 * @param minWidth The minimum width the view will try to be, in pixels 20187 * 20188 * @see #getMinimumWidth() 20189 * 20190 * @attr ref android.R.styleable#View_minWidth 20191 */ 20192 public void setMinimumWidth(int minWidth) { 20193 mMinWidth = minWidth; 20194 requestLayout(); 20195 20196 } 20197 20198 /** 20199 * Get the animation currently associated with this view. 20200 * 20201 * @return The animation that is currently playing or 20202 * scheduled to play for this view. 20203 */ 20204 public Animation getAnimation() { 20205 return mCurrentAnimation; 20206 } 20207 20208 /** 20209 * Start the specified animation now. 20210 * 20211 * @param animation the animation to start now 20212 */ 20213 public void startAnimation(Animation animation) { 20214 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20215 setAnimation(animation); 20216 invalidateParentCaches(); 20217 invalidate(true); 20218 } 20219 20220 /** 20221 * Cancels any animations for this view. 20222 */ 20223 public void clearAnimation() { 20224 if (mCurrentAnimation != null) { 20225 mCurrentAnimation.detach(); 20226 } 20227 mCurrentAnimation = null; 20228 invalidateParentIfNeeded(); 20229 } 20230 20231 /** 20232 * Sets the next animation to play for this view. 20233 * If you want the animation to play immediately, use 20234 * {@link #startAnimation(android.view.animation.Animation)} instead. 20235 * This method provides allows fine-grained 20236 * control over the start time and invalidation, but you 20237 * must make sure that 1) the animation has a start time set, and 20238 * 2) the view's parent (which controls animations on its children) 20239 * will be invalidated when the animation is supposed to 20240 * start. 20241 * 20242 * @param animation The next animation, or null. 20243 */ 20244 public void setAnimation(Animation animation) { 20245 mCurrentAnimation = animation; 20246 20247 if (animation != null) { 20248 // If the screen is off assume the animation start time is now instead of 20249 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20250 // would cause the animation to start when the screen turns back on 20251 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20252 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20253 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20254 } 20255 animation.reset(); 20256 } 20257 } 20258 20259 /** 20260 * Invoked by a parent ViewGroup to notify the start of the animation 20261 * currently associated with this view. If you override this method, 20262 * always call super.onAnimationStart(); 20263 * 20264 * @see #setAnimation(android.view.animation.Animation) 20265 * @see #getAnimation() 20266 */ 20267 @CallSuper 20268 protected void onAnimationStart() { 20269 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20270 } 20271 20272 /** 20273 * Invoked by a parent ViewGroup to notify the end of the animation 20274 * currently associated with this view. If you override this method, 20275 * always call super.onAnimationEnd(); 20276 * 20277 * @see #setAnimation(android.view.animation.Animation) 20278 * @see #getAnimation() 20279 */ 20280 @CallSuper 20281 protected void onAnimationEnd() { 20282 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20283 } 20284 20285 /** 20286 * Invoked if there is a Transform that involves alpha. Subclass that can 20287 * draw themselves with the specified alpha should return true, and then 20288 * respect that alpha when their onDraw() is called. If this returns false 20289 * then the view may be redirected to draw into an offscreen buffer to 20290 * fulfill the request, which will look fine, but may be slower than if the 20291 * subclass handles it internally. The default implementation returns false. 20292 * 20293 * @param alpha The alpha (0..255) to apply to the view's drawing 20294 * @return true if the view can draw with the specified alpha. 20295 */ 20296 protected boolean onSetAlpha(int alpha) { 20297 return false; 20298 } 20299 20300 /** 20301 * This is used by the RootView to perform an optimization when 20302 * the view hierarchy contains one or several SurfaceView. 20303 * SurfaceView is always considered transparent, but its children are not, 20304 * therefore all View objects remove themselves from the global transparent 20305 * region (passed as a parameter to this function). 20306 * 20307 * @param region The transparent region for this ViewAncestor (window). 20308 * 20309 * @return Returns true if the effective visibility of the view at this 20310 * point is opaque, regardless of the transparent region; returns false 20311 * if it is possible for underlying windows to be seen behind the view. 20312 * 20313 * {@hide} 20314 */ 20315 public boolean gatherTransparentRegion(Region region) { 20316 final AttachInfo attachInfo = mAttachInfo; 20317 if (region != null && attachInfo != null) { 20318 final int pflags = mPrivateFlags; 20319 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20320 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20321 // remove it from the transparent region. 20322 final int[] location = attachInfo.mTransparentLocation; 20323 getLocationInWindow(location); 20324 // When a view has Z value, then it will be better to leave some area below the view 20325 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 20326 // the bottom part needs more offset than the left, top and right parts due to the 20327 // spot light effects. 20328 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 20329 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 20330 location[0] + mRight - mLeft + shadowOffset, 20331 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 20332 } else { 20333 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20334 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20335 // the background drawable's non-transparent parts from this transparent region. 20336 applyDrawableToTransparentRegion(mBackground, region); 20337 } 20338 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20339 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20340 // Similarly, we remove the foreground drawable's non-transparent parts. 20341 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20342 } 20343 } 20344 } 20345 return true; 20346 } 20347 20348 /** 20349 * Play a sound effect for this view. 20350 * 20351 * <p>The framework will play sound effects for some built in actions, such as 20352 * clicking, but you may wish to play these effects in your widget, 20353 * for instance, for internal navigation. 20354 * 20355 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20356 * {@link #isSoundEffectsEnabled()} is true. 20357 * 20358 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20359 */ 20360 public void playSoundEffect(int soundConstant) { 20361 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20362 return; 20363 } 20364 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20365 } 20366 20367 /** 20368 * BZZZTT!!1! 20369 * 20370 * <p>Provide haptic feedback to the user for this view. 20371 * 20372 * <p>The framework will provide haptic feedback for some built in actions, 20373 * such as long presses, but you may wish to provide feedback for your 20374 * own widget. 20375 * 20376 * <p>The feedback will only be performed if 20377 * {@link #isHapticFeedbackEnabled()} is true. 20378 * 20379 * @param feedbackConstant One of the constants defined in 20380 * {@link HapticFeedbackConstants} 20381 */ 20382 public boolean performHapticFeedback(int feedbackConstant) { 20383 return performHapticFeedback(feedbackConstant, 0); 20384 } 20385 20386 /** 20387 * BZZZTT!!1! 20388 * 20389 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20390 * 20391 * @param feedbackConstant One of the constants defined in 20392 * {@link HapticFeedbackConstants} 20393 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20394 */ 20395 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20396 if (mAttachInfo == null) { 20397 return false; 20398 } 20399 //noinspection SimplifiableIfStatement 20400 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20401 && !isHapticFeedbackEnabled()) { 20402 return false; 20403 } 20404 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20405 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20406 } 20407 20408 /** 20409 * Request that the visibility of the status bar or other screen/window 20410 * decorations be changed. 20411 * 20412 * <p>This method is used to put the over device UI into temporary modes 20413 * where the user's attention is focused more on the application content, 20414 * by dimming or hiding surrounding system affordances. This is typically 20415 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20416 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20417 * to be placed behind the action bar (and with these flags other system 20418 * affordances) so that smooth transitions between hiding and showing them 20419 * can be done. 20420 * 20421 * <p>Two representative examples of the use of system UI visibility is 20422 * implementing a content browsing application (like a magazine reader) 20423 * and a video playing application. 20424 * 20425 * <p>The first code shows a typical implementation of a View in a content 20426 * browsing application. In this implementation, the application goes 20427 * into a content-oriented mode by hiding the status bar and action bar, 20428 * and putting the navigation elements into lights out mode. The user can 20429 * then interact with content while in this mode. Such an application should 20430 * provide an easy way for the user to toggle out of the mode (such as to 20431 * check information in the status bar or access notifications). In the 20432 * implementation here, this is done simply by tapping on the content. 20433 * 20434 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20435 * content} 20436 * 20437 * <p>This second code sample shows a typical implementation of a View 20438 * in a video playing application. In this situation, while the video is 20439 * playing the application would like to go into a complete full-screen mode, 20440 * to use as much of the display as possible for the video. When in this state 20441 * the user can not interact with the application; the system intercepts 20442 * touching on the screen to pop the UI out of full screen mode. See 20443 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20444 * 20445 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20446 * content} 20447 * 20448 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20449 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20450 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20451 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20452 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20453 */ 20454 public void setSystemUiVisibility(int visibility) { 20455 if (visibility != mSystemUiVisibility) { 20456 mSystemUiVisibility = visibility; 20457 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20458 mParent.recomputeViewAttributes(this); 20459 } 20460 } 20461 } 20462 20463 /** 20464 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20465 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20466 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20467 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20468 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20469 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20470 */ 20471 public int getSystemUiVisibility() { 20472 return mSystemUiVisibility; 20473 } 20474 20475 /** 20476 * Returns the current system UI visibility that is currently set for 20477 * the entire window. This is the combination of the 20478 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20479 * views in the window. 20480 */ 20481 public int getWindowSystemUiVisibility() { 20482 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20483 } 20484 20485 /** 20486 * Override to find out when the window's requested system UI visibility 20487 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20488 * This is different from the callbacks received through 20489 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20490 * in that this is only telling you about the local request of the window, 20491 * not the actual values applied by the system. 20492 */ 20493 public void onWindowSystemUiVisibilityChanged(int visible) { 20494 } 20495 20496 /** 20497 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20498 * the view hierarchy. 20499 */ 20500 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20501 onWindowSystemUiVisibilityChanged(visible); 20502 } 20503 20504 /** 20505 * Set a listener to receive callbacks when the visibility of the system bar changes. 20506 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20507 */ 20508 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20509 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20510 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20511 mParent.recomputeViewAttributes(this); 20512 } 20513 } 20514 20515 /** 20516 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20517 * the view hierarchy. 20518 */ 20519 public void dispatchSystemUiVisibilityChanged(int visibility) { 20520 ListenerInfo li = mListenerInfo; 20521 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20522 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20523 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20524 } 20525 } 20526 20527 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20528 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20529 if (val != mSystemUiVisibility) { 20530 setSystemUiVisibility(val); 20531 return true; 20532 } 20533 return false; 20534 } 20535 20536 /** @hide */ 20537 public void setDisabledSystemUiVisibility(int flags) { 20538 if (mAttachInfo != null) { 20539 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20540 mAttachInfo.mDisabledSystemUiVisibility = flags; 20541 if (mParent != null) { 20542 mParent.recomputeViewAttributes(this); 20543 } 20544 } 20545 } 20546 } 20547 20548 /** 20549 * Creates an image that the system displays during the drag and drop 20550 * operation. This is called a "drag shadow". The default implementation 20551 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20552 * appearance as the given View. The default also positions the center of the drag shadow 20553 * directly under the touch point. If no View is provided (the constructor with no parameters 20554 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20555 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20556 * default is an invisible drag shadow. 20557 * <p> 20558 * You are not required to use the View you provide to the constructor as the basis of the 20559 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20560 * anything you want as the drag shadow. 20561 * </p> 20562 * <p> 20563 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20564 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20565 * size and position of the drag shadow. It uses this data to construct a 20566 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20567 * so that your application can draw the shadow image in the Canvas. 20568 * </p> 20569 * 20570 * <div class="special reference"> 20571 * <h3>Developer Guides</h3> 20572 * <p>For a guide to implementing drag and drop features, read the 20573 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20574 * </div> 20575 */ 20576 public static class DragShadowBuilder { 20577 private final WeakReference<View> mView; 20578 20579 /** 20580 * Constructs a shadow image builder based on a View. By default, the resulting drag 20581 * shadow will have the same appearance and dimensions as the View, with the touch point 20582 * over the center of the View. 20583 * @param view A View. Any View in scope can be used. 20584 */ 20585 public DragShadowBuilder(View view) { 20586 mView = new WeakReference<View>(view); 20587 } 20588 20589 /** 20590 * Construct a shadow builder object with no associated View. This 20591 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20592 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20593 * to supply the drag shadow's dimensions and appearance without 20594 * reference to any View object. If they are not overridden, then the result is an 20595 * invisible drag shadow. 20596 */ 20597 public DragShadowBuilder() { 20598 mView = new WeakReference<View>(null); 20599 } 20600 20601 /** 20602 * Returns the View object that had been passed to the 20603 * {@link #View.DragShadowBuilder(View)} 20604 * constructor. If that View parameter was {@code null} or if the 20605 * {@link #View.DragShadowBuilder()} 20606 * constructor was used to instantiate the builder object, this method will return 20607 * null. 20608 * 20609 * @return The View object associate with this builder object. 20610 */ 20611 @SuppressWarnings({"JavadocReference"}) 20612 final public View getView() { 20613 return mView.get(); 20614 } 20615 20616 /** 20617 * Provides the metrics for the shadow image. These include the dimensions of 20618 * the shadow image, and the point within that shadow that should 20619 * be centered under the touch location while dragging. 20620 * <p> 20621 * The default implementation sets the dimensions of the shadow to be the 20622 * same as the dimensions of the View itself and centers the shadow under 20623 * the touch point. 20624 * </p> 20625 * 20626 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20627 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20628 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20629 * image. 20630 * 20631 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20632 * shadow image that should be underneath the touch point during the drag and drop 20633 * operation. Your application must set {@link android.graphics.Point#x} to the 20634 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20635 */ 20636 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20637 final View view = mView.get(); 20638 if (view != null) { 20639 outShadowSize.set(view.getWidth(), view.getHeight()); 20640 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20641 } else { 20642 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20643 } 20644 } 20645 20646 /** 20647 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20648 * based on the dimensions it received from the 20649 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20650 * 20651 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20652 */ 20653 public void onDrawShadow(Canvas canvas) { 20654 final View view = mView.get(); 20655 if (view != null) { 20656 view.draw(canvas); 20657 } else { 20658 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20659 } 20660 } 20661 } 20662 20663 /** 20664 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20665 * startDragAndDrop()} for newer platform versions. 20666 */ 20667 @Deprecated 20668 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20669 Object myLocalState, int flags) { 20670 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20671 } 20672 20673 /** 20674 * Starts a drag and drop operation. When your application calls this method, it passes a 20675 * {@link android.view.View.DragShadowBuilder} object to the system. The 20676 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20677 * to get metrics for the drag shadow, and then calls the object's 20678 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20679 * <p> 20680 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20681 * drag events to all the View objects in your application that are currently visible. It does 20682 * this either by calling the View object's drag listener (an implementation of 20683 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20684 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20685 * Both are passed a {@link android.view.DragEvent} object that has a 20686 * {@link android.view.DragEvent#getAction()} value of 20687 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20688 * </p> 20689 * <p> 20690 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20691 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20692 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20693 * to the View the user selected for dragging. 20694 * </p> 20695 * @param data A {@link android.content.ClipData} object pointing to the data to be 20696 * transferred by the drag and drop operation. 20697 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20698 * drag shadow. 20699 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20700 * drop operation. When dispatching drag events to views in the same activity this object 20701 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 20702 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 20703 * will return null). 20704 * <p> 20705 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20706 * to the target Views. For example, it can contain flags that differentiate between a 20707 * a copy operation and a move operation. 20708 * </p> 20709 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 20710 * flags, or any combination of the following: 20711 * <ul> 20712 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 20713 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 20714 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 20715 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 20716 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 20717 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 20718 * </ul> 20719 * @return {@code true} if the method completes successfully, or 20720 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20721 * do a drag, and so no drag operation is in progress. 20722 */ 20723 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20724 Object myLocalState, int flags) { 20725 if (ViewDebug.DEBUG_DRAG) { 20726 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20727 } 20728 if (mAttachInfo == null) { 20729 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 20730 return false; 20731 } 20732 20733 if (data != null) { 20734 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 20735 } 20736 20737 boolean okay = false; 20738 20739 Point shadowSize = new Point(); 20740 Point shadowTouchPoint = new Point(); 20741 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20742 20743 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20744 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20745 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20746 } 20747 20748 if (ViewDebug.DEBUG_DRAG) { 20749 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20750 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20751 } 20752 if (mAttachInfo.mDragSurface != null) { 20753 mAttachInfo.mDragSurface.release(); 20754 } 20755 mAttachInfo.mDragSurface = new Surface(); 20756 try { 20757 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20758 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20759 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20760 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20761 if (mAttachInfo.mDragToken != null) { 20762 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20763 try { 20764 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20765 shadowBuilder.onDrawShadow(canvas); 20766 } finally { 20767 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20768 } 20769 20770 final ViewRootImpl root = getViewRootImpl(); 20771 20772 // Cache the local state object for delivery with DragEvents 20773 root.setLocalDragState(myLocalState); 20774 20775 // repurpose 'shadowSize' for the last touch point 20776 root.getLastTouchPoint(shadowSize); 20777 20778 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20779 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20780 shadowTouchPoint.x, shadowTouchPoint.y, data); 20781 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20782 } 20783 } catch (Exception e) { 20784 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20785 mAttachInfo.mDragSurface.destroy(); 20786 mAttachInfo.mDragSurface = null; 20787 } 20788 20789 return okay; 20790 } 20791 20792 /** 20793 * Cancels an ongoing drag and drop operation. 20794 * <p> 20795 * A {@link android.view.DragEvent} object with 20796 * {@link android.view.DragEvent#getAction()} value of 20797 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20798 * {@link android.view.DragEvent#getResult()} value of {@code false} 20799 * will be sent to every 20800 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20801 * even if they are not currently visible. 20802 * </p> 20803 * <p> 20804 * This method can be called on any View in the same window as the View on which 20805 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20806 * was called. 20807 * </p> 20808 */ 20809 public final void cancelDragAndDrop() { 20810 if (ViewDebug.DEBUG_DRAG) { 20811 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20812 } 20813 if (mAttachInfo == null) { 20814 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 20815 return; 20816 } 20817 if (mAttachInfo.mDragToken != null) { 20818 try { 20819 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20820 } catch (Exception e) { 20821 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20822 } 20823 mAttachInfo.mDragToken = null; 20824 } else { 20825 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20826 } 20827 } 20828 20829 /** 20830 * Updates the drag shadow for the ongoing drag and drop operation. 20831 * 20832 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20833 * new drag shadow. 20834 */ 20835 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20836 if (ViewDebug.DEBUG_DRAG) { 20837 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20838 } 20839 if (mAttachInfo == null) { 20840 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 20841 return; 20842 } 20843 if (mAttachInfo.mDragToken != null) { 20844 try { 20845 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20846 try { 20847 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20848 shadowBuilder.onDrawShadow(canvas); 20849 } finally { 20850 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20851 } 20852 } catch (Exception e) { 20853 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20854 } 20855 } else { 20856 Log.e(VIEW_LOG_TAG, "No active drag"); 20857 } 20858 } 20859 20860 /** 20861 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20862 * between {startX, startY} and the new cursor positon. 20863 * @param startX horizontal coordinate where the move started. 20864 * @param startY vertical coordinate where the move started. 20865 * @return whether moving was started successfully. 20866 * @hide 20867 */ 20868 public final boolean startMovingTask(float startX, float startY) { 20869 if (ViewDebug.DEBUG_POSITIONING) { 20870 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20871 } 20872 try { 20873 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20874 } catch (RemoteException e) { 20875 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20876 } 20877 return false; 20878 } 20879 20880 /** 20881 * Handles drag events sent by the system following a call to 20882 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20883 * startDragAndDrop()}. 20884 *<p> 20885 * When the system calls this method, it passes a 20886 * {@link android.view.DragEvent} object. A call to 20887 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20888 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20889 * operation. 20890 * @param event The {@link android.view.DragEvent} sent by the system. 20891 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20892 * in DragEvent, indicating the type of drag event represented by this object. 20893 * @return {@code true} if the method was successful, otherwise {@code false}. 20894 * <p> 20895 * The method should return {@code true} in response to an action type of 20896 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20897 * operation. 20898 * </p> 20899 * <p> 20900 * The method should also return {@code true} in response to an action type of 20901 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20902 * {@code false} if it didn't. 20903 * </p> 20904 * <p> 20905 * For all other events, the return value is ignored. 20906 * </p> 20907 */ 20908 public boolean onDragEvent(DragEvent event) { 20909 return false; 20910 } 20911 20912 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 20913 boolean dispatchDragEnterExitInPreN(DragEvent event) { 20914 return callDragEventHandler(event); 20915 } 20916 20917 /** 20918 * Detects if this View is enabled and has a drag event listener. 20919 * If both are true, then it calls the drag event listener with the 20920 * {@link android.view.DragEvent} it received. If the drag event listener returns 20921 * {@code true}, then dispatchDragEvent() returns {@code true}. 20922 * <p> 20923 * For all other cases, the method calls the 20924 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20925 * method and returns its result. 20926 * </p> 20927 * <p> 20928 * This ensures that a drag event is always consumed, even if the View does not have a drag 20929 * event listener. However, if the View has a listener and the listener returns true, then 20930 * onDragEvent() is not called. 20931 * </p> 20932 */ 20933 public boolean dispatchDragEvent(DragEvent event) { 20934 event.mEventHandlerWasCalled = true; 20935 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 20936 event.mAction == DragEvent.ACTION_DROP) { 20937 // About to deliver an event with coordinates to this view. Notify that now this view 20938 // has drag focus. This will send exit/enter events as needed. 20939 getViewRootImpl().setDragFocus(this, event); 20940 } 20941 return callDragEventHandler(event); 20942 } 20943 20944 final boolean callDragEventHandler(DragEvent event) { 20945 final boolean result; 20946 20947 ListenerInfo li = mListenerInfo; 20948 //noinspection SimplifiableIfStatement 20949 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20950 && li.mOnDragListener.onDrag(this, event)) { 20951 result = true; 20952 } else { 20953 result = onDragEvent(event); 20954 } 20955 20956 switch (event.mAction) { 20957 case DragEvent.ACTION_DRAG_ENTERED: { 20958 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 20959 refreshDrawableState(); 20960 } break; 20961 case DragEvent.ACTION_DRAG_EXITED: { 20962 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 20963 refreshDrawableState(); 20964 } break; 20965 case DragEvent.ACTION_DRAG_ENDED: { 20966 mPrivateFlags2 &= ~View.DRAG_MASK; 20967 refreshDrawableState(); 20968 } break; 20969 } 20970 20971 return result; 20972 } 20973 20974 boolean canAcceptDrag() { 20975 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20976 } 20977 20978 /** 20979 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20980 * it is ever exposed at all. 20981 * @hide 20982 */ 20983 public void onCloseSystemDialogs(String reason) { 20984 } 20985 20986 /** 20987 * Given a Drawable whose bounds have been set to draw into this view, 20988 * update a Region being computed for 20989 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20990 * that any non-transparent parts of the Drawable are removed from the 20991 * given transparent region. 20992 * 20993 * @param dr The Drawable whose transparency is to be applied to the region. 20994 * @param region A Region holding the current transparency information, 20995 * where any parts of the region that are set are considered to be 20996 * transparent. On return, this region will be modified to have the 20997 * transparency information reduced by the corresponding parts of the 20998 * Drawable that are not transparent. 20999 * {@hide} 21000 */ 21001 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 21002 if (DBG) { 21003 Log.i("View", "Getting transparent region for: " + this); 21004 } 21005 final Region r = dr.getTransparentRegion(); 21006 final Rect db = dr.getBounds(); 21007 final AttachInfo attachInfo = mAttachInfo; 21008 if (r != null && attachInfo != null) { 21009 final int w = getRight()-getLeft(); 21010 final int h = getBottom()-getTop(); 21011 if (db.left > 0) { 21012 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 21013 r.op(0, 0, db.left, h, Region.Op.UNION); 21014 } 21015 if (db.right < w) { 21016 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 21017 r.op(db.right, 0, w, h, Region.Op.UNION); 21018 } 21019 if (db.top > 0) { 21020 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 21021 r.op(0, 0, w, db.top, Region.Op.UNION); 21022 } 21023 if (db.bottom < h) { 21024 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 21025 r.op(0, db.bottom, w, h, Region.Op.UNION); 21026 } 21027 final int[] location = attachInfo.mTransparentLocation; 21028 getLocationInWindow(location); 21029 r.translate(location[0], location[1]); 21030 region.op(r, Region.Op.INTERSECT); 21031 } else { 21032 region.op(db, Region.Op.DIFFERENCE); 21033 } 21034 } 21035 21036 private void checkForLongClick(int delayOffset, float x, float y) { 21037 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 21038 mHasPerformedLongPress = false; 21039 21040 if (mPendingCheckForLongPress == null) { 21041 mPendingCheckForLongPress = new CheckForLongPress(); 21042 } 21043 mPendingCheckForLongPress.setAnchor(x, y); 21044 mPendingCheckForLongPress.rememberWindowAttachCount(); 21045 postDelayed(mPendingCheckForLongPress, 21046 ViewConfiguration.getLongPressTimeout() - delayOffset); 21047 } 21048 } 21049 21050 /** 21051 * Inflate a view from an XML resource. This convenience method wraps the {@link 21052 * LayoutInflater} class, which provides a full range of options for view inflation. 21053 * 21054 * @param context The Context object for your activity or application. 21055 * @param resource The resource ID to inflate 21056 * @param root A view group that will be the parent. Used to properly inflate the 21057 * layout_* parameters. 21058 * @see LayoutInflater 21059 */ 21060 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 21061 LayoutInflater factory = LayoutInflater.from(context); 21062 return factory.inflate(resource, root); 21063 } 21064 21065 /** 21066 * Scroll the view with standard behavior for scrolling beyond the normal 21067 * content boundaries. Views that call this method should override 21068 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 21069 * results of an over-scroll operation. 21070 * 21071 * Views can use this method to handle any touch or fling-based scrolling. 21072 * 21073 * @param deltaX Change in X in pixels 21074 * @param deltaY Change in Y in pixels 21075 * @param scrollX Current X scroll value in pixels before applying deltaX 21076 * @param scrollY Current Y scroll value in pixels before applying deltaY 21077 * @param scrollRangeX Maximum content scroll range along the X axis 21078 * @param scrollRangeY Maximum content scroll range along the Y axis 21079 * @param maxOverScrollX Number of pixels to overscroll by in either direction 21080 * along the X axis. 21081 * @param maxOverScrollY Number of pixels to overscroll by in either direction 21082 * along the Y axis. 21083 * @param isTouchEvent true if this scroll operation is the result of a touch event. 21084 * @return true if scrolling was clamped to an over-scroll boundary along either 21085 * axis, false otherwise. 21086 */ 21087 @SuppressWarnings({"UnusedParameters"}) 21088 protected boolean overScrollBy(int deltaX, int deltaY, 21089 int scrollX, int scrollY, 21090 int scrollRangeX, int scrollRangeY, 21091 int maxOverScrollX, int maxOverScrollY, 21092 boolean isTouchEvent) { 21093 final int overScrollMode = mOverScrollMode; 21094 final boolean canScrollHorizontal = 21095 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 21096 final boolean canScrollVertical = 21097 computeVerticalScrollRange() > computeVerticalScrollExtent(); 21098 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 21099 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 21100 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 21101 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 21102 21103 int newScrollX = scrollX + deltaX; 21104 if (!overScrollHorizontal) { 21105 maxOverScrollX = 0; 21106 } 21107 21108 int newScrollY = scrollY + deltaY; 21109 if (!overScrollVertical) { 21110 maxOverScrollY = 0; 21111 } 21112 21113 // Clamp values if at the limits and record 21114 final int left = -maxOverScrollX; 21115 final int right = maxOverScrollX + scrollRangeX; 21116 final int top = -maxOverScrollY; 21117 final int bottom = maxOverScrollY + scrollRangeY; 21118 21119 boolean clampedX = false; 21120 if (newScrollX > right) { 21121 newScrollX = right; 21122 clampedX = true; 21123 } else if (newScrollX < left) { 21124 newScrollX = left; 21125 clampedX = true; 21126 } 21127 21128 boolean clampedY = false; 21129 if (newScrollY > bottom) { 21130 newScrollY = bottom; 21131 clampedY = true; 21132 } else if (newScrollY < top) { 21133 newScrollY = top; 21134 clampedY = true; 21135 } 21136 21137 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 21138 21139 return clampedX || clampedY; 21140 } 21141 21142 /** 21143 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 21144 * respond to the results of an over-scroll operation. 21145 * 21146 * @param scrollX New X scroll value in pixels 21147 * @param scrollY New Y scroll value in pixels 21148 * @param clampedX True if scrollX was clamped to an over-scroll boundary 21149 * @param clampedY True if scrollY was clamped to an over-scroll boundary 21150 */ 21151 protected void onOverScrolled(int scrollX, int scrollY, 21152 boolean clampedX, boolean clampedY) { 21153 // Intentionally empty. 21154 } 21155 21156 /** 21157 * Returns the over-scroll mode for this view. The result will be 21158 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21159 * (allow over-scrolling only if the view content is larger than the container), 21160 * or {@link #OVER_SCROLL_NEVER}. 21161 * 21162 * @return This view's over-scroll mode. 21163 */ 21164 public int getOverScrollMode() { 21165 return mOverScrollMode; 21166 } 21167 21168 /** 21169 * Set the over-scroll mode for this view. Valid over-scroll modes are 21170 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 21171 * (allow over-scrolling only if the view content is larger than the container), 21172 * or {@link #OVER_SCROLL_NEVER}. 21173 * 21174 * Setting the over-scroll mode of a view will have an effect only if the 21175 * view is capable of scrolling. 21176 * 21177 * @param overScrollMode The new over-scroll mode for this view. 21178 */ 21179 public void setOverScrollMode(int overScrollMode) { 21180 if (overScrollMode != OVER_SCROLL_ALWAYS && 21181 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 21182 overScrollMode != OVER_SCROLL_NEVER) { 21183 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 21184 } 21185 mOverScrollMode = overScrollMode; 21186 } 21187 21188 /** 21189 * Enable or disable nested scrolling for this view. 21190 * 21191 * <p>If this property is set to true the view will be permitted to initiate nested 21192 * scrolling operations with a compatible parent view in the current hierarchy. If this 21193 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 21194 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 21195 * the nested scroll.</p> 21196 * 21197 * @param enabled true to enable nested scrolling, false to disable 21198 * 21199 * @see #isNestedScrollingEnabled() 21200 */ 21201 public void setNestedScrollingEnabled(boolean enabled) { 21202 if (enabled) { 21203 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 21204 } else { 21205 stopNestedScroll(); 21206 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 21207 } 21208 } 21209 21210 /** 21211 * Returns true if nested scrolling is enabled for this view. 21212 * 21213 * <p>If nested scrolling is enabled and this View class implementation supports it, 21214 * this view will act as a nested scrolling child view when applicable, forwarding data 21215 * about the scroll operation in progress to a compatible and cooperating nested scrolling 21216 * parent.</p> 21217 * 21218 * @return true if nested scrolling is enabled 21219 * 21220 * @see #setNestedScrollingEnabled(boolean) 21221 */ 21222 public boolean isNestedScrollingEnabled() { 21223 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 21224 PFLAG3_NESTED_SCROLLING_ENABLED; 21225 } 21226 21227 /** 21228 * Begin a nestable scroll operation along the given axes. 21229 * 21230 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 21231 * 21232 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 21233 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 21234 * In the case of touch scrolling the nested scroll will be terminated automatically in 21235 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 21236 * In the event of programmatic scrolling the caller must explicitly call 21237 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 21238 * 21239 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21240 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21241 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21242 * 21243 * <p>At each incremental step of the scroll the caller should invoke 21244 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21245 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21246 * parent at least partially consumed the scroll and the caller should adjust the amount it 21247 * scrolls by.</p> 21248 * 21249 * <p>After applying the remainder of the scroll delta the caller should invoke 21250 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21251 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21252 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21253 * </p> 21254 * 21255 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21256 * {@link #SCROLL_AXIS_VERTICAL}. 21257 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21258 * the current gesture. 21259 * 21260 * @see #stopNestedScroll() 21261 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21262 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21263 */ 21264 public boolean startNestedScroll(int axes) { 21265 if (hasNestedScrollingParent()) { 21266 // Already in progress 21267 return true; 21268 } 21269 if (isNestedScrollingEnabled()) { 21270 ViewParent p = getParent(); 21271 View child = this; 21272 while (p != null) { 21273 try { 21274 if (p.onStartNestedScroll(child, this, axes)) { 21275 mNestedScrollingParent = p; 21276 p.onNestedScrollAccepted(child, this, axes); 21277 return true; 21278 } 21279 } catch (AbstractMethodError e) { 21280 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21281 "method onStartNestedScroll", e); 21282 // Allow the search upward to continue 21283 } 21284 if (p instanceof View) { 21285 child = (View) p; 21286 } 21287 p = p.getParent(); 21288 } 21289 } 21290 return false; 21291 } 21292 21293 /** 21294 * Stop a nested scroll in progress. 21295 * 21296 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21297 * 21298 * @see #startNestedScroll(int) 21299 */ 21300 public void stopNestedScroll() { 21301 if (mNestedScrollingParent != null) { 21302 mNestedScrollingParent.onStopNestedScroll(this); 21303 mNestedScrollingParent = null; 21304 } 21305 } 21306 21307 /** 21308 * Returns true if this view has a nested scrolling parent. 21309 * 21310 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21311 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21312 * 21313 * @return whether this view has a nested scrolling parent 21314 */ 21315 public boolean hasNestedScrollingParent() { 21316 return mNestedScrollingParent != null; 21317 } 21318 21319 /** 21320 * Dispatch one step of a nested scroll in progress. 21321 * 21322 * <p>Implementations of views that support nested scrolling should call this to report 21323 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21324 * is not currently in progress or nested scrolling is not 21325 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21326 * 21327 * <p>Compatible View implementations should also call 21328 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21329 * consuming a component of the scroll event themselves.</p> 21330 * 21331 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21332 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21333 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21334 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21335 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21336 * in local view coordinates of this view from before this operation 21337 * to after it completes. View implementations may use this to adjust 21338 * expected input coordinate tracking. 21339 * @return true if the event was dispatched, false if it could not be dispatched. 21340 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21341 */ 21342 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21343 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21344 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21345 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21346 int startX = 0; 21347 int startY = 0; 21348 if (offsetInWindow != null) { 21349 getLocationInWindow(offsetInWindow); 21350 startX = offsetInWindow[0]; 21351 startY = offsetInWindow[1]; 21352 } 21353 21354 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21355 dxUnconsumed, dyUnconsumed); 21356 21357 if (offsetInWindow != null) { 21358 getLocationInWindow(offsetInWindow); 21359 offsetInWindow[0] -= startX; 21360 offsetInWindow[1] -= startY; 21361 } 21362 return true; 21363 } else if (offsetInWindow != null) { 21364 // No motion, no dispatch. Keep offsetInWindow up to date. 21365 offsetInWindow[0] = 0; 21366 offsetInWindow[1] = 0; 21367 } 21368 } 21369 return false; 21370 } 21371 21372 /** 21373 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21374 * 21375 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21376 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21377 * scrolling operation to consume some or all of the scroll operation before the child view 21378 * consumes it.</p> 21379 * 21380 * @param dx Horizontal scroll distance in pixels 21381 * @param dy Vertical scroll distance in pixels 21382 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21383 * and consumed[1] the consumed dy. 21384 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21385 * in local view coordinates of this view from before this operation 21386 * to after it completes. View implementations may use this to adjust 21387 * expected input coordinate tracking. 21388 * @return true if the parent consumed some or all of the scroll delta 21389 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21390 */ 21391 public boolean dispatchNestedPreScroll(int dx, int dy, 21392 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21393 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21394 if (dx != 0 || dy != 0) { 21395 int startX = 0; 21396 int startY = 0; 21397 if (offsetInWindow != null) { 21398 getLocationInWindow(offsetInWindow); 21399 startX = offsetInWindow[0]; 21400 startY = offsetInWindow[1]; 21401 } 21402 21403 if (consumed == null) { 21404 if (mTempNestedScrollConsumed == null) { 21405 mTempNestedScrollConsumed = new int[2]; 21406 } 21407 consumed = mTempNestedScrollConsumed; 21408 } 21409 consumed[0] = 0; 21410 consumed[1] = 0; 21411 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21412 21413 if (offsetInWindow != null) { 21414 getLocationInWindow(offsetInWindow); 21415 offsetInWindow[0] -= startX; 21416 offsetInWindow[1] -= startY; 21417 } 21418 return consumed[0] != 0 || consumed[1] != 0; 21419 } else if (offsetInWindow != null) { 21420 offsetInWindow[0] = 0; 21421 offsetInWindow[1] = 0; 21422 } 21423 } 21424 return false; 21425 } 21426 21427 /** 21428 * Dispatch a fling to a nested scrolling parent. 21429 * 21430 * <p>This method should be used to indicate that a nested scrolling child has detected 21431 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21432 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21433 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21434 * along a scrollable axis.</p> 21435 * 21436 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21437 * its own content, it can use this method to delegate the fling to its nested scrolling 21438 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21439 * 21440 * @param velocityX Horizontal fling velocity in pixels per second 21441 * @param velocityY Vertical fling velocity in pixels per second 21442 * @param consumed true if the child consumed the fling, false otherwise 21443 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21444 */ 21445 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21446 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21447 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21448 } 21449 return false; 21450 } 21451 21452 /** 21453 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21454 * 21455 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21456 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21457 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21458 * before the child view consumes it. If this method returns <code>true</code>, a nested 21459 * parent view consumed the fling and this view should not scroll as a result.</p> 21460 * 21461 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21462 * the fling at a time. If a parent view consumed the fling this method will return false. 21463 * Custom view implementations should account for this in two ways:</p> 21464 * 21465 * <ul> 21466 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21467 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21468 * position regardless.</li> 21469 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21470 * even to settle back to a valid idle position.</li> 21471 * </ul> 21472 * 21473 * <p>Views should also not offer fling velocities to nested parent views along an axis 21474 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21475 * should not offer a horizontal fling velocity to its parents since scrolling along that 21476 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21477 * 21478 * @param velocityX Horizontal fling velocity in pixels per second 21479 * @param velocityY Vertical fling velocity in pixels per second 21480 * @return true if a nested scrolling parent consumed the fling 21481 */ 21482 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21483 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21484 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21485 } 21486 return false; 21487 } 21488 21489 /** 21490 * Gets a scale factor that determines the distance the view should scroll 21491 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21492 * @return The vertical scroll scale factor. 21493 * @hide 21494 */ 21495 protected float getVerticalScrollFactor() { 21496 if (mVerticalScrollFactor == 0) { 21497 TypedValue outValue = new TypedValue(); 21498 if (!mContext.getTheme().resolveAttribute( 21499 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21500 throw new IllegalStateException( 21501 "Expected theme to define listPreferredItemHeight."); 21502 } 21503 mVerticalScrollFactor = outValue.getDimension( 21504 mContext.getResources().getDisplayMetrics()); 21505 } 21506 return mVerticalScrollFactor; 21507 } 21508 21509 /** 21510 * Gets a scale factor that determines the distance the view should scroll 21511 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21512 * @return The horizontal scroll scale factor. 21513 * @hide 21514 */ 21515 protected float getHorizontalScrollFactor() { 21516 // TODO: Should use something else. 21517 return getVerticalScrollFactor(); 21518 } 21519 21520 /** 21521 * Return the value specifying the text direction or policy that was set with 21522 * {@link #setTextDirection(int)}. 21523 * 21524 * @return the defined text direction. It can be one of: 21525 * 21526 * {@link #TEXT_DIRECTION_INHERIT}, 21527 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21528 * {@link #TEXT_DIRECTION_ANY_RTL}, 21529 * {@link #TEXT_DIRECTION_LTR}, 21530 * {@link #TEXT_DIRECTION_RTL}, 21531 * {@link #TEXT_DIRECTION_LOCALE}, 21532 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21533 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21534 * 21535 * @attr ref android.R.styleable#View_textDirection 21536 * 21537 * @hide 21538 */ 21539 @ViewDebug.ExportedProperty(category = "text", mapping = { 21540 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21541 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21542 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21543 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21544 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21545 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21546 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21547 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21548 }) 21549 public int getRawTextDirection() { 21550 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21551 } 21552 21553 /** 21554 * Set the text direction. 21555 * 21556 * @param textDirection the direction to set. Should be one of: 21557 * 21558 * {@link #TEXT_DIRECTION_INHERIT}, 21559 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21560 * {@link #TEXT_DIRECTION_ANY_RTL}, 21561 * {@link #TEXT_DIRECTION_LTR}, 21562 * {@link #TEXT_DIRECTION_RTL}, 21563 * {@link #TEXT_DIRECTION_LOCALE} 21564 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21565 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21566 * 21567 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21568 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21569 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21570 * 21571 * @attr ref android.R.styleable#View_textDirection 21572 */ 21573 public void setTextDirection(int textDirection) { 21574 if (getRawTextDirection() != textDirection) { 21575 // Reset the current text direction and the resolved one 21576 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21577 resetResolvedTextDirection(); 21578 // Set the new text direction 21579 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21580 // Do resolution 21581 resolveTextDirection(); 21582 // Notify change 21583 onRtlPropertiesChanged(getLayoutDirection()); 21584 // Refresh 21585 requestLayout(); 21586 invalidate(true); 21587 } 21588 } 21589 21590 /** 21591 * Return the resolved text direction. 21592 * 21593 * @return the resolved text direction. Returns one of: 21594 * 21595 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21596 * {@link #TEXT_DIRECTION_ANY_RTL}, 21597 * {@link #TEXT_DIRECTION_LTR}, 21598 * {@link #TEXT_DIRECTION_RTL}, 21599 * {@link #TEXT_DIRECTION_LOCALE}, 21600 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21601 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21602 * 21603 * @attr ref android.R.styleable#View_textDirection 21604 */ 21605 @ViewDebug.ExportedProperty(category = "text", mapping = { 21606 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21607 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21608 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21609 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21610 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21611 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21612 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21613 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21614 }) 21615 public int getTextDirection() { 21616 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21617 } 21618 21619 /** 21620 * Resolve the text direction. 21621 * 21622 * @return true if resolution has been done, false otherwise. 21623 * 21624 * @hide 21625 */ 21626 public boolean resolveTextDirection() { 21627 // Reset any previous text direction resolution 21628 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21629 21630 if (hasRtlSupport()) { 21631 // Set resolved text direction flag depending on text direction flag 21632 final int textDirection = getRawTextDirection(); 21633 switch(textDirection) { 21634 case TEXT_DIRECTION_INHERIT: 21635 if (!canResolveTextDirection()) { 21636 // We cannot do the resolution if there is no parent, so use the default one 21637 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21638 // Resolution will need to happen again later 21639 return false; 21640 } 21641 21642 // Parent has not yet resolved, so we still return the default 21643 try { 21644 if (!mParent.isTextDirectionResolved()) { 21645 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21646 // Resolution will need to happen again later 21647 return false; 21648 } 21649 } catch (AbstractMethodError e) { 21650 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21651 " does not fully implement ViewParent", e); 21652 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21653 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21654 return true; 21655 } 21656 21657 // Set current resolved direction to the same value as the parent's one 21658 int parentResolvedDirection; 21659 try { 21660 parentResolvedDirection = mParent.getTextDirection(); 21661 } catch (AbstractMethodError e) { 21662 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21663 " does not fully implement ViewParent", e); 21664 parentResolvedDirection = TEXT_DIRECTION_LTR; 21665 } 21666 switch (parentResolvedDirection) { 21667 case TEXT_DIRECTION_FIRST_STRONG: 21668 case TEXT_DIRECTION_ANY_RTL: 21669 case TEXT_DIRECTION_LTR: 21670 case TEXT_DIRECTION_RTL: 21671 case TEXT_DIRECTION_LOCALE: 21672 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21673 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21674 mPrivateFlags2 |= 21675 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21676 break; 21677 default: 21678 // Default resolved direction is "first strong" heuristic 21679 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21680 } 21681 break; 21682 case TEXT_DIRECTION_FIRST_STRONG: 21683 case TEXT_DIRECTION_ANY_RTL: 21684 case TEXT_DIRECTION_LTR: 21685 case TEXT_DIRECTION_RTL: 21686 case TEXT_DIRECTION_LOCALE: 21687 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21688 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21689 // Resolved direction is the same as text direction 21690 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21691 break; 21692 default: 21693 // Default resolved direction is "first strong" heuristic 21694 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21695 } 21696 } else { 21697 // Default resolved direction is "first strong" heuristic 21698 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21699 } 21700 21701 // Set to resolved 21702 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21703 return true; 21704 } 21705 21706 /** 21707 * Check if text direction resolution can be done. 21708 * 21709 * @return true if text direction resolution can be done otherwise return false. 21710 */ 21711 public boolean canResolveTextDirection() { 21712 switch (getRawTextDirection()) { 21713 case TEXT_DIRECTION_INHERIT: 21714 if (mParent != null) { 21715 try { 21716 return mParent.canResolveTextDirection(); 21717 } catch (AbstractMethodError e) { 21718 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21719 " does not fully implement ViewParent", e); 21720 } 21721 } 21722 return false; 21723 21724 default: 21725 return true; 21726 } 21727 } 21728 21729 /** 21730 * Reset resolved text direction. Text direction will be resolved during a call to 21731 * {@link #onMeasure(int, int)}. 21732 * 21733 * @hide 21734 */ 21735 public void resetResolvedTextDirection() { 21736 // Reset any previous text direction resolution 21737 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21738 // Set to default value 21739 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21740 } 21741 21742 /** 21743 * @return true if text direction is inherited. 21744 * 21745 * @hide 21746 */ 21747 public boolean isTextDirectionInherited() { 21748 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21749 } 21750 21751 /** 21752 * @return true if text direction is resolved. 21753 */ 21754 public boolean isTextDirectionResolved() { 21755 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21756 } 21757 21758 /** 21759 * Return the value specifying the text alignment or policy that was set with 21760 * {@link #setTextAlignment(int)}. 21761 * 21762 * @return the defined text alignment. It can be one of: 21763 * 21764 * {@link #TEXT_ALIGNMENT_INHERIT}, 21765 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21766 * {@link #TEXT_ALIGNMENT_CENTER}, 21767 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21768 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21769 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21770 * {@link #TEXT_ALIGNMENT_VIEW_END} 21771 * 21772 * @attr ref android.R.styleable#View_textAlignment 21773 * 21774 * @hide 21775 */ 21776 @ViewDebug.ExportedProperty(category = "text", mapping = { 21777 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21778 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21779 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21780 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21781 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21782 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21783 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21784 }) 21785 @TextAlignment 21786 public int getRawTextAlignment() { 21787 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21788 } 21789 21790 /** 21791 * Set the text alignment. 21792 * 21793 * @param textAlignment The text alignment to set. Should be one of 21794 * 21795 * {@link #TEXT_ALIGNMENT_INHERIT}, 21796 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21797 * {@link #TEXT_ALIGNMENT_CENTER}, 21798 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21799 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21800 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21801 * {@link #TEXT_ALIGNMENT_VIEW_END} 21802 * 21803 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21804 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21805 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21806 * 21807 * @attr ref android.R.styleable#View_textAlignment 21808 */ 21809 public void setTextAlignment(@TextAlignment int textAlignment) { 21810 if (textAlignment != getRawTextAlignment()) { 21811 // Reset the current and resolved text alignment 21812 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21813 resetResolvedTextAlignment(); 21814 // Set the new text alignment 21815 mPrivateFlags2 |= 21816 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21817 // Do resolution 21818 resolveTextAlignment(); 21819 // Notify change 21820 onRtlPropertiesChanged(getLayoutDirection()); 21821 // Refresh 21822 requestLayout(); 21823 invalidate(true); 21824 } 21825 } 21826 21827 /** 21828 * Return the resolved text alignment. 21829 * 21830 * @return the resolved text alignment. Returns one of: 21831 * 21832 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21833 * {@link #TEXT_ALIGNMENT_CENTER}, 21834 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21835 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21836 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21837 * {@link #TEXT_ALIGNMENT_VIEW_END} 21838 * 21839 * @attr ref android.R.styleable#View_textAlignment 21840 */ 21841 @ViewDebug.ExportedProperty(category = "text", mapping = { 21842 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21843 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21844 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21845 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21846 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21847 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21848 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21849 }) 21850 @TextAlignment 21851 public int getTextAlignment() { 21852 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21853 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21854 } 21855 21856 /** 21857 * Resolve the text alignment. 21858 * 21859 * @return true if resolution has been done, false otherwise. 21860 * 21861 * @hide 21862 */ 21863 public boolean resolveTextAlignment() { 21864 // Reset any previous text alignment resolution 21865 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21866 21867 if (hasRtlSupport()) { 21868 // Set resolved text alignment flag depending on text alignment flag 21869 final int textAlignment = getRawTextAlignment(); 21870 switch (textAlignment) { 21871 case TEXT_ALIGNMENT_INHERIT: 21872 // Check if we can resolve the text alignment 21873 if (!canResolveTextAlignment()) { 21874 // We cannot do the resolution if there is no parent so use the default 21875 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21876 // Resolution will need to happen again later 21877 return false; 21878 } 21879 21880 // Parent has not yet resolved, so we still return the default 21881 try { 21882 if (!mParent.isTextAlignmentResolved()) { 21883 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21884 // Resolution will need to happen again later 21885 return false; 21886 } 21887 } catch (AbstractMethodError e) { 21888 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21889 " does not fully implement ViewParent", e); 21890 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21891 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21892 return true; 21893 } 21894 21895 int parentResolvedTextAlignment; 21896 try { 21897 parentResolvedTextAlignment = mParent.getTextAlignment(); 21898 } catch (AbstractMethodError e) { 21899 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21900 " does not fully implement ViewParent", e); 21901 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21902 } 21903 switch (parentResolvedTextAlignment) { 21904 case TEXT_ALIGNMENT_GRAVITY: 21905 case TEXT_ALIGNMENT_TEXT_START: 21906 case TEXT_ALIGNMENT_TEXT_END: 21907 case TEXT_ALIGNMENT_CENTER: 21908 case TEXT_ALIGNMENT_VIEW_START: 21909 case TEXT_ALIGNMENT_VIEW_END: 21910 // Resolved text alignment is the same as the parent resolved 21911 // text alignment 21912 mPrivateFlags2 |= 21913 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21914 break; 21915 default: 21916 // Use default resolved text alignment 21917 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21918 } 21919 break; 21920 case TEXT_ALIGNMENT_GRAVITY: 21921 case TEXT_ALIGNMENT_TEXT_START: 21922 case TEXT_ALIGNMENT_TEXT_END: 21923 case TEXT_ALIGNMENT_CENTER: 21924 case TEXT_ALIGNMENT_VIEW_START: 21925 case TEXT_ALIGNMENT_VIEW_END: 21926 // Resolved text alignment is the same as text alignment 21927 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21928 break; 21929 default: 21930 // Use default resolved text alignment 21931 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21932 } 21933 } else { 21934 // Use default resolved text alignment 21935 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21936 } 21937 21938 // Set the resolved 21939 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21940 return true; 21941 } 21942 21943 /** 21944 * Check if text alignment resolution can be done. 21945 * 21946 * @return true if text alignment resolution can be done otherwise return false. 21947 */ 21948 public boolean canResolveTextAlignment() { 21949 switch (getRawTextAlignment()) { 21950 case TEXT_DIRECTION_INHERIT: 21951 if (mParent != null) { 21952 try { 21953 return mParent.canResolveTextAlignment(); 21954 } catch (AbstractMethodError e) { 21955 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21956 " does not fully implement ViewParent", e); 21957 } 21958 } 21959 return false; 21960 21961 default: 21962 return true; 21963 } 21964 } 21965 21966 /** 21967 * Reset resolved text alignment. Text alignment will be resolved during a call to 21968 * {@link #onMeasure(int, int)}. 21969 * 21970 * @hide 21971 */ 21972 public void resetResolvedTextAlignment() { 21973 // Reset any previous text alignment resolution 21974 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21975 // Set to default 21976 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21977 } 21978 21979 /** 21980 * @return true if text alignment is inherited. 21981 * 21982 * @hide 21983 */ 21984 public boolean isTextAlignmentInherited() { 21985 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21986 } 21987 21988 /** 21989 * @return true if text alignment is resolved. 21990 */ 21991 public boolean isTextAlignmentResolved() { 21992 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21993 } 21994 21995 /** 21996 * Generate a value suitable for use in {@link #setId(int)}. 21997 * This value will not collide with ID values generated at build time by aapt for R.id. 21998 * 21999 * @return a generated ID value 22000 */ 22001 public static int generateViewId() { 22002 for (;;) { 22003 final int result = sNextGeneratedId.get(); 22004 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 22005 int newValue = result + 1; 22006 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 22007 if (sNextGeneratedId.compareAndSet(result, newValue)) { 22008 return result; 22009 } 22010 } 22011 } 22012 22013 /** 22014 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 22015 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 22016 * a normal View or a ViewGroup with 22017 * {@link android.view.ViewGroup#isTransitionGroup()} true. 22018 * @hide 22019 */ 22020 public void captureTransitioningViews(List<View> transitioningViews) { 22021 if (getVisibility() == View.VISIBLE) { 22022 transitioningViews.add(this); 22023 } 22024 } 22025 22026 /** 22027 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 22028 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 22029 * @hide 22030 */ 22031 public void findNamedViews(Map<String, View> namedElements) { 22032 if (getVisibility() == VISIBLE || mGhostView != null) { 22033 String transitionName = getTransitionName(); 22034 if (transitionName != null) { 22035 namedElements.put(transitionName, this); 22036 } 22037 } 22038 } 22039 22040 /** 22041 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 22042 * The default implementation does not care the location or event types, but some subclasses 22043 * may use it (such as WebViews). 22044 * @param event The MotionEvent from a mouse 22045 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 22046 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 22047 * @see PointerIcon 22048 */ 22049 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 22050 final float x = event.getX(pointerIndex); 22051 final float y = event.getY(pointerIndex); 22052 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 22053 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 22054 } 22055 return mPointerIcon; 22056 } 22057 22058 /** 22059 * Set the pointer icon for the current view. 22060 * Passing {@code null} will restore the pointer icon to its default value. 22061 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 22062 */ 22063 public void setPointerIcon(PointerIcon pointerIcon) { 22064 mPointerIcon = pointerIcon; 22065 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 22066 return; 22067 } 22068 try { 22069 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 22070 } catch (RemoteException e) { 22071 } 22072 } 22073 22074 /** 22075 * Gets the pointer icon for the current view. 22076 */ 22077 public PointerIcon getPointerIcon() { 22078 return mPointerIcon; 22079 } 22080 22081 // 22082 // Properties 22083 // 22084 /** 22085 * A Property wrapper around the <code>alpha</code> functionality handled by the 22086 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 22087 */ 22088 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 22089 @Override 22090 public void setValue(View object, float value) { 22091 object.setAlpha(value); 22092 } 22093 22094 @Override 22095 public Float get(View object) { 22096 return object.getAlpha(); 22097 } 22098 }; 22099 22100 /** 22101 * A Property wrapper around the <code>translationX</code> functionality handled by the 22102 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 22103 */ 22104 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 22105 @Override 22106 public void setValue(View object, float value) { 22107 object.setTranslationX(value); 22108 } 22109 22110 @Override 22111 public Float get(View object) { 22112 return object.getTranslationX(); 22113 } 22114 }; 22115 22116 /** 22117 * A Property wrapper around the <code>translationY</code> functionality handled by the 22118 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 22119 */ 22120 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 22121 @Override 22122 public void setValue(View object, float value) { 22123 object.setTranslationY(value); 22124 } 22125 22126 @Override 22127 public Float get(View object) { 22128 return object.getTranslationY(); 22129 } 22130 }; 22131 22132 /** 22133 * A Property wrapper around the <code>translationZ</code> functionality handled by the 22134 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 22135 */ 22136 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 22137 @Override 22138 public void setValue(View object, float value) { 22139 object.setTranslationZ(value); 22140 } 22141 22142 @Override 22143 public Float get(View object) { 22144 return object.getTranslationZ(); 22145 } 22146 }; 22147 22148 /** 22149 * A Property wrapper around the <code>x</code> functionality handled by the 22150 * {@link View#setX(float)} and {@link View#getX()} methods. 22151 */ 22152 public static final Property<View, Float> X = new FloatProperty<View>("x") { 22153 @Override 22154 public void setValue(View object, float value) { 22155 object.setX(value); 22156 } 22157 22158 @Override 22159 public Float get(View object) { 22160 return object.getX(); 22161 } 22162 }; 22163 22164 /** 22165 * A Property wrapper around the <code>y</code> functionality handled by the 22166 * {@link View#setY(float)} and {@link View#getY()} methods. 22167 */ 22168 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 22169 @Override 22170 public void setValue(View object, float value) { 22171 object.setY(value); 22172 } 22173 22174 @Override 22175 public Float get(View object) { 22176 return object.getY(); 22177 } 22178 }; 22179 22180 /** 22181 * A Property wrapper around the <code>z</code> functionality handled by the 22182 * {@link View#setZ(float)} and {@link View#getZ()} methods. 22183 */ 22184 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 22185 @Override 22186 public void setValue(View object, float value) { 22187 object.setZ(value); 22188 } 22189 22190 @Override 22191 public Float get(View object) { 22192 return object.getZ(); 22193 } 22194 }; 22195 22196 /** 22197 * A Property wrapper around the <code>rotation</code> functionality handled by the 22198 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22199 */ 22200 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22201 @Override 22202 public void setValue(View object, float value) { 22203 object.setRotation(value); 22204 } 22205 22206 @Override 22207 public Float get(View object) { 22208 return object.getRotation(); 22209 } 22210 }; 22211 22212 /** 22213 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22214 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22215 */ 22216 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22217 @Override 22218 public void setValue(View object, float value) { 22219 object.setRotationX(value); 22220 } 22221 22222 @Override 22223 public Float get(View object) { 22224 return object.getRotationX(); 22225 } 22226 }; 22227 22228 /** 22229 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22230 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22231 */ 22232 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22233 @Override 22234 public void setValue(View object, float value) { 22235 object.setRotationY(value); 22236 } 22237 22238 @Override 22239 public Float get(View object) { 22240 return object.getRotationY(); 22241 } 22242 }; 22243 22244 /** 22245 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22246 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22247 */ 22248 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22249 @Override 22250 public void setValue(View object, float value) { 22251 object.setScaleX(value); 22252 } 22253 22254 @Override 22255 public Float get(View object) { 22256 return object.getScaleX(); 22257 } 22258 }; 22259 22260 /** 22261 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22262 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22263 */ 22264 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22265 @Override 22266 public void setValue(View object, float value) { 22267 object.setScaleY(value); 22268 } 22269 22270 @Override 22271 public Float get(View object) { 22272 return object.getScaleY(); 22273 } 22274 }; 22275 22276 /** 22277 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22278 * Each MeasureSpec represents a requirement for either the width or the height. 22279 * A MeasureSpec is comprised of a size and a mode. There are three possible 22280 * modes: 22281 * <dl> 22282 * <dt>UNSPECIFIED</dt> 22283 * <dd> 22284 * The parent has not imposed any constraint on the child. It can be whatever size 22285 * it wants. 22286 * </dd> 22287 * 22288 * <dt>EXACTLY</dt> 22289 * <dd> 22290 * The parent has determined an exact size for the child. The child is going to be 22291 * given those bounds regardless of how big it wants to be. 22292 * </dd> 22293 * 22294 * <dt>AT_MOST</dt> 22295 * <dd> 22296 * The child can be as large as it wants up to the specified size. 22297 * </dd> 22298 * </dl> 22299 * 22300 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22301 * is provided to pack and unpack the <size, mode> tuple into the int. 22302 */ 22303 public static class MeasureSpec { 22304 private static final int MODE_SHIFT = 30; 22305 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22306 22307 /** @hide */ 22308 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22309 @Retention(RetentionPolicy.SOURCE) 22310 public @interface MeasureSpecMode {} 22311 22312 /** 22313 * Measure specification mode: The parent has not imposed any constraint 22314 * on the child. It can be whatever size it wants. 22315 */ 22316 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22317 22318 /** 22319 * Measure specification mode: The parent has determined an exact size 22320 * for the child. The child is going to be given those bounds regardless 22321 * of how big it wants to be. 22322 */ 22323 public static final int EXACTLY = 1 << MODE_SHIFT; 22324 22325 /** 22326 * Measure specification mode: The child can be as large as it wants up 22327 * to the specified size. 22328 */ 22329 public static final int AT_MOST = 2 << MODE_SHIFT; 22330 22331 /** 22332 * Creates a measure specification based on the supplied size and mode. 22333 * 22334 * The mode must always be one of the following: 22335 * <ul> 22336 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22337 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22338 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22339 * </ul> 22340 * 22341 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22342 * implementation was such that the order of arguments did not matter 22343 * and overflow in either value could impact the resulting MeasureSpec. 22344 * {@link android.widget.RelativeLayout} was affected by this bug. 22345 * Apps targeting API levels greater than 17 will get the fixed, more strict 22346 * behavior.</p> 22347 * 22348 * @param size the size of the measure specification 22349 * @param mode the mode of the measure specification 22350 * @return the measure specification based on size and mode 22351 */ 22352 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22353 @MeasureSpecMode int mode) { 22354 if (sUseBrokenMakeMeasureSpec) { 22355 return size + mode; 22356 } else { 22357 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22358 } 22359 } 22360 22361 /** 22362 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22363 * will automatically get a size of 0. Older apps expect this. 22364 * 22365 * @hide internal use only for compatibility with system widgets and older apps 22366 */ 22367 public static int makeSafeMeasureSpec(int size, int mode) { 22368 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22369 return 0; 22370 } 22371 return makeMeasureSpec(size, mode); 22372 } 22373 22374 /** 22375 * Extracts the mode from the supplied measure specification. 22376 * 22377 * @param measureSpec the measure specification to extract the mode from 22378 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22379 * {@link android.view.View.MeasureSpec#AT_MOST} or 22380 * {@link android.view.View.MeasureSpec#EXACTLY} 22381 */ 22382 @MeasureSpecMode 22383 public static int getMode(int measureSpec) { 22384 //noinspection ResourceType 22385 return (measureSpec & MODE_MASK); 22386 } 22387 22388 /** 22389 * Extracts the size from the supplied measure specification. 22390 * 22391 * @param measureSpec the measure specification to extract the size from 22392 * @return the size in pixels defined in the supplied measure specification 22393 */ 22394 public static int getSize(int measureSpec) { 22395 return (measureSpec & ~MODE_MASK); 22396 } 22397 22398 static int adjust(int measureSpec, int delta) { 22399 final int mode = getMode(measureSpec); 22400 int size = getSize(measureSpec); 22401 if (mode == UNSPECIFIED) { 22402 // No need to adjust size for UNSPECIFIED mode. 22403 return makeMeasureSpec(size, UNSPECIFIED); 22404 } 22405 size += delta; 22406 if (size < 0) { 22407 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22408 ") spec: " + toString(measureSpec) + " delta: " + delta); 22409 size = 0; 22410 } 22411 return makeMeasureSpec(size, mode); 22412 } 22413 22414 /** 22415 * Returns a String representation of the specified measure 22416 * specification. 22417 * 22418 * @param measureSpec the measure specification to convert to a String 22419 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22420 */ 22421 public static String toString(int measureSpec) { 22422 int mode = getMode(measureSpec); 22423 int size = getSize(measureSpec); 22424 22425 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22426 22427 if (mode == UNSPECIFIED) 22428 sb.append("UNSPECIFIED "); 22429 else if (mode == EXACTLY) 22430 sb.append("EXACTLY "); 22431 else if (mode == AT_MOST) 22432 sb.append("AT_MOST "); 22433 else 22434 sb.append(mode).append(" "); 22435 22436 sb.append(size); 22437 return sb.toString(); 22438 } 22439 } 22440 22441 private final class CheckForLongPress implements Runnable { 22442 private int mOriginalWindowAttachCount; 22443 private float mX; 22444 private float mY; 22445 22446 @Override 22447 public void run() { 22448 if (isPressed() && (mParent != null) 22449 && mOriginalWindowAttachCount == mWindowAttachCount) { 22450 if (performLongClick(mX, mY)) { 22451 mHasPerformedLongPress = true; 22452 } 22453 } 22454 } 22455 22456 public void setAnchor(float x, float y) { 22457 mX = x; 22458 mY = y; 22459 } 22460 22461 public void rememberWindowAttachCount() { 22462 mOriginalWindowAttachCount = mWindowAttachCount; 22463 } 22464 } 22465 22466 private final class CheckForTap implements Runnable { 22467 public float x; 22468 public float y; 22469 22470 @Override 22471 public void run() { 22472 mPrivateFlags &= ~PFLAG_PREPRESSED; 22473 setPressed(true, x, y); 22474 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22475 } 22476 } 22477 22478 private final class PerformClick implements Runnable { 22479 @Override 22480 public void run() { 22481 performClick(); 22482 } 22483 } 22484 22485 /** 22486 * This method returns a ViewPropertyAnimator object, which can be used to animate 22487 * specific properties on this View. 22488 * 22489 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22490 */ 22491 public ViewPropertyAnimator animate() { 22492 if (mAnimator == null) { 22493 mAnimator = new ViewPropertyAnimator(this); 22494 } 22495 return mAnimator; 22496 } 22497 22498 /** 22499 * Sets the name of the View to be used to identify Views in Transitions. 22500 * Names should be unique in the View hierarchy. 22501 * 22502 * @param transitionName The name of the View to uniquely identify it for Transitions. 22503 */ 22504 public final void setTransitionName(String transitionName) { 22505 mTransitionName = transitionName; 22506 } 22507 22508 /** 22509 * Returns the name of the View to be used to identify Views in Transitions. 22510 * Names should be unique in the View hierarchy. 22511 * 22512 * <p>This returns null if the View has not been given a name.</p> 22513 * 22514 * @return The name used of the View to be used to identify Views in Transitions or null 22515 * if no name has been given. 22516 */ 22517 @ViewDebug.ExportedProperty 22518 public String getTransitionName() { 22519 return mTransitionName; 22520 } 22521 22522 /** 22523 * @hide 22524 */ 22525 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22526 // Do nothing. 22527 } 22528 22529 /** 22530 * Interface definition for a callback to be invoked when a hardware key event is 22531 * dispatched to this view. The callback will be invoked before the key event is 22532 * given to the view. This is only useful for hardware keyboards; a software input 22533 * method has no obligation to trigger this listener. 22534 */ 22535 public interface OnKeyListener { 22536 /** 22537 * Called when a hardware key is dispatched to a view. This allows listeners to 22538 * get a chance to respond before the target view. 22539 * <p>Key presses in software keyboards will generally NOT trigger this method, 22540 * although some may elect to do so in some situations. Do not assume a 22541 * software input method has to be key-based; even if it is, it may use key presses 22542 * in a different way than you expect, so there is no way to reliably catch soft 22543 * input key presses. 22544 * 22545 * @param v The view the key has been dispatched to. 22546 * @param keyCode The code for the physical key that was pressed 22547 * @param event The KeyEvent object containing full information about 22548 * the event. 22549 * @return True if the listener has consumed the event, false otherwise. 22550 */ 22551 boolean onKey(View v, int keyCode, KeyEvent event); 22552 } 22553 22554 /** 22555 * Interface definition for a callback to be invoked when a touch event is 22556 * dispatched to this view. The callback will be invoked before the touch 22557 * event is given to the view. 22558 */ 22559 public interface OnTouchListener { 22560 /** 22561 * Called when a touch event is dispatched to a view. This allows listeners to 22562 * get a chance to respond before the target view. 22563 * 22564 * @param v The view the touch event has been dispatched to. 22565 * @param event The MotionEvent object containing full information about 22566 * the event. 22567 * @return True if the listener has consumed the event, false otherwise. 22568 */ 22569 boolean onTouch(View v, MotionEvent event); 22570 } 22571 22572 /** 22573 * Interface definition for a callback to be invoked when a hover event is 22574 * dispatched to this view. The callback will be invoked before the hover 22575 * event is given to the view. 22576 */ 22577 public interface OnHoverListener { 22578 /** 22579 * Called when a hover event is dispatched to a view. This allows listeners to 22580 * get a chance to respond before the target view. 22581 * 22582 * @param v The view the hover event has been dispatched to. 22583 * @param event The MotionEvent object containing full information about 22584 * the event. 22585 * @return True if the listener has consumed the event, false otherwise. 22586 */ 22587 boolean onHover(View v, MotionEvent event); 22588 } 22589 22590 /** 22591 * Interface definition for a callback to be invoked when a generic motion event is 22592 * dispatched to this view. The callback will be invoked before the generic motion 22593 * event is given to the view. 22594 */ 22595 public interface OnGenericMotionListener { 22596 /** 22597 * Called when a generic motion event is dispatched to a view. This allows listeners to 22598 * get a chance to respond before the target view. 22599 * 22600 * @param v The view the generic motion event has been dispatched to. 22601 * @param event The MotionEvent object containing full information about 22602 * the event. 22603 * @return True if the listener has consumed the event, false otherwise. 22604 */ 22605 boolean onGenericMotion(View v, MotionEvent event); 22606 } 22607 22608 /** 22609 * Interface definition for a callback to be invoked when a view has been clicked and held. 22610 */ 22611 public interface OnLongClickListener { 22612 /** 22613 * Called when a view has been clicked and held. 22614 * 22615 * @param v The view that was clicked and held. 22616 * 22617 * @return true if the callback consumed the long click, false otherwise. 22618 */ 22619 boolean onLongClick(View v); 22620 } 22621 22622 /** 22623 * Interface definition for a callback to be invoked when a drag is being dispatched 22624 * to this view. The callback will be invoked before the hosting view's own 22625 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22626 * onDrag(event) behavior, it should return 'false' from this callback. 22627 * 22628 * <div class="special reference"> 22629 * <h3>Developer Guides</h3> 22630 * <p>For a guide to implementing drag and drop features, read the 22631 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22632 * </div> 22633 */ 22634 public interface OnDragListener { 22635 /** 22636 * Called when a drag event is dispatched to a view. This allows listeners 22637 * to get a chance to override base View behavior. 22638 * 22639 * @param v The View that received the drag event. 22640 * @param event The {@link android.view.DragEvent} object for the drag event. 22641 * @return {@code true} if the drag event was handled successfully, or {@code false} 22642 * if the drag event was not handled. Note that {@code false} will trigger the View 22643 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22644 */ 22645 boolean onDrag(View v, DragEvent event); 22646 } 22647 22648 /** 22649 * Interface definition for a callback to be invoked when the focus state of 22650 * a view changed. 22651 */ 22652 public interface OnFocusChangeListener { 22653 /** 22654 * Called when the focus state of a view has changed. 22655 * 22656 * @param v The view whose state has changed. 22657 * @param hasFocus The new focus state of v. 22658 */ 22659 void onFocusChange(View v, boolean hasFocus); 22660 } 22661 22662 /** 22663 * Interface definition for a callback to be invoked when a view is clicked. 22664 */ 22665 public interface OnClickListener { 22666 /** 22667 * Called when a view has been clicked. 22668 * 22669 * @param v The view that was clicked. 22670 */ 22671 void onClick(View v); 22672 } 22673 22674 /** 22675 * Interface definition for a callback to be invoked when a view is context clicked. 22676 */ 22677 public interface OnContextClickListener { 22678 /** 22679 * Called when a view is context clicked. 22680 * 22681 * @param v The view that has been context clicked. 22682 * @return true if the callback consumed the context click, false otherwise. 22683 */ 22684 boolean onContextClick(View v); 22685 } 22686 22687 /** 22688 * Interface definition for a callback to be invoked when the context menu 22689 * for this view is being built. 22690 */ 22691 public interface OnCreateContextMenuListener { 22692 /** 22693 * Called when the context menu for this view is being built. It is not 22694 * safe to hold onto the menu after this method returns. 22695 * 22696 * @param menu The context menu that is being built 22697 * @param v The view for which the context menu is being built 22698 * @param menuInfo Extra information about the item for which the 22699 * context menu should be shown. This information will vary 22700 * depending on the class of v. 22701 */ 22702 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22703 } 22704 22705 /** 22706 * Interface definition for a callback to be invoked when the status bar changes 22707 * visibility. This reports <strong>global</strong> changes to the system UI 22708 * state, not what the application is requesting. 22709 * 22710 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22711 */ 22712 public interface OnSystemUiVisibilityChangeListener { 22713 /** 22714 * Called when the status bar changes visibility because of a call to 22715 * {@link View#setSystemUiVisibility(int)}. 22716 * 22717 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22718 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22719 * This tells you the <strong>global</strong> state of these UI visibility 22720 * flags, not what your app is currently applying. 22721 */ 22722 public void onSystemUiVisibilityChange(int visibility); 22723 } 22724 22725 /** 22726 * Interface definition for a callback to be invoked when this view is attached 22727 * or detached from its window. 22728 */ 22729 public interface OnAttachStateChangeListener { 22730 /** 22731 * Called when the view is attached to a window. 22732 * @param v The view that was attached 22733 */ 22734 public void onViewAttachedToWindow(View v); 22735 /** 22736 * Called when the view is detached from a window. 22737 * @param v The view that was detached 22738 */ 22739 public void onViewDetachedFromWindow(View v); 22740 } 22741 22742 /** 22743 * Listener for applying window insets on a view in a custom way. 22744 * 22745 * <p>Apps may choose to implement this interface if they want to apply custom policy 22746 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22747 * is set, its 22748 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22749 * method will be called instead of the View's own 22750 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22751 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22752 * the View's normal behavior as part of its own.</p> 22753 */ 22754 public interface OnApplyWindowInsetsListener { 22755 /** 22756 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22757 * on a View, this listener method will be called instead of the view's own 22758 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22759 * 22760 * @param v The view applying window insets 22761 * @param insets The insets to apply 22762 * @return The insets supplied, minus any insets that were consumed 22763 */ 22764 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22765 } 22766 22767 private final class UnsetPressedState implements Runnable { 22768 @Override 22769 public void run() { 22770 setPressed(false); 22771 } 22772 } 22773 22774 /** 22775 * Base class for derived classes that want to save and restore their own 22776 * state in {@link android.view.View#onSaveInstanceState()}. 22777 */ 22778 public static class BaseSavedState extends AbsSavedState { 22779 String mStartActivityRequestWhoSaved; 22780 22781 /** 22782 * Constructor used when reading from a parcel. Reads the state of the superclass. 22783 * 22784 * @param source parcel to read from 22785 */ 22786 public BaseSavedState(Parcel source) { 22787 this(source, null); 22788 } 22789 22790 /** 22791 * Constructor used when reading from a parcel using a given class loader. 22792 * Reads the state of the superclass. 22793 * 22794 * @param source parcel to read from 22795 * @param loader ClassLoader to use for reading 22796 */ 22797 public BaseSavedState(Parcel source, ClassLoader loader) { 22798 super(source, loader); 22799 mStartActivityRequestWhoSaved = source.readString(); 22800 } 22801 22802 /** 22803 * Constructor called by derived classes when creating their SavedState objects 22804 * 22805 * @param superState The state of the superclass of this view 22806 */ 22807 public BaseSavedState(Parcelable superState) { 22808 super(superState); 22809 } 22810 22811 @Override 22812 public void writeToParcel(Parcel out, int flags) { 22813 super.writeToParcel(out, flags); 22814 out.writeString(mStartActivityRequestWhoSaved); 22815 } 22816 22817 public static final Parcelable.Creator<BaseSavedState> CREATOR 22818 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 22819 @Override 22820 public BaseSavedState createFromParcel(Parcel in) { 22821 return new BaseSavedState(in); 22822 } 22823 22824 @Override 22825 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 22826 return new BaseSavedState(in, loader); 22827 } 22828 22829 @Override 22830 public BaseSavedState[] newArray(int size) { 22831 return new BaseSavedState[size]; 22832 } 22833 }; 22834 } 22835 22836 /** 22837 * A set of information given to a view when it is attached to its parent 22838 * window. 22839 */ 22840 final static class AttachInfo { 22841 interface Callbacks { 22842 void playSoundEffect(int effectId); 22843 boolean performHapticFeedback(int effectId, boolean always); 22844 } 22845 22846 /** 22847 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22848 * to a Handler. This class contains the target (View) to invalidate and 22849 * the coordinates of the dirty rectangle. 22850 * 22851 * For performance purposes, this class also implements a pool of up to 22852 * POOL_LIMIT objects that get reused. This reduces memory allocations 22853 * whenever possible. 22854 */ 22855 static class InvalidateInfo { 22856 private static final int POOL_LIMIT = 10; 22857 22858 private static final SynchronizedPool<InvalidateInfo> sPool = 22859 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22860 22861 View target; 22862 22863 int left; 22864 int top; 22865 int right; 22866 int bottom; 22867 22868 public static InvalidateInfo obtain() { 22869 InvalidateInfo instance = sPool.acquire(); 22870 return (instance != null) ? instance : new InvalidateInfo(); 22871 } 22872 22873 public void recycle() { 22874 target = null; 22875 sPool.release(this); 22876 } 22877 } 22878 22879 final IWindowSession mSession; 22880 22881 final IWindow mWindow; 22882 22883 final IBinder mWindowToken; 22884 22885 final Display mDisplay; 22886 22887 final Callbacks mRootCallbacks; 22888 22889 IWindowId mIWindowId; 22890 WindowId mWindowId; 22891 22892 /** 22893 * The top view of the hierarchy. 22894 */ 22895 View mRootView; 22896 22897 IBinder mPanelParentWindowToken; 22898 22899 boolean mHardwareAccelerated; 22900 boolean mHardwareAccelerationRequested; 22901 ThreadedRenderer mThreadedRenderer; 22902 List<RenderNode> mPendingAnimatingRenderNodes; 22903 22904 /** 22905 * The state of the display to which the window is attached, as reported 22906 * by {@link Display#getState()}. Note that the display state constants 22907 * declared by {@link Display} do not exactly line up with the screen state 22908 * constants declared by {@link View} (there are more display states than 22909 * screen states). 22910 */ 22911 int mDisplayState = Display.STATE_UNKNOWN; 22912 22913 /** 22914 * Scale factor used by the compatibility mode 22915 */ 22916 float mApplicationScale; 22917 22918 /** 22919 * Indicates whether the application is in compatibility mode 22920 */ 22921 boolean mScalingRequired; 22922 22923 /** 22924 * Left position of this view's window 22925 */ 22926 int mWindowLeft; 22927 22928 /** 22929 * Top position of this view's window 22930 */ 22931 int mWindowTop; 22932 22933 /** 22934 * Indicates whether views need to use 32-bit drawing caches 22935 */ 22936 boolean mUse32BitDrawingCache; 22937 22938 /** 22939 * For windows that are full-screen but using insets to layout inside 22940 * of the screen areas, these are the current insets to appear inside 22941 * the overscan area of the display. 22942 */ 22943 final Rect mOverscanInsets = new Rect(); 22944 22945 /** 22946 * For windows that are full-screen but using insets to layout inside 22947 * of the screen decorations, these are the current insets for the 22948 * content of the window. 22949 */ 22950 final Rect mContentInsets = new Rect(); 22951 22952 /** 22953 * For windows that are full-screen but using insets to layout inside 22954 * of the screen decorations, these are the current insets for the 22955 * actual visible parts of the window. 22956 */ 22957 final Rect mVisibleInsets = new Rect(); 22958 22959 /** 22960 * For windows that are full-screen but using insets to layout inside 22961 * of the screen decorations, these are the current insets for the 22962 * stable system windows. 22963 */ 22964 final Rect mStableInsets = new Rect(); 22965 22966 /** 22967 * For windows that include areas that are not covered by real surface these are the outsets 22968 * for real surface. 22969 */ 22970 final Rect mOutsets = new Rect(); 22971 22972 /** 22973 * In multi-window we force show the navigation bar. Because we don't want that the surface 22974 * size changes in this mode, we instead have a flag whether the navigation bar size should 22975 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22976 */ 22977 boolean mAlwaysConsumeNavBar; 22978 22979 /** 22980 * The internal insets given by this window. This value is 22981 * supplied by the client (through 22982 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22983 * be given to the window manager when changed to be used in laying 22984 * out windows behind it. 22985 */ 22986 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22987 = new ViewTreeObserver.InternalInsetsInfo(); 22988 22989 /** 22990 * Set to true when mGivenInternalInsets is non-empty. 22991 */ 22992 boolean mHasNonEmptyGivenInternalInsets; 22993 22994 /** 22995 * All views in the window's hierarchy that serve as scroll containers, 22996 * used to determine if the window can be resized or must be panned 22997 * to adjust for a soft input area. 22998 */ 22999 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 23000 23001 final KeyEvent.DispatcherState mKeyDispatchState 23002 = new KeyEvent.DispatcherState(); 23003 23004 /** 23005 * Indicates whether the view's window currently has the focus. 23006 */ 23007 boolean mHasWindowFocus; 23008 23009 /** 23010 * The current visibility of the window. 23011 */ 23012 int mWindowVisibility; 23013 23014 /** 23015 * Indicates the time at which drawing started to occur. 23016 */ 23017 long mDrawingTime; 23018 23019 /** 23020 * Indicates whether or not ignoring the DIRTY_MASK flags. 23021 */ 23022 boolean mIgnoreDirtyState; 23023 23024 /** 23025 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 23026 * to avoid clearing that flag prematurely. 23027 */ 23028 boolean mSetIgnoreDirtyState = false; 23029 23030 /** 23031 * Indicates whether the view's window is currently in touch mode. 23032 */ 23033 boolean mInTouchMode; 23034 23035 /** 23036 * Indicates whether the view has requested unbuffered input dispatching for the current 23037 * event stream. 23038 */ 23039 boolean mUnbufferedDispatchRequested; 23040 23041 /** 23042 * Indicates that ViewAncestor should trigger a global layout change 23043 * the next time it performs a traversal 23044 */ 23045 boolean mRecomputeGlobalAttributes; 23046 23047 /** 23048 * Always report new attributes at next traversal. 23049 */ 23050 boolean mForceReportNewAttributes; 23051 23052 /** 23053 * Set during a traveral if any views want to keep the screen on. 23054 */ 23055 boolean mKeepScreenOn; 23056 23057 /** 23058 * Set during a traveral if the light center needs to be updated. 23059 */ 23060 boolean mNeedsUpdateLightCenter; 23061 23062 /** 23063 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 23064 */ 23065 int mSystemUiVisibility; 23066 23067 /** 23068 * Hack to force certain system UI visibility flags to be cleared. 23069 */ 23070 int mDisabledSystemUiVisibility; 23071 23072 /** 23073 * Last global system UI visibility reported by the window manager. 23074 */ 23075 int mGlobalSystemUiVisibility = -1; 23076 23077 /** 23078 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 23079 * attached. 23080 */ 23081 boolean mHasSystemUiListeners; 23082 23083 /** 23084 * Set if the window has requested to extend into the overscan region 23085 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 23086 */ 23087 boolean mOverscanRequested; 23088 23089 /** 23090 * Set if the visibility of any views has changed. 23091 */ 23092 boolean mViewVisibilityChanged; 23093 23094 /** 23095 * Set to true if a view has been scrolled. 23096 */ 23097 boolean mViewScrollChanged; 23098 23099 /** 23100 * Set to true if high contrast mode enabled 23101 */ 23102 boolean mHighContrastText; 23103 23104 /** 23105 * Set to true if a pointer event is currently being handled. 23106 */ 23107 boolean mHandlingPointerEvent; 23108 23109 /** 23110 * Global to the view hierarchy used as a temporary for dealing with 23111 * x/y points in the transparent region computations. 23112 */ 23113 final int[] mTransparentLocation = new int[2]; 23114 23115 /** 23116 * Global to the view hierarchy used as a temporary for dealing with 23117 * x/y points in the ViewGroup.invalidateChild implementation. 23118 */ 23119 final int[] mInvalidateChildLocation = new int[2]; 23120 23121 /** 23122 * Global to the view hierarchy used as a temporary for dealing with 23123 * computing absolute on-screen location. 23124 */ 23125 final int[] mTmpLocation = new int[2]; 23126 23127 /** 23128 * Global to the view hierarchy used as a temporary for dealing with 23129 * x/y location when view is transformed. 23130 */ 23131 final float[] mTmpTransformLocation = new float[2]; 23132 23133 /** 23134 * The view tree observer used to dispatch global events like 23135 * layout, pre-draw, touch mode change, etc. 23136 */ 23137 final ViewTreeObserver mTreeObserver; 23138 23139 /** 23140 * A Canvas used by the view hierarchy to perform bitmap caching. 23141 */ 23142 Canvas mCanvas; 23143 23144 /** 23145 * The view root impl. 23146 */ 23147 final ViewRootImpl mViewRootImpl; 23148 23149 /** 23150 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 23151 * handler can be used to pump events in the UI events queue. 23152 */ 23153 final Handler mHandler; 23154 23155 /** 23156 * Temporary for use in computing invalidate rectangles while 23157 * calling up the hierarchy. 23158 */ 23159 final Rect mTmpInvalRect = new Rect(); 23160 23161 /** 23162 * Temporary for use in computing hit areas with transformed views 23163 */ 23164 final RectF mTmpTransformRect = new RectF(); 23165 23166 /** 23167 * Temporary for use in computing hit areas with transformed views 23168 */ 23169 final RectF mTmpTransformRect1 = new RectF(); 23170 23171 /** 23172 * Temporary list of rectanges. 23173 */ 23174 final List<RectF> mTmpRectList = new ArrayList<>(); 23175 23176 /** 23177 * Temporary for use in transforming invalidation rect 23178 */ 23179 final Matrix mTmpMatrix = new Matrix(); 23180 23181 /** 23182 * Temporary for use in transforming invalidation rect 23183 */ 23184 final Transformation mTmpTransformation = new Transformation(); 23185 23186 /** 23187 * Temporary for use in querying outlines from OutlineProviders 23188 */ 23189 final Outline mTmpOutline = new Outline(); 23190 23191 /** 23192 * Temporary list for use in collecting focusable descendents of a view. 23193 */ 23194 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 23195 23196 /** 23197 * The id of the window for accessibility purposes. 23198 */ 23199 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 23200 23201 /** 23202 * Flags related to accessibility processing. 23203 * 23204 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23205 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23206 */ 23207 int mAccessibilityFetchFlags; 23208 23209 /** 23210 * The drawable for highlighting accessibility focus. 23211 */ 23212 Drawable mAccessibilityFocusDrawable; 23213 23214 /** 23215 * Show where the margins, bounds and layout bounds are for each view. 23216 */ 23217 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23218 23219 /** 23220 * Point used to compute visible regions. 23221 */ 23222 final Point mPoint = new Point(); 23223 23224 /** 23225 * Used to track which View originated a requestLayout() call, used when 23226 * requestLayout() is called during layout. 23227 */ 23228 View mViewRequestingLayout; 23229 23230 /** 23231 * Used to track views that need (at least) a partial relayout at their current size 23232 * during the next traversal. 23233 */ 23234 List<View> mPartialLayoutViews = new ArrayList<>(); 23235 23236 /** 23237 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23238 * modification. Lazily assigned during ViewRootImpl layout. 23239 */ 23240 List<View> mEmptyPartialLayoutViews; 23241 23242 /** 23243 * Used to track the identity of the current drag operation. 23244 */ 23245 IBinder mDragToken; 23246 23247 /** 23248 * The drag shadow surface for the current drag operation. 23249 */ 23250 public Surface mDragSurface; 23251 23252 /** 23253 * Creates a new set of attachment information with the specified 23254 * events handler and thread. 23255 * 23256 * @param handler the events handler the view must use 23257 */ 23258 AttachInfo(IWindowSession session, IWindow window, Display display, 23259 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 23260 Context context) { 23261 mSession = session; 23262 mWindow = window; 23263 mWindowToken = window.asBinder(); 23264 mDisplay = display; 23265 mViewRootImpl = viewRootImpl; 23266 mHandler = handler; 23267 mRootCallbacks = effectPlayer; 23268 mTreeObserver = new ViewTreeObserver(context); 23269 } 23270 } 23271 23272 /** 23273 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23274 * is supported. This avoids keeping too many unused fields in most 23275 * instances of View.</p> 23276 */ 23277 private static class ScrollabilityCache implements Runnable { 23278 23279 /** 23280 * Scrollbars are not visible 23281 */ 23282 public static final int OFF = 0; 23283 23284 /** 23285 * Scrollbars are visible 23286 */ 23287 public static final int ON = 1; 23288 23289 /** 23290 * Scrollbars are fading away 23291 */ 23292 public static final int FADING = 2; 23293 23294 public boolean fadeScrollBars; 23295 23296 public int fadingEdgeLength; 23297 public int scrollBarDefaultDelayBeforeFade; 23298 public int scrollBarFadeDuration; 23299 23300 public int scrollBarSize; 23301 public ScrollBarDrawable scrollBar; 23302 public float[] interpolatorValues; 23303 public View host; 23304 23305 public final Paint paint; 23306 public final Matrix matrix; 23307 public Shader shader; 23308 23309 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23310 23311 private static final float[] OPAQUE = { 255 }; 23312 private static final float[] TRANSPARENT = { 0.0f }; 23313 23314 /** 23315 * When fading should start. This time moves into the future every time 23316 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23317 */ 23318 public long fadeStartTime; 23319 23320 23321 /** 23322 * The current state of the scrollbars: ON, OFF, or FADING 23323 */ 23324 public int state = OFF; 23325 23326 private int mLastColor; 23327 23328 public final Rect mScrollBarBounds = new Rect(); 23329 23330 public static final int NOT_DRAGGING = 0; 23331 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23332 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23333 public int mScrollBarDraggingState = NOT_DRAGGING; 23334 23335 public float mScrollBarDraggingPos = 0; 23336 23337 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23338 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23339 scrollBarSize = configuration.getScaledScrollBarSize(); 23340 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23341 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23342 23343 paint = new Paint(); 23344 matrix = new Matrix(); 23345 // use use a height of 1, and then wack the matrix each time we 23346 // actually use it. 23347 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23348 paint.setShader(shader); 23349 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23350 23351 this.host = host; 23352 } 23353 23354 public void setFadeColor(int color) { 23355 if (color != mLastColor) { 23356 mLastColor = color; 23357 23358 if (color != 0) { 23359 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23360 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23361 paint.setShader(shader); 23362 // Restore the default transfer mode (src_over) 23363 paint.setXfermode(null); 23364 } else { 23365 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23366 paint.setShader(shader); 23367 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23368 } 23369 } 23370 } 23371 23372 public void run() { 23373 long now = AnimationUtils.currentAnimationTimeMillis(); 23374 if (now >= fadeStartTime) { 23375 23376 // the animation fades the scrollbars out by changing 23377 // the opacity (alpha) from fully opaque to fully 23378 // transparent 23379 int nextFrame = (int) now; 23380 int framesCount = 0; 23381 23382 Interpolator interpolator = scrollBarInterpolator; 23383 23384 // Start opaque 23385 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23386 23387 // End transparent 23388 nextFrame += scrollBarFadeDuration; 23389 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23390 23391 state = FADING; 23392 23393 // Kick off the fade animation 23394 host.invalidate(true); 23395 } 23396 } 23397 } 23398 23399 /** 23400 * Resuable callback for sending 23401 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23402 */ 23403 private class SendViewScrolledAccessibilityEvent implements Runnable { 23404 public volatile boolean mIsPending; 23405 23406 public void run() { 23407 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23408 mIsPending = false; 23409 } 23410 } 23411 23412 /** 23413 * <p> 23414 * This class represents a delegate that can be registered in a {@link View} 23415 * to enhance accessibility support via composition rather via inheritance. 23416 * It is specifically targeted to widget developers that extend basic View 23417 * classes i.e. classes in package android.view, that would like their 23418 * applications to be backwards compatible. 23419 * </p> 23420 * <div class="special reference"> 23421 * <h3>Developer Guides</h3> 23422 * <p>For more information about making applications accessible, read the 23423 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23424 * developer guide.</p> 23425 * </div> 23426 * <p> 23427 * A scenario in which a developer would like to use an accessibility delegate 23428 * is overriding a method introduced in a later API version than the minimal API 23429 * version supported by the application. For example, the method 23430 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23431 * in API version 4 when the accessibility APIs were first introduced. If a 23432 * developer would like his application to run on API version 4 devices (assuming 23433 * all other APIs used by the application are version 4 or lower) and take advantage 23434 * of this method, instead of overriding the method which would break the application's 23435 * backwards compatibility, he can override the corresponding method in this 23436 * delegate and register the delegate in the target View if the API version of 23437 * the system is high enough, i.e. the API version is the same as or higher than the API 23438 * version that introduced 23439 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23440 * </p> 23441 * <p> 23442 * Here is an example implementation: 23443 * </p> 23444 * <code><pre><p> 23445 * if (Build.VERSION.SDK_INT >= 14) { 23446 * // If the API version is equal of higher than the version in 23447 * // which onInitializeAccessibilityNodeInfo was introduced we 23448 * // register a delegate with a customized implementation. 23449 * View view = findViewById(R.id.view_id); 23450 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23451 * public void onInitializeAccessibilityNodeInfo(View host, 23452 * AccessibilityNodeInfo info) { 23453 * // Let the default implementation populate the info. 23454 * super.onInitializeAccessibilityNodeInfo(host, info); 23455 * // Set some other information. 23456 * info.setEnabled(host.isEnabled()); 23457 * } 23458 * }); 23459 * } 23460 * </code></pre></p> 23461 * <p> 23462 * This delegate contains methods that correspond to the accessibility methods 23463 * in View. If a delegate has been specified the implementation in View hands 23464 * off handling to the corresponding method in this delegate. The default 23465 * implementation the delegate methods behaves exactly as the corresponding 23466 * method in View for the case of no accessibility delegate been set. Hence, 23467 * to customize the behavior of a View method, clients can override only the 23468 * corresponding delegate method without altering the behavior of the rest 23469 * accessibility related methods of the host view. 23470 * </p> 23471 * <p> 23472 * <strong>Note:</strong> On platform versions prior to 23473 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23474 * views in the {@code android.widget.*} package are called <i>before</i> 23475 * host methods. This prevents certain properties such as class name from 23476 * being modified by overriding 23477 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23478 * as any changes will be overwritten by the host class. 23479 * <p> 23480 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23481 * methods are called <i>after</i> host methods, which all properties to be 23482 * modified without being overwritten by the host class. 23483 */ 23484 public static class AccessibilityDelegate { 23485 23486 /** 23487 * Sends an accessibility event of the given type. If accessibility is not 23488 * enabled this method has no effect. 23489 * <p> 23490 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23491 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23492 * been set. 23493 * </p> 23494 * 23495 * @param host The View hosting the delegate. 23496 * @param eventType The type of the event to send. 23497 * 23498 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23499 */ 23500 public void sendAccessibilityEvent(View host, int eventType) { 23501 host.sendAccessibilityEventInternal(eventType); 23502 } 23503 23504 /** 23505 * Performs the specified accessibility action on the view. For 23506 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23507 * <p> 23508 * The default implementation behaves as 23509 * {@link View#performAccessibilityAction(int, Bundle) 23510 * View#performAccessibilityAction(int, Bundle)} for the case of 23511 * no accessibility delegate been set. 23512 * </p> 23513 * 23514 * @param action The action to perform. 23515 * @return Whether the action was performed. 23516 * 23517 * @see View#performAccessibilityAction(int, Bundle) 23518 * View#performAccessibilityAction(int, Bundle) 23519 */ 23520 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23521 return host.performAccessibilityActionInternal(action, args); 23522 } 23523 23524 /** 23525 * Sends an accessibility event. This method behaves exactly as 23526 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23527 * empty {@link AccessibilityEvent} and does not perform a check whether 23528 * accessibility is enabled. 23529 * <p> 23530 * The default implementation behaves as 23531 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23532 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23533 * the case of no accessibility delegate been set. 23534 * </p> 23535 * 23536 * @param host The View hosting the delegate. 23537 * @param event The event to send. 23538 * 23539 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23540 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23541 */ 23542 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23543 host.sendAccessibilityEventUncheckedInternal(event); 23544 } 23545 23546 /** 23547 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23548 * to its children for adding their text content to the event. 23549 * <p> 23550 * The default implementation behaves as 23551 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23552 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23553 * the case of no accessibility delegate been set. 23554 * </p> 23555 * 23556 * @param host The View hosting the delegate. 23557 * @param event The event. 23558 * @return True if the event population was completed. 23559 * 23560 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23561 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23562 */ 23563 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23564 return host.dispatchPopulateAccessibilityEventInternal(event); 23565 } 23566 23567 /** 23568 * Gives a chance to the host View to populate the accessibility event with its 23569 * text content. 23570 * <p> 23571 * The default implementation behaves as 23572 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23573 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23574 * the case of no accessibility delegate been set. 23575 * </p> 23576 * 23577 * @param host The View hosting the delegate. 23578 * @param event The accessibility event which to populate. 23579 * 23580 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23581 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23582 */ 23583 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23584 host.onPopulateAccessibilityEventInternal(event); 23585 } 23586 23587 /** 23588 * Initializes an {@link AccessibilityEvent} with information about the 23589 * the host View which is the event source. 23590 * <p> 23591 * The default implementation behaves as 23592 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23593 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23594 * the case of no accessibility delegate been set. 23595 * </p> 23596 * 23597 * @param host The View hosting the delegate. 23598 * @param event The event to initialize. 23599 * 23600 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23601 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23602 */ 23603 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23604 host.onInitializeAccessibilityEventInternal(event); 23605 } 23606 23607 /** 23608 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23609 * <p> 23610 * The default implementation behaves as 23611 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23612 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23613 * the case of no accessibility delegate been set. 23614 * </p> 23615 * 23616 * @param host The View hosting the delegate. 23617 * @param info The instance to initialize. 23618 * 23619 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23620 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23621 */ 23622 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23623 host.onInitializeAccessibilityNodeInfoInternal(info); 23624 } 23625 23626 /** 23627 * Called when a child of the host View has requested sending an 23628 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23629 * to augment the event. 23630 * <p> 23631 * The default implementation behaves as 23632 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23633 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23634 * the case of no accessibility delegate been set. 23635 * </p> 23636 * 23637 * @param host The View hosting the delegate. 23638 * @param child The child which requests sending the event. 23639 * @param event The event to be sent. 23640 * @return True if the event should be sent 23641 * 23642 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23643 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23644 */ 23645 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23646 AccessibilityEvent event) { 23647 return host.onRequestSendAccessibilityEventInternal(child, event); 23648 } 23649 23650 /** 23651 * Gets the provider for managing a virtual view hierarchy rooted at this View 23652 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23653 * that explore the window content. 23654 * <p> 23655 * The default implementation behaves as 23656 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23657 * the case of no accessibility delegate been set. 23658 * </p> 23659 * 23660 * @return The provider. 23661 * 23662 * @see AccessibilityNodeProvider 23663 */ 23664 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23665 return null; 23666 } 23667 23668 /** 23669 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23670 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23671 * This method is responsible for obtaining an accessibility node info from a 23672 * pool of reusable instances and calling 23673 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23674 * view to initialize the former. 23675 * <p> 23676 * <strong>Note:</strong> The client is responsible for recycling the obtained 23677 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23678 * creation. 23679 * </p> 23680 * <p> 23681 * The default implementation behaves as 23682 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23683 * the case of no accessibility delegate been set. 23684 * </p> 23685 * @return A populated {@link AccessibilityNodeInfo}. 23686 * 23687 * @see AccessibilityNodeInfo 23688 * 23689 * @hide 23690 */ 23691 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23692 return host.createAccessibilityNodeInfoInternal(); 23693 } 23694 } 23695 23696 private class MatchIdPredicate implements Predicate<View> { 23697 public int mId; 23698 23699 @Override 23700 public boolean apply(View view) { 23701 return (view.mID == mId); 23702 } 23703 } 23704 23705 private class MatchLabelForPredicate implements Predicate<View> { 23706 private int mLabeledId; 23707 23708 @Override 23709 public boolean apply(View view) { 23710 return (view.mLabelForId == mLabeledId); 23711 } 23712 } 23713 23714 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23715 private int mChangeTypes = 0; 23716 private boolean mPosted; 23717 private boolean mPostedWithDelay; 23718 private long mLastEventTimeMillis; 23719 23720 @Override 23721 public void run() { 23722 mPosted = false; 23723 mPostedWithDelay = false; 23724 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23725 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23726 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23727 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23728 event.setContentChangeTypes(mChangeTypes); 23729 sendAccessibilityEventUnchecked(event); 23730 } 23731 mChangeTypes = 0; 23732 } 23733 23734 public void runOrPost(int changeType) { 23735 mChangeTypes |= changeType; 23736 23737 // If this is a live region or the child of a live region, collect 23738 // all events from this frame and send them on the next frame. 23739 if (inLiveRegion()) { 23740 // If we're already posted with a delay, remove that. 23741 if (mPostedWithDelay) { 23742 removeCallbacks(this); 23743 mPostedWithDelay = false; 23744 } 23745 // Only post if we're not already posted. 23746 if (!mPosted) { 23747 post(this); 23748 mPosted = true; 23749 } 23750 return; 23751 } 23752 23753 if (mPosted) { 23754 return; 23755 } 23756 23757 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23758 final long minEventIntevalMillis = 23759 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23760 if (timeSinceLastMillis >= minEventIntevalMillis) { 23761 removeCallbacks(this); 23762 run(); 23763 } else { 23764 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23765 mPostedWithDelay = true; 23766 } 23767 } 23768 } 23769 23770 private boolean inLiveRegion() { 23771 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23772 return true; 23773 } 23774 23775 ViewParent parent = getParent(); 23776 while (parent instanceof View) { 23777 if (((View) parent).getAccessibilityLiveRegion() 23778 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23779 return true; 23780 } 23781 parent = parent.getParent(); 23782 } 23783 23784 return false; 23785 } 23786 23787 /** 23788 * Dump all private flags in readable format, useful for documentation and 23789 * sanity checking. 23790 */ 23791 private static void dumpFlags() { 23792 final HashMap<String, String> found = Maps.newHashMap(); 23793 try { 23794 for (Field field : View.class.getDeclaredFields()) { 23795 final int modifiers = field.getModifiers(); 23796 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23797 if (field.getType().equals(int.class)) { 23798 final int value = field.getInt(null); 23799 dumpFlag(found, field.getName(), value); 23800 } else if (field.getType().equals(int[].class)) { 23801 final int[] values = (int[]) field.get(null); 23802 for (int i = 0; i < values.length; i++) { 23803 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23804 } 23805 } 23806 } 23807 } 23808 } catch (IllegalAccessException e) { 23809 throw new RuntimeException(e); 23810 } 23811 23812 final ArrayList<String> keys = Lists.newArrayList(); 23813 keys.addAll(found.keySet()); 23814 Collections.sort(keys); 23815 for (String key : keys) { 23816 Log.d(VIEW_LOG_TAG, found.get(key)); 23817 } 23818 } 23819 23820 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23821 // Sort flags by prefix, then by bits, always keeping unique keys 23822 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23823 final int prefix = name.indexOf('_'); 23824 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23825 final String output = bits + " " + name; 23826 found.put(key, output); 23827 } 23828 23829 /** {@hide} */ 23830 public void encode(@NonNull ViewHierarchyEncoder stream) { 23831 stream.beginObject(this); 23832 encodeProperties(stream); 23833 stream.endObject(); 23834 } 23835 23836 /** {@hide} */ 23837 @CallSuper 23838 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23839 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23840 if (resolveId instanceof String) { 23841 stream.addProperty("id", (String) resolveId); 23842 } else { 23843 stream.addProperty("id", mID); 23844 } 23845 23846 stream.addProperty("misc:transformation.alpha", 23847 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23848 stream.addProperty("misc:transitionName", getTransitionName()); 23849 23850 // layout 23851 stream.addProperty("layout:left", mLeft); 23852 stream.addProperty("layout:right", mRight); 23853 stream.addProperty("layout:top", mTop); 23854 stream.addProperty("layout:bottom", mBottom); 23855 stream.addProperty("layout:width", getWidth()); 23856 stream.addProperty("layout:height", getHeight()); 23857 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23858 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23859 stream.addProperty("layout:hasTransientState", hasTransientState()); 23860 stream.addProperty("layout:baseline", getBaseline()); 23861 23862 // layout params 23863 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23864 if (layoutParams != null) { 23865 stream.addPropertyKey("layoutParams"); 23866 layoutParams.encode(stream); 23867 } 23868 23869 // scrolling 23870 stream.addProperty("scrolling:scrollX", mScrollX); 23871 stream.addProperty("scrolling:scrollY", mScrollY); 23872 23873 // padding 23874 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23875 stream.addProperty("padding:paddingRight", mPaddingRight); 23876 stream.addProperty("padding:paddingTop", mPaddingTop); 23877 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23878 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23879 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23880 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23881 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23882 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23883 23884 // measurement 23885 stream.addProperty("measurement:minHeight", mMinHeight); 23886 stream.addProperty("measurement:minWidth", mMinWidth); 23887 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23888 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23889 23890 // drawing 23891 stream.addProperty("drawing:elevation", getElevation()); 23892 stream.addProperty("drawing:translationX", getTranslationX()); 23893 stream.addProperty("drawing:translationY", getTranslationY()); 23894 stream.addProperty("drawing:translationZ", getTranslationZ()); 23895 stream.addProperty("drawing:rotation", getRotation()); 23896 stream.addProperty("drawing:rotationX", getRotationX()); 23897 stream.addProperty("drawing:rotationY", getRotationY()); 23898 stream.addProperty("drawing:scaleX", getScaleX()); 23899 stream.addProperty("drawing:scaleY", getScaleY()); 23900 stream.addProperty("drawing:pivotX", getPivotX()); 23901 stream.addProperty("drawing:pivotY", getPivotY()); 23902 stream.addProperty("drawing:opaque", isOpaque()); 23903 stream.addProperty("drawing:alpha", getAlpha()); 23904 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23905 stream.addProperty("drawing:shadow", hasShadow()); 23906 stream.addProperty("drawing:solidColor", getSolidColor()); 23907 stream.addProperty("drawing:layerType", mLayerType); 23908 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23909 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23910 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23911 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23912 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23913 23914 // focus 23915 stream.addProperty("focus:hasFocus", hasFocus()); 23916 stream.addProperty("focus:isFocused", isFocused()); 23917 stream.addProperty("focus:isFocusable", isFocusable()); 23918 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23919 23920 stream.addProperty("misc:clickable", isClickable()); 23921 stream.addProperty("misc:pressed", isPressed()); 23922 stream.addProperty("misc:selected", isSelected()); 23923 stream.addProperty("misc:touchMode", isInTouchMode()); 23924 stream.addProperty("misc:hovered", isHovered()); 23925 stream.addProperty("misc:activated", isActivated()); 23926 23927 stream.addProperty("misc:visibility", getVisibility()); 23928 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23929 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23930 23931 stream.addProperty("misc:enabled", isEnabled()); 23932 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23933 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23934 23935 // theme attributes 23936 Resources.Theme theme = getContext().getTheme(); 23937 if (theme != null) { 23938 stream.addPropertyKey("theme"); 23939 theme.encode(stream); 23940 } 23941 23942 // view attribute information 23943 int n = mAttributes != null ? mAttributes.length : 0; 23944 stream.addProperty("meta:__attrCount__", n/2); 23945 for (int i = 0; i < n; i += 2) { 23946 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23947 } 23948 23949 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23950 23951 // text 23952 stream.addProperty("text:textDirection", getTextDirection()); 23953 stream.addProperty("text:textAlignment", getTextAlignment()); 23954 23955 // accessibility 23956 CharSequence contentDescription = getContentDescription(); 23957 stream.addProperty("accessibility:contentDescription", 23958 contentDescription == null ? "" : contentDescription.toString()); 23959 stream.addProperty("accessibility:labelFor", getLabelFor()); 23960 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23961 } 23962 23963 /** 23964 * Determine if this view is rendered on a round wearable device and is the main view 23965 * on the screen. 23966 */ 23967 private boolean shouldDrawRoundScrollbar() { 23968 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 23969 return false; 23970 } 23971 23972 final View rootView = getRootView(); 23973 final WindowInsets insets = getRootWindowInsets(); 23974 23975 int height = getHeight(); 23976 int width = getWidth(); 23977 int displayHeight = rootView.getHeight(); 23978 int displayWidth = rootView.getWidth(); 23979 23980 if (height != displayHeight || width != displayWidth) { 23981 return false; 23982 } 23983 23984 getLocationOnScreen(mAttachInfo.mTmpLocation); 23985 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 23986 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 23987 } 23988} 23989