View.java revision a86d1e0b5938cee1d76aefcc1e8967c353ea922d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.CallSuper; 22import android.annotation.ColorInt; 23import android.annotation.DrawableRes; 24import android.annotation.FloatRange; 25import android.annotation.IdRes; 26import android.annotation.IntDef; 27import android.annotation.IntRange; 28import android.annotation.LayoutRes; 29import android.annotation.NonNull; 30import android.annotation.Nullable; 31import android.annotation.Size; 32import android.annotation.UiThread; 33import android.content.ClipData; 34import android.content.Context; 35import android.content.ContextWrapper; 36import android.content.Intent; 37import android.content.res.ColorStateList; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.content.res.TypedArray; 41import android.graphics.Bitmap; 42import android.graphics.Canvas; 43import android.graphics.Insets; 44import android.graphics.Interpolator; 45import android.graphics.LinearGradient; 46import android.graphics.Matrix; 47import android.graphics.Outline; 48import android.graphics.Paint; 49import android.graphics.PixelFormat; 50import android.graphics.Point; 51import android.graphics.PorterDuff; 52import android.graphics.PorterDuffXfermode; 53import android.graphics.Rect; 54import android.graphics.RectF; 55import android.graphics.Region; 56import android.graphics.Shader; 57import android.graphics.drawable.ColorDrawable; 58import android.graphics.drawable.Drawable; 59import android.hardware.display.DisplayManagerGlobal; 60import android.os.Build.VERSION_CODES; 61import android.os.Bundle; 62import android.os.Handler; 63import android.os.IBinder; 64import android.os.Parcel; 65import android.os.Parcelable; 66import android.os.RemoteException; 67import android.os.SystemClock; 68import android.os.SystemProperties; 69import android.os.Trace; 70import android.text.TextUtils; 71import android.util.AttributeSet; 72import android.util.FloatProperty; 73import android.util.LayoutDirection; 74import android.util.Log; 75import android.util.LongSparseLongArray; 76import android.util.Pools.SynchronizedPool; 77import android.util.Property; 78import android.util.SparseArray; 79import android.util.StateSet; 80import android.util.SuperNotCalledException; 81import android.util.TypedValue; 82import android.view.ContextMenu.ContextMenuInfo; 83import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 85import android.view.AccessibilityIterators.TextSegmentIterator; 86import android.view.AccessibilityIterators.WordTextSegmentIterator; 87import android.view.accessibility.AccessibilityEvent; 88import android.view.accessibility.AccessibilityEventSource; 89import android.view.accessibility.AccessibilityManager; 90import android.view.accessibility.AccessibilityNodeInfo; 91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 92import android.view.accessibility.AccessibilityNodeProvider; 93import android.view.animation.Animation; 94import android.view.animation.AnimationUtils; 95import android.view.animation.Transformation; 96import android.view.inputmethod.EditorInfo; 97import android.view.inputmethod.InputConnection; 98import android.view.inputmethod.InputMethodManager; 99import android.widget.Checkable; 100import android.widget.FrameLayout; 101import android.widget.ScrollBarDrawable; 102import static android.os.Build.VERSION_CODES.*; 103import static java.lang.Math.max; 104 105import com.android.internal.R; 106import com.android.internal.util.Predicate; 107import com.android.internal.view.menu.MenuBuilder; 108import com.android.internal.widget.ScrollBarUtils; 109import com.google.android.collect.Lists; 110import com.google.android.collect.Maps; 111 112import java.lang.NullPointerException; 113import java.lang.annotation.Retention; 114import java.lang.annotation.RetentionPolicy; 115import java.lang.ref.WeakReference; 116import java.lang.reflect.Field; 117import java.lang.reflect.InvocationTargetException; 118import java.lang.reflect.Method; 119import java.lang.reflect.Modifier; 120import java.util.ArrayList; 121import java.util.Arrays; 122import java.util.Collections; 123import java.util.HashMap; 124import java.util.List; 125import java.util.Locale; 126import java.util.Map; 127import java.util.concurrent.CopyOnWriteArrayList; 128import java.util.concurrent.atomic.AtomicInteger; 129 130/** 131 * <p> 132 * This class represents the basic building block for user interface components. A View 133 * occupies a rectangular area on the screen and is responsible for drawing and 134 * event handling. View is the base class for <em>widgets</em>, which are 135 * used to create interactive UI components (buttons, text fields, etc.). The 136 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 137 * are invisible containers that hold other Views (or other ViewGroups) and define 138 * their layout properties. 139 * </p> 140 * 141 * <div class="special reference"> 142 * <h3>Developer Guides</h3> 143 * <p>For information about using this class to develop your application's user interface, 144 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 145 * </div> 146 * 147 * <a name="Using"></a> 148 * <h3>Using Views</h3> 149 * <p> 150 * All of the views in a window are arranged in a single tree. You can add views 151 * either from code or by specifying a tree of views in one or more XML layout 152 * files. There are many specialized subclasses of views that act as controls or 153 * are capable of displaying text, images, or other content. 154 * </p> 155 * <p> 156 * Once you have created a tree of views, there are typically a few types of 157 * common operations you may wish to perform: 158 * <ul> 159 * <li><strong>Set properties:</strong> for example setting the text of a 160 * {@link android.widget.TextView}. The available properties and the methods 161 * that set them will vary among the different subclasses of views. Note that 162 * properties that are known at build time can be set in the XML layout 163 * files.</li> 164 * <li><strong>Set focus:</strong> The framework will handle moving focus in 165 * response to user input. To force focus to a specific view, call 166 * {@link #requestFocus}.</li> 167 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 168 * that will be notified when something interesting happens to the view. For 169 * example, all views will let you set a listener to be notified when the view 170 * gains or loses focus. You can register such a listener using 171 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 172 * Other view subclasses offer more specialized listeners. For example, a Button 173 * exposes a listener to notify clients when the button is clicked.</li> 174 * <li><strong>Set visibility:</strong> You can hide or show views using 175 * {@link #setVisibility(int)}.</li> 176 * </ul> 177 * </p> 178 * <p><em> 179 * Note: The Android framework is responsible for measuring, laying out and 180 * drawing views. You should not call methods that perform these actions on 181 * views yourself unless you are actually implementing a 182 * {@link android.view.ViewGroup}. 183 * </em></p> 184 * 185 * <a name="Lifecycle"></a> 186 * <h3>Implementing a Custom View</h3> 187 * 188 * <p> 189 * To implement a custom view, you will usually begin by providing overrides for 190 * some of the standard methods that the framework calls on all views. You do 191 * not need to override all of these methods. In fact, you can start by just 192 * overriding {@link #onDraw(android.graphics.Canvas)}. 193 * <table border="2" width="85%" align="center" cellpadding="5"> 194 * <thead> 195 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 196 * </thead> 197 * 198 * <tbody> 199 * <tr> 200 * <td rowspan="2">Creation</td> 201 * <td>Constructors</td> 202 * <td>There is a form of the constructor that are called when the view 203 * is created from code and a form that is called when the view is 204 * inflated from a layout file. The second form should parse and apply 205 * any attributes defined in the layout file. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onFinishInflate()}</code></td> 210 * <td>Called after a view and all of its children has been inflated 211 * from XML.</td> 212 * </tr> 213 * 214 * <tr> 215 * <td rowspan="3">Layout</td> 216 * <td><code>{@link #onMeasure(int, int)}</code></td> 217 * <td>Called to determine the size requirements for this view and all 218 * of its children. 219 * </td> 220 * </tr> 221 * <tr> 222 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 223 * <td>Called when this view should assign a size and position to all 224 * of its children. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 229 * <td>Called when the size of this view has changed. 230 * </td> 231 * </tr> 232 * 233 * <tr> 234 * <td>Drawing</td> 235 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 236 * <td>Called when the view should render its content. 237 * </td> 238 * </tr> 239 * 240 * <tr> 241 * <td rowspan="4">Event processing</td> 242 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 243 * <td>Called when a new hardware key event occurs. 244 * </td> 245 * </tr> 246 * <tr> 247 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 248 * <td>Called when a hardware key up event occurs. 249 * </td> 250 * </tr> 251 * <tr> 252 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 253 * <td>Called when a trackball motion event occurs. 254 * </td> 255 * </tr> 256 * <tr> 257 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 258 * <td>Called when a touch screen motion event occurs. 259 * </td> 260 * </tr> 261 * 262 * <tr> 263 * <td rowspan="2">Focus</td> 264 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 265 * <td>Called when the view gains or loses focus. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 271 * <td>Called when the window containing the view gains or loses focus. 272 * </td> 273 * </tr> 274 * 275 * <tr> 276 * <td rowspan="3">Attaching</td> 277 * <td><code>{@link #onAttachedToWindow()}</code></td> 278 * <td>Called when the view is attached to a window. 279 * </td> 280 * </tr> 281 * 282 * <tr> 283 * <td><code>{@link #onDetachedFromWindow}</code></td> 284 * <td>Called when the view is detached from its window. 285 * </td> 286 * </tr> 287 * 288 * <tr> 289 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 290 * <td>Called when the visibility of the window containing the view 291 * has changed. 292 * </td> 293 * </tr> 294 * </tbody> 295 * 296 * </table> 297 * </p> 298 * 299 * <a name="IDs"></a> 300 * <h3>IDs</h3> 301 * Views may have an integer id associated with them. These ids are typically 302 * assigned in the layout XML files, and are used to find specific views within 303 * the view tree. A common pattern is to: 304 * <ul> 305 * <li>Define a Button in the layout file and assign it a unique ID. 306 * <pre> 307 * <Button 308 * android:id="@+id/my_button" 309 * android:layout_width="wrap_content" 310 * android:layout_height="wrap_content" 311 * android:text="@string/my_button_text"/> 312 * </pre></li> 313 * <li>From the onCreate method of an Activity, find the Button 314 * <pre class="prettyprint"> 315 * Button myButton = (Button) findViewById(R.id.my_button); 316 * </pre></li> 317 * </ul> 318 * <p> 319 * View IDs need not be unique throughout the tree, but it is good practice to 320 * ensure that they are at least unique within the part of the tree you are 321 * searching. 322 * </p> 323 * 324 * <a name="Position"></a> 325 * <h3>Position</h3> 326 * <p> 327 * The geometry of a view is that of a rectangle. A view has a location, 328 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 329 * two dimensions, expressed as a width and a height. The unit for location 330 * and dimensions is the pixel. 331 * </p> 332 * 333 * <p> 334 * It is possible to retrieve the location of a view by invoking the methods 335 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 336 * coordinate of the rectangle representing the view. The latter returns the 337 * top, or Y, coordinate of the rectangle representing the view. These methods 338 * both return the location of the view relative to its parent. For instance, 339 * when getLeft() returns 20, that means the view is located 20 pixels to the 340 * right of the left edge of its direct parent. 341 * </p> 342 * 343 * <p> 344 * In addition, several convenience methods are offered to avoid unnecessary 345 * computations, namely {@link #getRight()} and {@link #getBottom()}. 346 * These methods return the coordinates of the right and bottom edges of the 347 * rectangle representing the view. For instance, calling {@link #getRight()} 348 * is similar to the following computation: <code>getLeft() + getWidth()</code> 349 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 350 * </p> 351 * 352 * <a name="SizePaddingMargins"></a> 353 * <h3>Size, padding and margins</h3> 354 * <p> 355 * The size of a view is expressed with a width and a height. A view actually 356 * possess two pairs of width and height values. 357 * </p> 358 * 359 * <p> 360 * The first pair is known as <em>measured width</em> and 361 * <em>measured height</em>. These dimensions define how big a view wants to be 362 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 363 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 364 * and {@link #getMeasuredHeight()}. 365 * </p> 366 * 367 * <p> 368 * The second pair is simply known as <em>width</em> and <em>height</em>, or 369 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 370 * dimensions define the actual size of the view on screen, at drawing time and 371 * after layout. These values may, but do not have to, be different from the 372 * measured width and height. The width and height can be obtained by calling 373 * {@link #getWidth()} and {@link #getHeight()}. 374 * </p> 375 * 376 * <p> 377 * To measure its dimensions, a view takes into account its padding. The padding 378 * is expressed in pixels for the left, top, right and bottom parts of the view. 379 * Padding can be used to offset the content of the view by a specific amount of 380 * pixels. For instance, a left padding of 2 will push the view's content by 381 * 2 pixels to the right of the left edge. Padding can be set using the 382 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 383 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 384 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 385 * {@link #getPaddingEnd()}. 386 * </p> 387 * 388 * <p> 389 * Even though a view can define a padding, it does not provide any support for 390 * margins. However, view groups provide such a support. Refer to 391 * {@link android.view.ViewGroup} and 392 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 393 * </p> 394 * 395 * <a name="Layout"></a> 396 * <h3>Layout</h3> 397 * <p> 398 * Layout is a two pass process: a measure pass and a layout pass. The measuring 399 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 400 * of the view tree. Each view pushes dimension specifications down the tree 401 * during the recursion. At the end of the measure pass, every view has stored 402 * its measurements. The second pass happens in 403 * {@link #layout(int,int,int,int)} and is also top-down. During 404 * this pass each parent is responsible for positioning all of its children 405 * using the sizes computed in the measure pass. 406 * </p> 407 * 408 * <p> 409 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 410 * {@link #getMeasuredHeight()} values must be set, along with those for all of 411 * that view's descendants. A view's measured width and measured height values 412 * must respect the constraints imposed by the view's parents. This guarantees 413 * that at the end of the measure pass, all parents accept all of their 414 * children's measurements. A parent view may call measure() more than once on 415 * its children. For example, the parent may measure each child once with 416 * unspecified dimensions to find out how big they want to be, then call 417 * measure() on them again with actual numbers if the sum of all the children's 418 * unconstrained sizes is too big or too small. 419 * </p> 420 * 421 * <p> 422 * The measure pass uses two classes to communicate dimensions. The 423 * {@link MeasureSpec} class is used by views to tell their parents how they 424 * want to be measured and positioned. The base LayoutParams class just 425 * describes how big the view wants to be for both width and height. For each 426 * dimension, it can specify one of: 427 * <ul> 428 * <li> an exact number 429 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 430 * (minus padding) 431 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 432 * enclose its content (plus padding). 433 * </ul> 434 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 435 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 436 * an X and Y value. 437 * </p> 438 * 439 * <p> 440 * MeasureSpecs are used to push requirements down the tree from parent to 441 * child. A MeasureSpec can be in one of three modes: 442 * <ul> 443 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 444 * of a child view. For example, a LinearLayout may call measure() on its child 445 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 446 * tall the child view wants to be given a width of 240 pixels. 447 * <li>EXACTLY: This is used by the parent to impose an exact size on the 448 * child. The child must use this size, and guarantee that all of its 449 * descendants will fit within this size. 450 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 451 * child. The child must guarantee that it and all of its descendants will fit 452 * within this size. 453 * </ul> 454 * </p> 455 * 456 * <p> 457 * To initiate a layout, call {@link #requestLayout}. This method is typically 458 * called by a view on itself when it believes that is can no longer fit within 459 * its current bounds. 460 * </p> 461 * 462 * <a name="Drawing"></a> 463 * <h3>Drawing</h3> 464 * <p> 465 * Drawing is handled by walking the tree and recording the drawing commands of 466 * any View that needs to update. After this, the drawing commands of the 467 * entire tree are issued to screen, clipped to the newly damaged area. 468 * </p> 469 * 470 * <p> 471 * The tree is largely recorded and drawn in order, with parents drawn before 472 * (i.e., behind) their children, with siblings drawn in the order they appear 473 * in the tree. If you set a background drawable for a View, then the View will 474 * draw it before calling back to its <code>onDraw()</code> method. The child 475 * drawing order can be overridden with 476 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 477 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 478 * </p> 479 * 480 * <p> 481 * To force a view to draw, call {@link #invalidate()}. 482 * </p> 483 * 484 * <a name="EventHandlingThreading"></a> 485 * <h3>Event Handling and Threading</h3> 486 * <p> 487 * The basic cycle of a view is as follows: 488 * <ol> 489 * <li>An event comes in and is dispatched to the appropriate view. The view 490 * handles the event and notifies any listeners.</li> 491 * <li>If in the course of processing the event, the view's bounds may need 492 * to be changed, the view will call {@link #requestLayout()}.</li> 493 * <li>Similarly, if in the course of processing the event the view's appearance 494 * may need to be changed, the view will call {@link #invalidate()}.</li> 495 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 496 * the framework will take care of measuring, laying out, and drawing the tree 497 * as appropriate.</li> 498 * </ol> 499 * </p> 500 * 501 * <p><em>Note: The entire view tree is single threaded. You must always be on 502 * the UI thread when calling any method on any view.</em> 503 * If you are doing work on other threads and want to update the state of a view 504 * from that thread, you should use a {@link Handler}. 505 * </p> 506 * 507 * <a name="FocusHandling"></a> 508 * <h3>Focus Handling</h3> 509 * <p> 510 * The framework will handle routine focus movement in response to user input. 511 * This includes changing the focus as views are removed or hidden, or as new 512 * views become available. Views indicate their willingness to take focus 513 * through the {@link #isFocusable} method. To change whether a view can take 514 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 515 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 516 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 517 * </p> 518 * <p> 519 * Focus movement is based on an algorithm which finds the nearest neighbor in a 520 * given direction. In rare cases, the default algorithm may not match the 521 * intended behavior of the developer. In these situations, you can provide 522 * explicit overrides by using these XML attributes in the layout file: 523 * <pre> 524 * nextFocusDown 525 * nextFocusLeft 526 * nextFocusRight 527 * nextFocusUp 528 * </pre> 529 * </p> 530 * 531 * 532 * <p> 533 * To get a particular view to take focus, call {@link #requestFocus()}. 534 * </p> 535 * 536 * <a name="TouchMode"></a> 537 * <h3>Touch Mode</h3> 538 * <p> 539 * When a user is navigating a user interface via directional keys such as a D-pad, it is 540 * necessary to give focus to actionable items such as buttons so the user can see 541 * what will take input. If the device has touch capabilities, however, and the user 542 * begins interacting with the interface by touching it, it is no longer necessary to 543 * always highlight, or give focus to, a particular view. This motivates a mode 544 * for interaction named 'touch mode'. 545 * </p> 546 * <p> 547 * For a touch capable device, once the user touches the screen, the device 548 * will enter touch mode. From this point onward, only views for which 549 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 550 * Other views that are touchable, like buttons, will not take focus when touched; they will 551 * only fire the on click listeners. 552 * </p> 553 * <p> 554 * Any time a user hits a directional key, such as a D-pad direction, the view device will 555 * exit touch mode, and find a view to take focus, so that the user may resume interacting 556 * with the user interface without touching the screen again. 557 * </p> 558 * <p> 559 * The touch mode state is maintained across {@link android.app.Activity}s. Call 560 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 561 * </p> 562 * 563 * <a name="Scrolling"></a> 564 * <h3>Scrolling</h3> 565 * <p> 566 * The framework provides basic support for views that wish to internally 567 * scroll their content. This includes keeping track of the X and Y scroll 568 * offset as well as mechanisms for drawing scrollbars. See 569 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 570 * {@link #awakenScrollBars()} for more details. 571 * </p> 572 * 573 * <a name="Tags"></a> 574 * <h3>Tags</h3> 575 * <p> 576 * Unlike IDs, tags are not used to identify views. Tags are essentially an 577 * extra piece of information that can be associated with a view. They are most 578 * often used as a convenience to store data related to views in the views 579 * themselves rather than by putting them in a separate structure. 580 * </p> 581 * <p> 582 * Tags may be specified with character sequence values in layout XML as either 583 * a single tag using the {@link android.R.styleable#View_tag android:tag} 584 * attribute or multiple tags using the {@code <tag>} child element: 585 * <pre> 586 * <View ... 587 * android:tag="@string/mytag_value" /> 588 * <View ...> 589 * <tag android:id="@+id/mytag" 590 * android:value="@string/mytag_value" /> 591 * </View> 592 * </pre> 593 * </p> 594 * <p> 595 * Tags may also be specified with arbitrary objects from code using 596 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 597 * </p> 598 * 599 * <a name="Themes"></a> 600 * <h3>Themes</h3> 601 * <p> 602 * By default, Views are created using the theme of the Context object supplied 603 * to their constructor; however, a different theme may be specified by using 604 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 605 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 606 * code. 607 * </p> 608 * <p> 609 * When the {@link android.R.styleable#View_theme android:theme} attribute is 610 * used in XML, the specified theme is applied on top of the inflation 611 * context's theme (see {@link LayoutInflater}) and used for the view itself as 612 * well as any child elements. 613 * </p> 614 * <p> 615 * In the following example, both views will be created using the Material dark 616 * color scheme; however, because an overlay theme is used which only defines a 617 * subset of attributes, the value of 618 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 619 * the inflation context's theme (e.g. the Activity theme) will be preserved. 620 * <pre> 621 * <LinearLayout 622 * ... 623 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 624 * <View ...> 625 * </LinearLayout> 626 * </pre> 627 * </p> 628 * 629 * <a name="Properties"></a> 630 * <h3>Properties</h3> 631 * <p> 632 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 633 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 634 * available both in the {@link Property} form as well as in similarly-named setter/getter 635 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 636 * be used to set persistent state associated with these rendering-related properties on the view. 637 * The properties and methods can also be used in conjunction with 638 * {@link android.animation.Animator Animator}-based animations, described more in the 639 * <a href="#Animation">Animation</a> section. 640 * </p> 641 * 642 * <a name="Animation"></a> 643 * <h3>Animation</h3> 644 * <p> 645 * Starting with Android 3.0, the preferred way of animating views is to use the 646 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 647 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 648 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 649 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 650 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 651 * makes animating these View properties particularly easy and efficient. 652 * </p> 653 * <p> 654 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 655 * You can attach an {@link Animation} object to a view using 656 * {@link #setAnimation(Animation)} or 657 * {@link #startAnimation(Animation)}. The animation can alter the scale, 658 * rotation, translation and alpha of a view over time. If the animation is 659 * attached to a view that has children, the animation will affect the entire 660 * subtree rooted by that node. When an animation is started, the framework will 661 * take care of redrawing the appropriate views until the animation completes. 662 * </p> 663 * 664 * <a name="Security"></a> 665 * <h3>Security</h3> 666 * <p> 667 * Sometimes it is essential that an application be able to verify that an action 668 * is being performed with the full knowledge and consent of the user, such as 669 * granting a permission request, making a purchase or clicking on an advertisement. 670 * Unfortunately, a malicious application could try to spoof the user into 671 * performing these actions, unaware, by concealing the intended purpose of the view. 672 * As a remedy, the framework offers a touch filtering mechanism that can be used to 673 * improve the security of views that provide access to sensitive functionality. 674 * </p><p> 675 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 676 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 677 * will discard touches that are received whenever the view's window is obscured by 678 * another visible window. As a result, the view will not receive touches whenever a 679 * toast, dialog or other window appears above the view's window. 680 * </p><p> 681 * For more fine-grained control over security, consider overriding the 682 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 683 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 684 * </p> 685 * 686 * @attr ref android.R.styleable#View_alpha 687 * @attr ref android.R.styleable#View_background 688 * @attr ref android.R.styleable#View_clickable 689 * @attr ref android.R.styleable#View_contentDescription 690 * @attr ref android.R.styleable#View_drawingCacheQuality 691 * @attr ref android.R.styleable#View_duplicateParentState 692 * @attr ref android.R.styleable#View_id 693 * @attr ref android.R.styleable#View_requiresFadingEdge 694 * @attr ref android.R.styleable#View_fadeScrollbars 695 * @attr ref android.R.styleable#View_fadingEdgeLength 696 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 697 * @attr ref android.R.styleable#View_fitsSystemWindows 698 * @attr ref android.R.styleable#View_isScrollContainer 699 * @attr ref android.R.styleable#View_focusable 700 * @attr ref android.R.styleable#View_focusableInTouchMode 701 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 702 * @attr ref android.R.styleable#View_keepScreenOn 703 * @attr ref android.R.styleable#View_layerType 704 * @attr ref android.R.styleable#View_layoutDirection 705 * @attr ref android.R.styleable#View_longClickable 706 * @attr ref android.R.styleable#View_minHeight 707 * @attr ref android.R.styleable#View_minWidth 708 * @attr ref android.R.styleable#View_nextFocusDown 709 * @attr ref android.R.styleable#View_nextFocusLeft 710 * @attr ref android.R.styleable#View_nextFocusRight 711 * @attr ref android.R.styleable#View_nextFocusUp 712 * @attr ref android.R.styleable#View_onClick 713 * @attr ref android.R.styleable#View_padding 714 * @attr ref android.R.styleable#View_paddingBottom 715 * @attr ref android.R.styleable#View_paddingLeft 716 * @attr ref android.R.styleable#View_paddingRight 717 * @attr ref android.R.styleable#View_paddingTop 718 * @attr ref android.R.styleable#View_paddingStart 719 * @attr ref android.R.styleable#View_paddingEnd 720 * @attr ref android.R.styleable#View_saveEnabled 721 * @attr ref android.R.styleable#View_rotation 722 * @attr ref android.R.styleable#View_rotationX 723 * @attr ref android.R.styleable#View_rotationY 724 * @attr ref android.R.styleable#View_scaleX 725 * @attr ref android.R.styleable#View_scaleY 726 * @attr ref android.R.styleable#View_scrollX 727 * @attr ref android.R.styleable#View_scrollY 728 * @attr ref android.R.styleable#View_scrollbarSize 729 * @attr ref android.R.styleable#View_scrollbarStyle 730 * @attr ref android.R.styleable#View_scrollbars 731 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 732 * @attr ref android.R.styleable#View_scrollbarFadeDuration 733 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 734 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 735 * @attr ref android.R.styleable#View_scrollbarThumbVertical 736 * @attr ref android.R.styleable#View_scrollbarTrackVertical 737 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 739 * @attr ref android.R.styleable#View_stateListAnimator 740 * @attr ref android.R.styleable#View_transitionName 741 * @attr ref android.R.styleable#View_soundEffectsEnabled 742 * @attr ref android.R.styleable#View_tag 743 * @attr ref android.R.styleable#View_textAlignment 744 * @attr ref android.R.styleable#View_textDirection 745 * @attr ref android.R.styleable#View_transformPivotX 746 * @attr ref android.R.styleable#View_transformPivotY 747 * @attr ref android.R.styleable#View_translationX 748 * @attr ref android.R.styleable#View_translationY 749 * @attr ref android.R.styleable#View_translationZ 750 * @attr ref android.R.styleable#View_visibility 751 * @attr ref android.R.styleable#View_theme 752 * 753 * @see android.view.ViewGroup 754 */ 755@UiThread 756public class View implements Drawable.Callback, KeyEvent.Callback, 757 AccessibilityEventSource { 758 private static final boolean DBG = false; 759 760 /** 761 * The logging tag used by this class with android.util.Log. 762 */ 763 protected static final String VIEW_LOG_TAG = "View"; 764 765 /** 766 * When set to true, apps will draw debugging information about their layouts. 767 * 768 * @hide 769 */ 770 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 771 772 /** 773 * When set to true, this view will save its attribute data. 774 * 775 * @hide 776 */ 777 public static boolean mDebugViewAttributes = false; 778 779 /** 780 * Used to mark a View that has no ID. 781 */ 782 public static final int NO_ID = -1; 783 784 /** 785 * Signals that compatibility booleans have been initialized according to 786 * target SDK versions. 787 */ 788 private static boolean sCompatibilityDone = false; 789 790 /** 791 * Use the old (broken) way of building MeasureSpecs. 792 */ 793 private static boolean sUseBrokenMakeMeasureSpec = false; 794 795 /** 796 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 797 */ 798 static boolean sUseZeroUnspecifiedMeasureSpec = false; 799 800 /** 801 * Ignore any optimizations using the measure cache. 802 */ 803 private static boolean sIgnoreMeasureCache = false; 804 805 /** 806 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 807 */ 808 private static boolean sAlwaysRemeasureExactly = false; 809 810 /** 811 * Relax constraints around whether setLayoutParams() must be called after 812 * modifying the layout params. 813 */ 814 private static boolean sLayoutParamsAlwaysChanged = false; 815 816 /** 817 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 818 * without throwing 819 */ 820 static boolean sTextureViewIgnoresDrawableSetters = false; 821 822 /** 823 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 824 * calling setFlags. 825 */ 826 private static final int NOT_FOCUSABLE = 0x00000000; 827 828 /** 829 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 830 * setFlags. 831 */ 832 private static final int FOCUSABLE = 0x00000001; 833 834 /** 835 * Mask for use with setFlags indicating bits used for focus. 836 */ 837 private static final int FOCUSABLE_MASK = 0x00000001; 838 839 /** 840 * This view will adjust its padding to fit sytem windows (e.g. status bar) 841 */ 842 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 843 844 /** @hide */ 845 @IntDef({VISIBLE, INVISIBLE, GONE}) 846 @Retention(RetentionPolicy.SOURCE) 847 public @interface Visibility {} 848 849 /** 850 * This view is visible. 851 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 852 * android:visibility}. 853 */ 854 public static final int VISIBLE = 0x00000000; 855 856 /** 857 * This view is invisible, but it still takes up space for layout purposes. 858 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 859 * android:visibility}. 860 */ 861 public static final int INVISIBLE = 0x00000004; 862 863 /** 864 * This view is invisible, and it doesn't take any space for layout 865 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 866 * android:visibility}. 867 */ 868 public static final int GONE = 0x00000008; 869 870 /** 871 * Mask for use with setFlags indicating bits used for visibility. 872 * {@hide} 873 */ 874 static final int VISIBILITY_MASK = 0x0000000C; 875 876 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 877 878 /** 879 * This view is enabled. Interpretation varies by subclass. 880 * Use with ENABLED_MASK when calling setFlags. 881 * {@hide} 882 */ 883 static final int ENABLED = 0x00000000; 884 885 /** 886 * This view is disabled. Interpretation varies by subclass. 887 * Use with ENABLED_MASK when calling setFlags. 888 * {@hide} 889 */ 890 static final int DISABLED = 0x00000020; 891 892 /** 893 * Mask for use with setFlags indicating bits used for indicating whether 894 * this view is enabled 895 * {@hide} 896 */ 897 static final int ENABLED_MASK = 0x00000020; 898 899 /** 900 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 901 * called and further optimizations will be performed. It is okay to have 902 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 903 * {@hide} 904 */ 905 static final int WILL_NOT_DRAW = 0x00000080; 906 907 /** 908 * Mask for use with setFlags indicating bits used for indicating whether 909 * this view is will draw 910 * {@hide} 911 */ 912 static final int DRAW_MASK = 0x00000080; 913 914 /** 915 * <p>This view doesn't show scrollbars.</p> 916 * {@hide} 917 */ 918 static final int SCROLLBARS_NONE = 0x00000000; 919 920 /** 921 * <p>This view shows horizontal scrollbars.</p> 922 * {@hide} 923 */ 924 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 925 926 /** 927 * <p>This view shows vertical scrollbars.</p> 928 * {@hide} 929 */ 930 static final int SCROLLBARS_VERTICAL = 0x00000200; 931 932 /** 933 * <p>Mask for use with setFlags indicating bits used for indicating which 934 * scrollbars are enabled.</p> 935 * {@hide} 936 */ 937 static final int SCROLLBARS_MASK = 0x00000300; 938 939 /** 940 * Indicates that the view should filter touches when its window is obscured. 941 * Refer to the class comments for more information about this security feature. 942 * {@hide} 943 */ 944 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 945 946 /** 947 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 948 * that they are optional and should be skipped if the window has 949 * requested system UI flags that ignore those insets for layout. 950 */ 951 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 952 953 /** 954 * <p>This view doesn't show fading edges.</p> 955 * {@hide} 956 */ 957 static final int FADING_EDGE_NONE = 0x00000000; 958 959 /** 960 * <p>This view shows horizontal fading edges.</p> 961 * {@hide} 962 */ 963 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 964 965 /** 966 * <p>This view shows vertical fading edges.</p> 967 * {@hide} 968 */ 969 static final int FADING_EDGE_VERTICAL = 0x00002000; 970 971 /** 972 * <p>Mask for use with setFlags indicating bits used for indicating which 973 * fading edges are enabled.</p> 974 * {@hide} 975 */ 976 static final int FADING_EDGE_MASK = 0x00003000; 977 978 /** 979 * <p>Indicates this view can be clicked. When clickable, a View reacts 980 * to clicks by notifying the OnClickListener.<p> 981 * {@hide} 982 */ 983 static final int CLICKABLE = 0x00004000; 984 985 /** 986 * <p>Indicates this view is caching its drawing into a bitmap.</p> 987 * {@hide} 988 */ 989 static final int DRAWING_CACHE_ENABLED = 0x00008000; 990 991 /** 992 * <p>Indicates that no icicle should be saved for this view.<p> 993 * {@hide} 994 */ 995 static final int SAVE_DISABLED = 0x000010000; 996 997 /** 998 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 999 * property.</p> 1000 * {@hide} 1001 */ 1002 static final int SAVE_DISABLED_MASK = 0x000010000; 1003 1004 /** 1005 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1006 * {@hide} 1007 */ 1008 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1009 1010 /** 1011 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1012 * {@hide} 1013 */ 1014 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1015 1016 /** @hide */ 1017 @Retention(RetentionPolicy.SOURCE) 1018 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1019 public @interface DrawingCacheQuality {} 1020 1021 /** 1022 * <p>Enables low quality mode for the drawing cache.</p> 1023 */ 1024 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1025 1026 /** 1027 * <p>Enables high quality mode for the drawing cache.</p> 1028 */ 1029 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1030 1031 /** 1032 * <p>Enables automatic quality mode for the drawing cache.</p> 1033 */ 1034 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1035 1036 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1037 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1038 }; 1039 1040 /** 1041 * <p>Mask for use with setFlags indicating bits used for the cache 1042 * quality property.</p> 1043 * {@hide} 1044 */ 1045 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1046 1047 /** 1048 * <p> 1049 * Indicates this view can be long clicked. When long clickable, a View 1050 * reacts to long clicks by notifying the OnLongClickListener or showing a 1051 * context menu. 1052 * </p> 1053 * {@hide} 1054 */ 1055 static final int LONG_CLICKABLE = 0x00200000; 1056 1057 /** 1058 * <p>Indicates that this view gets its drawable states from its direct parent 1059 * and ignores its original internal states.</p> 1060 * 1061 * @hide 1062 */ 1063 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1064 1065 /** 1066 * <p> 1067 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1068 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1069 * OnContextClickListener. 1070 * </p> 1071 * {@hide} 1072 */ 1073 static final int CONTEXT_CLICKABLE = 0x00800000; 1074 1075 1076 /** @hide */ 1077 @IntDef({ 1078 SCROLLBARS_INSIDE_OVERLAY, 1079 SCROLLBARS_INSIDE_INSET, 1080 SCROLLBARS_OUTSIDE_OVERLAY, 1081 SCROLLBARS_OUTSIDE_INSET 1082 }) 1083 @Retention(RetentionPolicy.SOURCE) 1084 public @interface ScrollBarStyle {} 1085 1086 /** 1087 * The scrollbar style to display the scrollbars inside the content area, 1088 * without increasing the padding. The scrollbars will be overlaid with 1089 * translucency on the view's content. 1090 */ 1091 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1092 1093 /** 1094 * The scrollbar style to display the scrollbars inside the padded area, 1095 * increasing the padding of the view. The scrollbars will not overlap the 1096 * content area of the view. 1097 */ 1098 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1099 1100 /** 1101 * The scrollbar style to display the scrollbars at the edge of the view, 1102 * without increasing the padding. The scrollbars will be overlaid with 1103 * translucency. 1104 */ 1105 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1106 1107 /** 1108 * The scrollbar style to display the scrollbars at the edge of the view, 1109 * increasing the padding of the view. The scrollbars will only overlap the 1110 * background, if any. 1111 */ 1112 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1113 1114 /** 1115 * Mask to check if the scrollbar style is overlay or inset. 1116 * {@hide} 1117 */ 1118 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1119 1120 /** 1121 * Mask to check if the scrollbar style is inside or outside. 1122 * {@hide} 1123 */ 1124 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1125 1126 /** 1127 * Mask for scrollbar style. 1128 * {@hide} 1129 */ 1130 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1131 1132 /** 1133 * View flag indicating that the screen should remain on while the 1134 * window containing this view is visible to the user. This effectively 1135 * takes care of automatically setting the WindowManager's 1136 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1137 */ 1138 public static final int KEEP_SCREEN_ON = 0x04000000; 1139 1140 /** 1141 * View flag indicating whether this view should have sound effects enabled 1142 * for events such as clicking and touching. 1143 */ 1144 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1145 1146 /** 1147 * View flag indicating whether this view should have haptic feedback 1148 * enabled for events such as long presses. 1149 */ 1150 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1151 1152 /** 1153 * <p>Indicates that the view hierarchy should stop saving state when 1154 * it reaches this view. If state saving is initiated immediately at 1155 * the view, it will be allowed. 1156 * {@hide} 1157 */ 1158 static final int PARENT_SAVE_DISABLED = 0x20000000; 1159 1160 /** 1161 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1162 * {@hide} 1163 */ 1164 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1165 1166 /** @hide */ 1167 @IntDef(flag = true, 1168 value = { 1169 FOCUSABLES_ALL, 1170 FOCUSABLES_TOUCH_MODE 1171 }) 1172 @Retention(RetentionPolicy.SOURCE) 1173 public @interface FocusableMode {} 1174 1175 /** 1176 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1177 * should add all focusable Views regardless if they are focusable in touch mode. 1178 */ 1179 public static final int FOCUSABLES_ALL = 0x00000000; 1180 1181 /** 1182 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1183 * should add only Views focusable in touch mode. 1184 */ 1185 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1186 1187 /** @hide */ 1188 @IntDef({ 1189 FOCUS_BACKWARD, 1190 FOCUS_FORWARD, 1191 FOCUS_LEFT, 1192 FOCUS_UP, 1193 FOCUS_RIGHT, 1194 FOCUS_DOWN 1195 }) 1196 @Retention(RetentionPolicy.SOURCE) 1197 public @interface FocusDirection {} 1198 1199 /** @hide */ 1200 @IntDef({ 1201 FOCUS_LEFT, 1202 FOCUS_UP, 1203 FOCUS_RIGHT, 1204 FOCUS_DOWN 1205 }) 1206 @Retention(RetentionPolicy.SOURCE) 1207 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1208 1209 /** 1210 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1211 * item. 1212 */ 1213 public static final int FOCUS_BACKWARD = 0x00000001; 1214 1215 /** 1216 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1217 * item. 1218 */ 1219 public static final int FOCUS_FORWARD = 0x00000002; 1220 1221 /** 1222 * Use with {@link #focusSearch(int)}. Move focus to the left. 1223 */ 1224 public static final int FOCUS_LEFT = 0x00000011; 1225 1226 /** 1227 * Use with {@link #focusSearch(int)}. Move focus up. 1228 */ 1229 public static final int FOCUS_UP = 0x00000021; 1230 1231 /** 1232 * Use with {@link #focusSearch(int)}. Move focus to the right. 1233 */ 1234 public static final int FOCUS_RIGHT = 0x00000042; 1235 1236 /** 1237 * Use with {@link #focusSearch(int)}. Move focus down. 1238 */ 1239 public static final int FOCUS_DOWN = 0x00000082; 1240 1241 /** 1242 * Bits of {@link #getMeasuredWidthAndState()} and 1243 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1244 */ 1245 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1246 1247 /** 1248 * Bits of {@link #getMeasuredWidthAndState()} and 1249 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1250 */ 1251 public static final int MEASURED_STATE_MASK = 0xff000000; 1252 1253 /** 1254 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1255 * for functions that combine both width and height into a single int, 1256 * such as {@link #getMeasuredState()} and the childState argument of 1257 * {@link #resolveSizeAndState(int, int, int)}. 1258 */ 1259 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1260 1261 /** 1262 * Bit of {@link #getMeasuredWidthAndState()} and 1263 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1264 * is smaller that the space the view would like to have. 1265 */ 1266 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1267 1268 /** 1269 * Base View state sets 1270 */ 1271 // Singles 1272 /** 1273 * Indicates the view has no states set. States are used with 1274 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1275 * view depending on its state. 1276 * 1277 * @see android.graphics.drawable.Drawable 1278 * @see #getDrawableState() 1279 */ 1280 protected static final int[] EMPTY_STATE_SET; 1281 /** 1282 * Indicates the view is enabled. States are used with 1283 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1284 * view depending on its state. 1285 * 1286 * @see android.graphics.drawable.Drawable 1287 * @see #getDrawableState() 1288 */ 1289 protected static final int[] ENABLED_STATE_SET; 1290 /** 1291 * Indicates the view is focused. States are used with 1292 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1293 * view depending on its state. 1294 * 1295 * @see android.graphics.drawable.Drawable 1296 * @see #getDrawableState() 1297 */ 1298 protected static final int[] FOCUSED_STATE_SET; 1299 /** 1300 * Indicates the view is selected. States are used with 1301 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1302 * view depending on its state. 1303 * 1304 * @see android.graphics.drawable.Drawable 1305 * @see #getDrawableState() 1306 */ 1307 protected static final int[] SELECTED_STATE_SET; 1308 /** 1309 * Indicates the view is pressed. States are used with 1310 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1311 * view depending on its state. 1312 * 1313 * @see android.graphics.drawable.Drawable 1314 * @see #getDrawableState() 1315 */ 1316 protected static final int[] PRESSED_STATE_SET; 1317 /** 1318 * Indicates the view's window has focus. States are used with 1319 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1320 * view depending on its state. 1321 * 1322 * @see android.graphics.drawable.Drawable 1323 * @see #getDrawableState() 1324 */ 1325 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1326 // Doubles 1327 /** 1328 * Indicates the view is enabled and has the focus. 1329 * 1330 * @see #ENABLED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is enabled and selected. 1336 * 1337 * @see #ENABLED_STATE_SET 1338 * @see #SELECTED_STATE_SET 1339 */ 1340 protected static final int[] ENABLED_SELECTED_STATE_SET; 1341 /** 1342 * Indicates the view is enabled and that its window has focus. 1343 * 1344 * @see #ENABLED_STATE_SET 1345 * @see #WINDOW_FOCUSED_STATE_SET 1346 */ 1347 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1348 /** 1349 * Indicates the view is focused and selected. 1350 * 1351 * @see #FOCUSED_STATE_SET 1352 * @see #SELECTED_STATE_SET 1353 */ 1354 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1355 /** 1356 * Indicates the view has the focus and that its window has the focus. 1357 * 1358 * @see #FOCUSED_STATE_SET 1359 * @see #WINDOW_FOCUSED_STATE_SET 1360 */ 1361 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1362 /** 1363 * Indicates the view is selected and that its window has the focus. 1364 * 1365 * @see #SELECTED_STATE_SET 1366 * @see #WINDOW_FOCUSED_STATE_SET 1367 */ 1368 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1369 // Triples 1370 /** 1371 * Indicates the view is enabled, focused and selected. 1372 * 1373 * @see #ENABLED_STATE_SET 1374 * @see #FOCUSED_STATE_SET 1375 * @see #SELECTED_STATE_SET 1376 */ 1377 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1378 /** 1379 * Indicates the view is enabled, focused and its window has the focus. 1380 * 1381 * @see #ENABLED_STATE_SET 1382 * @see #FOCUSED_STATE_SET 1383 * @see #WINDOW_FOCUSED_STATE_SET 1384 */ 1385 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1386 /** 1387 * Indicates the view is enabled, selected and its window has the focus. 1388 * 1389 * @see #ENABLED_STATE_SET 1390 * @see #SELECTED_STATE_SET 1391 * @see #WINDOW_FOCUSED_STATE_SET 1392 */ 1393 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1394 /** 1395 * Indicates the view is focused, selected and its window has the focus. 1396 * 1397 * @see #FOCUSED_STATE_SET 1398 * @see #SELECTED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1402 /** 1403 * Indicates the view is enabled, focused, selected and its window 1404 * has the focus. 1405 * 1406 * @see #ENABLED_STATE_SET 1407 * @see #FOCUSED_STATE_SET 1408 * @see #SELECTED_STATE_SET 1409 * @see #WINDOW_FOCUSED_STATE_SET 1410 */ 1411 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1412 /** 1413 * Indicates the view is pressed and its window has the focus. 1414 * 1415 * @see #PRESSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed and selected. 1421 * 1422 * @see #PRESSED_STATE_SET 1423 * @see #SELECTED_STATE_SET 1424 */ 1425 protected static final int[] PRESSED_SELECTED_STATE_SET; 1426 /** 1427 * Indicates the view is pressed, selected and its window has the focus. 1428 * 1429 * @see #PRESSED_STATE_SET 1430 * @see #SELECTED_STATE_SET 1431 * @see #WINDOW_FOCUSED_STATE_SET 1432 */ 1433 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1434 /** 1435 * Indicates the view is pressed and focused. 1436 * 1437 * @see #PRESSED_STATE_SET 1438 * @see #FOCUSED_STATE_SET 1439 */ 1440 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1441 /** 1442 * Indicates the view is pressed, focused and its window has the focus. 1443 * 1444 * @see #PRESSED_STATE_SET 1445 * @see #FOCUSED_STATE_SET 1446 * @see #WINDOW_FOCUSED_STATE_SET 1447 */ 1448 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1449 /** 1450 * Indicates the view is pressed, focused and selected. 1451 * 1452 * @see #PRESSED_STATE_SET 1453 * @see #SELECTED_STATE_SET 1454 * @see #FOCUSED_STATE_SET 1455 */ 1456 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1457 /** 1458 * Indicates the view is pressed, focused, selected and its window has the focus. 1459 * 1460 * @see #PRESSED_STATE_SET 1461 * @see #FOCUSED_STATE_SET 1462 * @see #SELECTED_STATE_SET 1463 * @see #WINDOW_FOCUSED_STATE_SET 1464 */ 1465 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1466 /** 1467 * Indicates the view is pressed and enabled. 1468 * 1469 * @see #PRESSED_STATE_SET 1470 * @see #ENABLED_STATE_SET 1471 */ 1472 protected static final int[] PRESSED_ENABLED_STATE_SET; 1473 /** 1474 * Indicates the view is pressed, enabled and its window has the focus. 1475 * 1476 * @see #PRESSED_STATE_SET 1477 * @see #ENABLED_STATE_SET 1478 * @see #WINDOW_FOCUSED_STATE_SET 1479 */ 1480 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1481 /** 1482 * Indicates the view is pressed, enabled and selected. 1483 * 1484 * @see #PRESSED_STATE_SET 1485 * @see #ENABLED_STATE_SET 1486 * @see #SELECTED_STATE_SET 1487 */ 1488 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1489 /** 1490 * Indicates the view is pressed, enabled, selected and its window has the 1491 * focus. 1492 * 1493 * @see #PRESSED_STATE_SET 1494 * @see #ENABLED_STATE_SET 1495 * @see #SELECTED_STATE_SET 1496 * @see #WINDOW_FOCUSED_STATE_SET 1497 */ 1498 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1499 /** 1500 * Indicates the view is pressed, enabled and focused. 1501 * 1502 * @see #PRESSED_STATE_SET 1503 * @see #ENABLED_STATE_SET 1504 * @see #FOCUSED_STATE_SET 1505 */ 1506 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1507 /** 1508 * Indicates the view is pressed, enabled, focused and its window has the 1509 * focus. 1510 * 1511 * @see #PRESSED_STATE_SET 1512 * @see #ENABLED_STATE_SET 1513 * @see #FOCUSED_STATE_SET 1514 * @see #WINDOW_FOCUSED_STATE_SET 1515 */ 1516 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1517 /** 1518 * Indicates the view is pressed, enabled, focused and selected. 1519 * 1520 * @see #PRESSED_STATE_SET 1521 * @see #ENABLED_STATE_SET 1522 * @see #SELECTED_STATE_SET 1523 * @see #FOCUSED_STATE_SET 1524 */ 1525 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1526 /** 1527 * Indicates the view is pressed, enabled, focused, selected and its window 1528 * has the focus. 1529 * 1530 * @see #PRESSED_STATE_SET 1531 * @see #ENABLED_STATE_SET 1532 * @see #SELECTED_STATE_SET 1533 * @see #FOCUSED_STATE_SET 1534 * @see #WINDOW_FOCUSED_STATE_SET 1535 */ 1536 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1537 1538 static { 1539 EMPTY_STATE_SET = StateSet.get(0); 1540 1541 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1542 1543 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1544 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1545 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1546 1547 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1548 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1549 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1550 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1551 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1552 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1553 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1554 | StateSet.VIEW_STATE_FOCUSED); 1555 1556 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1557 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1558 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1559 ENABLED_SELECTED_STATE_SET = StateSet.get( 1560 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1561 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1562 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1563 | StateSet.VIEW_STATE_ENABLED); 1564 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1565 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1566 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1567 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1568 | StateSet.VIEW_STATE_ENABLED); 1569 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1570 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1571 | StateSet.VIEW_STATE_ENABLED); 1572 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1573 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1574 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1575 1576 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1577 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1578 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1579 PRESSED_SELECTED_STATE_SET = StateSet.get( 1580 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1581 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1582 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1583 | StateSet.VIEW_STATE_PRESSED); 1584 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1585 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1586 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1587 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1588 | StateSet.VIEW_STATE_PRESSED); 1589 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1590 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1591 | StateSet.VIEW_STATE_PRESSED); 1592 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1593 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1594 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1595 PRESSED_ENABLED_STATE_SET = StateSet.get( 1596 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1597 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1598 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1599 | StateSet.VIEW_STATE_PRESSED); 1600 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1601 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1602 | StateSet.VIEW_STATE_PRESSED); 1603 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1604 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1605 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1606 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1607 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1608 | StateSet.VIEW_STATE_PRESSED); 1609 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1610 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1611 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1612 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1613 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1614 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1615 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1616 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1617 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1618 | StateSet.VIEW_STATE_PRESSED); 1619 } 1620 1621 /** 1622 * Accessibility event types that are dispatched for text population. 1623 */ 1624 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1625 AccessibilityEvent.TYPE_VIEW_CLICKED 1626 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1627 | AccessibilityEvent.TYPE_VIEW_SELECTED 1628 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1629 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1630 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1631 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1632 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1633 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1634 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1635 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1636 1637 /** 1638 * Temporary Rect currently for use in setBackground(). This will probably 1639 * be extended in the future to hold our own class with more than just 1640 * a Rect. :) 1641 */ 1642 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1643 1644 /** 1645 * Map used to store views' tags. 1646 */ 1647 private SparseArray<Object> mKeyedTags; 1648 1649 /** 1650 * The next available accessibility id. 1651 */ 1652 private static int sNextAccessibilityViewId; 1653 1654 /** 1655 * The animation currently associated with this view. 1656 * @hide 1657 */ 1658 protected Animation mCurrentAnimation = null; 1659 1660 /** 1661 * Width as measured during measure pass. 1662 * {@hide} 1663 */ 1664 @ViewDebug.ExportedProperty(category = "measurement") 1665 int mMeasuredWidth; 1666 1667 /** 1668 * Height as measured during measure pass. 1669 * {@hide} 1670 */ 1671 @ViewDebug.ExportedProperty(category = "measurement") 1672 int mMeasuredHeight; 1673 1674 /** 1675 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1676 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1677 * its display list. This flag, used only when hw accelerated, allows us to clear the 1678 * flag while retaining this information until it's needed (at getDisplayList() time and 1679 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1680 * 1681 * {@hide} 1682 */ 1683 boolean mRecreateDisplayList = false; 1684 1685 /** 1686 * The view's identifier. 1687 * {@hide} 1688 * 1689 * @see #setId(int) 1690 * @see #getId() 1691 */ 1692 @IdRes 1693 @ViewDebug.ExportedProperty(resolveId = true) 1694 int mID = NO_ID; 1695 1696 /** 1697 * The stable ID of this view for accessibility purposes. 1698 */ 1699 int mAccessibilityViewId = NO_ID; 1700 1701 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1702 1703 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1704 1705 /** 1706 * The view's tag. 1707 * {@hide} 1708 * 1709 * @see #setTag(Object) 1710 * @see #getTag() 1711 */ 1712 protected Object mTag = null; 1713 1714 // for mPrivateFlags: 1715 /** {@hide} */ 1716 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1717 /** {@hide} */ 1718 static final int PFLAG_FOCUSED = 0x00000002; 1719 /** {@hide} */ 1720 static final int PFLAG_SELECTED = 0x00000004; 1721 /** {@hide} */ 1722 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1723 /** {@hide} */ 1724 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1725 /** {@hide} */ 1726 static final int PFLAG_DRAWN = 0x00000020; 1727 /** 1728 * When this flag is set, this view is running an animation on behalf of its 1729 * children and should therefore not cancel invalidate requests, even if they 1730 * lie outside of this view's bounds. 1731 * 1732 * {@hide} 1733 */ 1734 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1735 /** {@hide} */ 1736 static final int PFLAG_SKIP_DRAW = 0x00000080; 1737 /** {@hide} */ 1738 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1739 /** {@hide} */ 1740 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1741 /** {@hide} */ 1742 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1743 /** {@hide} */ 1744 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1745 /** {@hide} */ 1746 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1747 1748 private static final int PFLAG_PRESSED = 0x00004000; 1749 1750 /** {@hide} */ 1751 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1752 /** 1753 * Flag used to indicate that this view should be drawn once more (and only once 1754 * more) after its animation has completed. 1755 * {@hide} 1756 */ 1757 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1758 1759 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1760 1761 /** 1762 * Indicates that the View returned true when onSetAlpha() was called and that 1763 * the alpha must be restored. 1764 * {@hide} 1765 */ 1766 static final int PFLAG_ALPHA_SET = 0x00040000; 1767 1768 /** 1769 * Set by {@link #setScrollContainer(boolean)}. 1770 */ 1771 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1772 1773 /** 1774 * Set by {@link #setScrollContainer(boolean)}. 1775 */ 1776 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1777 1778 /** 1779 * View flag indicating whether this view was invalidated (fully or partially.) 1780 * 1781 * @hide 1782 */ 1783 static final int PFLAG_DIRTY = 0x00200000; 1784 1785 /** 1786 * View flag indicating whether this view was invalidated by an opaque 1787 * invalidate request. 1788 * 1789 * @hide 1790 */ 1791 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1792 1793 /** 1794 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1795 * 1796 * @hide 1797 */ 1798 static final int PFLAG_DIRTY_MASK = 0x00600000; 1799 1800 /** 1801 * Indicates whether the background is opaque. 1802 * 1803 * @hide 1804 */ 1805 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1806 1807 /** 1808 * Indicates whether the scrollbars are opaque. 1809 * 1810 * @hide 1811 */ 1812 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1813 1814 /** 1815 * Indicates whether the view is opaque. 1816 * 1817 * @hide 1818 */ 1819 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1820 1821 /** 1822 * Indicates a prepressed state; 1823 * the short time between ACTION_DOWN and recognizing 1824 * a 'real' press. Prepressed is used to recognize quick taps 1825 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1826 * 1827 * @hide 1828 */ 1829 private static final int PFLAG_PREPRESSED = 0x02000000; 1830 1831 /** 1832 * Indicates whether the view is temporarily detached. 1833 * 1834 * @hide 1835 */ 1836 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1837 1838 /** 1839 * Indicates that we should awaken scroll bars once attached 1840 * 1841 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1842 * during window attachment and it is no longer needed. Feel free to repurpose it. 1843 * 1844 * @hide 1845 */ 1846 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1847 1848 /** 1849 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1850 * @hide 1851 */ 1852 private static final int PFLAG_HOVERED = 0x10000000; 1853 1854 /** 1855 * no longer needed, should be reused 1856 */ 1857 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1858 1859 /** {@hide} */ 1860 static final int PFLAG_ACTIVATED = 0x40000000; 1861 1862 /** 1863 * Indicates that this view was specifically invalidated, not just dirtied because some 1864 * child view was invalidated. The flag is used to determine when we need to recreate 1865 * a view's display list (as opposed to just returning a reference to its existing 1866 * display list). 1867 * 1868 * @hide 1869 */ 1870 static final int PFLAG_INVALIDATED = 0x80000000; 1871 1872 /** 1873 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1874 * 1875 * |-------|-------|-------|-------| 1876 * 1 PFLAG2_DRAG_CAN_ACCEPT 1877 * 1 PFLAG2_DRAG_HOVERED 1878 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1879 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1880 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1881 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1882 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1883 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1884 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1885 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1886 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1887 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1888 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1889 * 111 PFLAG2_TEXT_DIRECTION_MASK 1890 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1891 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1892 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1893 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1894 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1895 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1896 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1897 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1898 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1899 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1900 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1901 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1902 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1903 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1904 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1905 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1906 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1907 * 1 PFLAG2_VIEW_QUICK_REJECTED 1908 * 1 PFLAG2_PADDING_RESOLVED 1909 * 1 PFLAG2_DRAWABLE_RESOLVED 1910 * 1 PFLAG2_HAS_TRANSIENT_STATE 1911 * |-------|-------|-------|-------| 1912 */ 1913 1914 /** 1915 * Indicates that this view has reported that it can accept the current drag's content. 1916 * Cleared when the drag operation concludes. 1917 * @hide 1918 */ 1919 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1920 1921 /** 1922 * Indicates that this view is currently directly under the drag location in a 1923 * drag-and-drop operation involving content that it can accept. Cleared when 1924 * the drag exits the view, or when the drag operation concludes. 1925 * @hide 1926 */ 1927 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1928 1929 /** @hide */ 1930 @IntDef({ 1931 LAYOUT_DIRECTION_LTR, 1932 LAYOUT_DIRECTION_RTL, 1933 LAYOUT_DIRECTION_INHERIT, 1934 LAYOUT_DIRECTION_LOCALE 1935 }) 1936 @Retention(RetentionPolicy.SOURCE) 1937 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1938 public @interface LayoutDir {} 1939 1940 /** @hide */ 1941 @IntDef({ 1942 LAYOUT_DIRECTION_LTR, 1943 LAYOUT_DIRECTION_RTL 1944 }) 1945 @Retention(RetentionPolicy.SOURCE) 1946 public @interface ResolvedLayoutDir {} 1947 1948 /** 1949 * A flag to indicate that the layout direction of this view has not been defined yet. 1950 * @hide 1951 */ 1952 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1953 1954 /** 1955 * Horizontal layout direction of this view is from Left to Right. 1956 * Use with {@link #setLayoutDirection}. 1957 */ 1958 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1959 1960 /** 1961 * Horizontal layout direction of this view is from Right to Left. 1962 * Use with {@link #setLayoutDirection}. 1963 */ 1964 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1965 1966 /** 1967 * Horizontal layout direction of this view is inherited from its parent. 1968 * Use with {@link #setLayoutDirection}. 1969 */ 1970 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1971 1972 /** 1973 * Horizontal layout direction of this view is from deduced from the default language 1974 * script for the locale. Use with {@link #setLayoutDirection}. 1975 */ 1976 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1977 1978 /** 1979 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1980 * @hide 1981 */ 1982 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1983 1984 /** 1985 * Mask for use with private flags indicating bits used for horizontal layout direction. 1986 * @hide 1987 */ 1988 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1989 1990 /** 1991 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1992 * right-to-left direction. 1993 * @hide 1994 */ 1995 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1996 1997 /** 1998 * Indicates whether the view horizontal layout direction has been resolved. 1999 * @hide 2000 */ 2001 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2002 2003 /** 2004 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2005 * @hide 2006 */ 2007 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2008 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2009 2010 /* 2011 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2012 * flag value. 2013 * @hide 2014 */ 2015 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2016 LAYOUT_DIRECTION_LTR, 2017 LAYOUT_DIRECTION_RTL, 2018 LAYOUT_DIRECTION_INHERIT, 2019 LAYOUT_DIRECTION_LOCALE 2020 }; 2021 2022 /** 2023 * Default horizontal layout direction. 2024 */ 2025 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2026 2027 /** 2028 * Default horizontal layout direction. 2029 * @hide 2030 */ 2031 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2032 2033 /** 2034 * Text direction is inherited through {@link ViewGroup} 2035 */ 2036 public static final int TEXT_DIRECTION_INHERIT = 0; 2037 2038 /** 2039 * Text direction is using "first strong algorithm". The first strong directional character 2040 * determines the paragraph direction. If there is no strong directional character, the 2041 * paragraph direction is the view's resolved layout direction. 2042 */ 2043 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2044 2045 /** 2046 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2047 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2048 * If there are neither, the paragraph direction is the view's resolved layout direction. 2049 */ 2050 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2051 2052 /** 2053 * Text direction is forced to LTR. 2054 */ 2055 public static final int TEXT_DIRECTION_LTR = 3; 2056 2057 /** 2058 * Text direction is forced to RTL. 2059 */ 2060 public static final int TEXT_DIRECTION_RTL = 4; 2061 2062 /** 2063 * Text direction is coming from the system Locale. 2064 */ 2065 public static final int TEXT_DIRECTION_LOCALE = 5; 2066 2067 /** 2068 * Text direction is using "first strong algorithm". The first strong directional character 2069 * determines the paragraph direction. If there is no strong directional character, the 2070 * paragraph direction is LTR. 2071 */ 2072 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2073 2074 /** 2075 * Text direction is using "first strong algorithm". The first strong directional character 2076 * determines the paragraph direction. If there is no strong directional character, the 2077 * paragraph direction is RTL. 2078 */ 2079 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2080 2081 /** 2082 * Default text direction is inherited 2083 */ 2084 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2085 2086 /** 2087 * Default resolved text direction 2088 * @hide 2089 */ 2090 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2091 2092 /** 2093 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2094 * @hide 2095 */ 2096 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2097 2098 /** 2099 * Mask for use with private flags indicating bits used for text direction. 2100 * @hide 2101 */ 2102 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2103 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2104 2105 /** 2106 * Array of text direction flags for mapping attribute "textDirection" to correct 2107 * flag value. 2108 * @hide 2109 */ 2110 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2111 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2112 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2113 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2114 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2115 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2116 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2117 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2118 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2119 }; 2120 2121 /** 2122 * Indicates whether the view text direction has been resolved. 2123 * @hide 2124 */ 2125 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2126 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2127 2128 /** 2129 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2130 * @hide 2131 */ 2132 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2133 2134 /** 2135 * Mask for use with private flags indicating bits used for resolved text direction. 2136 * @hide 2137 */ 2138 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2139 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2140 2141 /** 2142 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2143 * @hide 2144 */ 2145 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2146 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2147 2148 /** @hide */ 2149 @IntDef({ 2150 TEXT_ALIGNMENT_INHERIT, 2151 TEXT_ALIGNMENT_GRAVITY, 2152 TEXT_ALIGNMENT_CENTER, 2153 TEXT_ALIGNMENT_TEXT_START, 2154 TEXT_ALIGNMENT_TEXT_END, 2155 TEXT_ALIGNMENT_VIEW_START, 2156 TEXT_ALIGNMENT_VIEW_END 2157 }) 2158 @Retention(RetentionPolicy.SOURCE) 2159 public @interface TextAlignment {} 2160 2161 /** 2162 * Default text alignment. The text alignment of this View is inherited from its parent. 2163 * Use with {@link #setTextAlignment(int)} 2164 */ 2165 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2166 2167 /** 2168 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2169 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2170 * 2171 * Use with {@link #setTextAlignment(int)} 2172 */ 2173 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2174 2175 /** 2176 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2177 * 2178 * Use with {@link #setTextAlignment(int)} 2179 */ 2180 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2181 2182 /** 2183 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2184 * 2185 * Use with {@link #setTextAlignment(int)} 2186 */ 2187 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2188 2189 /** 2190 * Center the paragraph, e.g. ALIGN_CENTER. 2191 * 2192 * Use with {@link #setTextAlignment(int)} 2193 */ 2194 public static final int TEXT_ALIGNMENT_CENTER = 4; 2195 2196 /** 2197 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2198 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2199 * 2200 * Use with {@link #setTextAlignment(int)} 2201 */ 2202 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2203 2204 /** 2205 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2206 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2207 * 2208 * Use with {@link #setTextAlignment(int)} 2209 */ 2210 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2211 2212 /** 2213 * Default text alignment is inherited 2214 */ 2215 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2216 2217 /** 2218 * Default resolved text alignment 2219 * @hide 2220 */ 2221 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2222 2223 /** 2224 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2225 * @hide 2226 */ 2227 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2228 2229 /** 2230 * Mask for use with private flags indicating bits used for text alignment. 2231 * @hide 2232 */ 2233 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2234 2235 /** 2236 * Array of text direction flags for mapping attribute "textAlignment" to correct 2237 * flag value. 2238 * @hide 2239 */ 2240 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2241 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2242 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2243 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2244 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2245 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2246 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2247 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2248 }; 2249 2250 /** 2251 * Indicates whether the view text alignment has been resolved. 2252 * @hide 2253 */ 2254 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2255 2256 /** 2257 * Bit shift to get the resolved text alignment. 2258 * @hide 2259 */ 2260 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2261 2262 /** 2263 * Mask for use with private flags indicating bits used for text alignment. 2264 * @hide 2265 */ 2266 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2267 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2268 2269 /** 2270 * Indicates whether if the view text alignment has been resolved to gravity 2271 */ 2272 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2273 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2274 2275 // Accessiblity constants for mPrivateFlags2 2276 2277 /** 2278 * Shift for the bits in {@link #mPrivateFlags2} related to the 2279 * "importantForAccessibility" attribute. 2280 */ 2281 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2282 2283 /** 2284 * Automatically determine whether a view is important for accessibility. 2285 */ 2286 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2287 2288 /** 2289 * The view is important for accessibility. 2290 */ 2291 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2292 2293 /** 2294 * The view is not important for accessibility. 2295 */ 2296 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2297 2298 /** 2299 * The view is not important for accessibility, nor are any of its 2300 * descendant views. 2301 */ 2302 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2303 2304 /** 2305 * The default whether the view is important for accessibility. 2306 */ 2307 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2308 2309 /** 2310 * Mask for obtainig the bits which specify how to determine 2311 * whether a view is important for accessibility. 2312 */ 2313 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2314 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2315 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2316 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2317 2318 /** 2319 * Shift for the bits in {@link #mPrivateFlags2} related to the 2320 * "accessibilityLiveRegion" attribute. 2321 */ 2322 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2323 2324 /** 2325 * Live region mode specifying that accessibility services should not 2326 * automatically announce changes to this view. This is the default live 2327 * region mode for most views. 2328 * <p> 2329 * Use with {@link #setAccessibilityLiveRegion(int)}. 2330 */ 2331 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2332 2333 /** 2334 * Live region mode specifying that accessibility services should announce 2335 * changes to this view. 2336 * <p> 2337 * Use with {@link #setAccessibilityLiveRegion(int)}. 2338 */ 2339 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2340 2341 /** 2342 * Live region mode specifying that accessibility services should interrupt 2343 * ongoing speech to immediately announce changes to this view. 2344 * <p> 2345 * Use with {@link #setAccessibilityLiveRegion(int)}. 2346 */ 2347 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2348 2349 /** 2350 * The default whether the view is important for accessibility. 2351 */ 2352 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2353 2354 /** 2355 * Mask for obtaining the bits which specify a view's accessibility live 2356 * region mode. 2357 */ 2358 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2359 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2360 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2361 2362 /** 2363 * Flag indicating whether a view has accessibility focus. 2364 */ 2365 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2366 2367 /** 2368 * Flag whether the accessibility state of the subtree rooted at this view changed. 2369 */ 2370 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2371 2372 /** 2373 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2374 * is used to check whether later changes to the view's transform should invalidate the 2375 * view to force the quickReject test to run again. 2376 */ 2377 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2378 2379 /** 2380 * Flag indicating that start/end padding has been resolved into left/right padding 2381 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2382 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2383 * during measurement. In some special cases this is required such as when an adapter-based 2384 * view measures prospective children without attaching them to a window. 2385 */ 2386 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2387 2388 /** 2389 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2390 */ 2391 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2392 2393 /** 2394 * Indicates that the view is tracking some sort of transient state 2395 * that the app should not need to be aware of, but that the framework 2396 * should take special care to preserve. 2397 */ 2398 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2399 2400 /** 2401 * Group of bits indicating that RTL properties resolution is done. 2402 */ 2403 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2404 PFLAG2_TEXT_DIRECTION_RESOLVED | 2405 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2406 PFLAG2_PADDING_RESOLVED | 2407 PFLAG2_DRAWABLE_RESOLVED; 2408 2409 // There are a couple of flags left in mPrivateFlags2 2410 2411 /* End of masks for mPrivateFlags2 */ 2412 2413 /** 2414 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2415 * 2416 * |-------|-------|-------|-------| 2417 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2418 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2419 * 1 PFLAG3_IS_LAID_OUT 2420 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2421 * 1 PFLAG3_CALLED_SUPER 2422 * 1 PFLAG3_APPLYING_INSETS 2423 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2424 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2425 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2426 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2427 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2428 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2429 * 1 PFLAG3_SCROLL_INDICATOR_START 2430 * 1 PFLAG3_SCROLL_INDICATOR_END 2431 * 1 PFLAG3_ASSIST_BLOCKED 2432 * 1 PFLAG3_POINTER_ICON_NULL 2433 * 1 PFLAG3_POINTER_ICON_VALUE_START 2434 * 11111111 PFLAG3_POINTER_ICON_MASK 2435 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2436 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2437 * 1 PFLAG3_TEMPORARY_DETACH 2438 * |-------|-------|-------|-------| 2439 */ 2440 2441 /** 2442 * Flag indicating that view has a transform animation set on it. This is used to track whether 2443 * an animation is cleared between successive frames, in order to tell the associated 2444 * DisplayList to clear its animation matrix. 2445 */ 2446 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2447 2448 /** 2449 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2450 * animation is cleared between successive frames, in order to tell the associated 2451 * DisplayList to restore its alpha value. 2452 */ 2453 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2454 2455 /** 2456 * Flag indicating that the view has been through at least one layout since it 2457 * was last attached to a window. 2458 */ 2459 static final int PFLAG3_IS_LAID_OUT = 0x4; 2460 2461 /** 2462 * Flag indicating that a call to measure() was skipped and should be done 2463 * instead when layout() is invoked. 2464 */ 2465 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2466 2467 /** 2468 * Flag indicating that an overridden method correctly called down to 2469 * the superclass implementation as required by the API spec. 2470 */ 2471 static final int PFLAG3_CALLED_SUPER = 0x10; 2472 2473 /** 2474 * Flag indicating that we're in the process of applying window insets. 2475 */ 2476 static final int PFLAG3_APPLYING_INSETS = 0x20; 2477 2478 /** 2479 * Flag indicating that we're in the process of fitting system windows using the old method. 2480 */ 2481 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2482 2483 /** 2484 * Flag indicating that nested scrolling is enabled for this view. 2485 * The view will optionally cooperate with views up its parent chain to allow for 2486 * integrated nested scrolling along the same axis. 2487 */ 2488 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2489 2490 /** 2491 * Flag indicating that the bottom scroll indicator should be displayed 2492 * when this view can scroll up. 2493 */ 2494 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2495 2496 /** 2497 * Flag indicating that the bottom scroll indicator should be displayed 2498 * when this view can scroll down. 2499 */ 2500 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2501 2502 /** 2503 * Flag indicating that the left scroll indicator should be displayed 2504 * when this view can scroll left. 2505 */ 2506 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2507 2508 /** 2509 * Flag indicating that the right scroll indicator should be displayed 2510 * when this view can scroll right. 2511 */ 2512 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2513 2514 /** 2515 * Flag indicating that the start scroll indicator should be displayed 2516 * when this view can scroll in the start direction. 2517 */ 2518 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2519 2520 /** 2521 * Flag indicating that the end scroll indicator should be displayed 2522 * when this view can scroll in the end direction. 2523 */ 2524 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2525 2526 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2527 2528 static final int SCROLL_INDICATORS_NONE = 0x0000; 2529 2530 /** 2531 * Mask for use with setFlags indicating bits used for indicating which 2532 * scroll indicators are enabled. 2533 */ 2534 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2535 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2536 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2537 | PFLAG3_SCROLL_INDICATOR_END; 2538 2539 /** 2540 * Left-shift required to translate between public scroll indicator flags 2541 * and internal PFLAGS3 flags. When used as a right-shift, translates 2542 * PFLAGS3 flags to public flags. 2543 */ 2544 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2545 2546 /** @hide */ 2547 @Retention(RetentionPolicy.SOURCE) 2548 @IntDef(flag = true, 2549 value = { 2550 SCROLL_INDICATOR_TOP, 2551 SCROLL_INDICATOR_BOTTOM, 2552 SCROLL_INDICATOR_LEFT, 2553 SCROLL_INDICATOR_RIGHT, 2554 SCROLL_INDICATOR_START, 2555 SCROLL_INDICATOR_END, 2556 }) 2557 public @interface ScrollIndicators {} 2558 2559 /** 2560 * Scroll indicator direction for the top edge of the view. 2561 * 2562 * @see #setScrollIndicators(int) 2563 * @see #setScrollIndicators(int, int) 2564 * @see #getScrollIndicators() 2565 */ 2566 public static final int SCROLL_INDICATOR_TOP = 2567 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2568 2569 /** 2570 * Scroll indicator direction for the bottom edge of the view. 2571 * 2572 * @see #setScrollIndicators(int) 2573 * @see #setScrollIndicators(int, int) 2574 * @see #getScrollIndicators() 2575 */ 2576 public static final int SCROLL_INDICATOR_BOTTOM = 2577 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2578 2579 /** 2580 * Scroll indicator direction for the left edge of the view. 2581 * 2582 * @see #setScrollIndicators(int) 2583 * @see #setScrollIndicators(int, int) 2584 * @see #getScrollIndicators() 2585 */ 2586 public static final int SCROLL_INDICATOR_LEFT = 2587 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2588 2589 /** 2590 * Scroll indicator direction for the right edge of the view. 2591 * 2592 * @see #setScrollIndicators(int) 2593 * @see #setScrollIndicators(int, int) 2594 * @see #getScrollIndicators() 2595 */ 2596 public static final int SCROLL_INDICATOR_RIGHT = 2597 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2598 2599 /** 2600 * Scroll indicator direction for the starting edge of the view. 2601 * <p> 2602 * Resolved according to the view's layout direction, see 2603 * {@link #getLayoutDirection()} for more information. 2604 * 2605 * @see #setScrollIndicators(int) 2606 * @see #setScrollIndicators(int, int) 2607 * @see #getScrollIndicators() 2608 */ 2609 public static final int SCROLL_INDICATOR_START = 2610 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2611 2612 /** 2613 * Scroll indicator direction for the ending edge of the view. 2614 * <p> 2615 * Resolved according to the view's layout direction, see 2616 * {@link #getLayoutDirection()} for more information. 2617 * 2618 * @see #setScrollIndicators(int) 2619 * @see #setScrollIndicators(int, int) 2620 * @see #getScrollIndicators() 2621 */ 2622 public static final int SCROLL_INDICATOR_END = 2623 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2624 2625 /** 2626 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2627 * into this view.<p> 2628 */ 2629 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2630 2631 /** 2632 * The mask for use with private flags indicating bits used for pointer icon shapes. 2633 */ 2634 static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000; 2635 2636 /** 2637 * Left-shift used for pointer icon shape values in private flags. 2638 */ 2639 static final int PFLAG3_POINTER_ICON_LSHIFT = 15; 2640 2641 /** 2642 * Value indicating no specific pointer icons. 2643 */ 2644 private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT; 2645 2646 /** 2647 * Value indicating {@link PointerIcon.STYLE_NULL}. 2648 */ 2649 private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT; 2650 2651 /** 2652 * The base value for other pointer icon shapes. 2653 */ 2654 private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT; 2655 2656 /** 2657 * Whether this view has rendered elements that overlap (see {@link 2658 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 2659 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 2660 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 2661 * determined by whatever {@link #hasOverlappingRendering()} returns. 2662 */ 2663 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 2664 2665 /** 2666 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 2667 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 2668 */ 2669 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 2670 2671 /** 2672 * Flag indicating that the view is temporarily detached from the parent view. 2673 * 2674 * @see #onStartTemporaryDetach() 2675 * @see #onFinishTemporaryDetach() 2676 */ 2677 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 2678 2679 /* End of masks for mPrivateFlags3 */ 2680 2681 /** 2682 * Always allow a user to over-scroll this view, provided it is a 2683 * view that can scroll. 2684 * 2685 * @see #getOverScrollMode() 2686 * @see #setOverScrollMode(int) 2687 */ 2688 public static final int OVER_SCROLL_ALWAYS = 0; 2689 2690 /** 2691 * Allow a user to over-scroll this view only if the content is large 2692 * enough to meaningfully scroll, provided it is a view that can scroll. 2693 * 2694 * @see #getOverScrollMode() 2695 * @see #setOverScrollMode(int) 2696 */ 2697 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2698 2699 /** 2700 * Never allow a user to over-scroll this view. 2701 * 2702 * @see #getOverScrollMode() 2703 * @see #setOverScrollMode(int) 2704 */ 2705 public static final int OVER_SCROLL_NEVER = 2; 2706 2707 /** 2708 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2709 * requested the system UI (status bar) to be visible (the default). 2710 * 2711 * @see #setSystemUiVisibility(int) 2712 */ 2713 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2714 2715 /** 2716 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2717 * system UI to enter an unobtrusive "low profile" mode. 2718 * 2719 * <p>This is for use in games, book readers, video players, or any other 2720 * "immersive" application where the usual system chrome is deemed too distracting. 2721 * 2722 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2723 * 2724 * @see #setSystemUiVisibility(int) 2725 */ 2726 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2727 2728 /** 2729 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2730 * system navigation be temporarily hidden. 2731 * 2732 * <p>This is an even less obtrusive state than that called for by 2733 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2734 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2735 * those to disappear. This is useful (in conjunction with the 2736 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2737 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2738 * window flags) for displaying content using every last pixel on the display. 2739 * 2740 * <p>There is a limitation: because navigation controls are so important, the least user 2741 * interaction will cause them to reappear immediately. When this happens, both 2742 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2743 * so that both elements reappear at the same time. 2744 * 2745 * @see #setSystemUiVisibility(int) 2746 */ 2747 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2748 2749 /** 2750 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2751 * into the normal fullscreen mode so that its content can take over the screen 2752 * while still allowing the user to interact with the application. 2753 * 2754 * <p>This has the same visual effect as 2755 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2756 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2757 * meaning that non-critical screen decorations (such as the status bar) will be 2758 * hidden while the user is in the View's window, focusing the experience on 2759 * that content. Unlike the window flag, if you are using ActionBar in 2760 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2761 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2762 * hide the action bar. 2763 * 2764 * <p>This approach to going fullscreen is best used over the window flag when 2765 * it is a transient state -- that is, the application does this at certain 2766 * points in its user interaction where it wants to allow the user to focus 2767 * on content, but not as a continuous state. For situations where the application 2768 * would like to simply stay full screen the entire time (such as a game that 2769 * wants to take over the screen), the 2770 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2771 * is usually a better approach. The state set here will be removed by the system 2772 * in various situations (such as the user moving to another application) like 2773 * the other system UI states. 2774 * 2775 * <p>When using this flag, the application should provide some easy facility 2776 * for the user to go out of it. A common example would be in an e-book 2777 * reader, where tapping on the screen brings back whatever screen and UI 2778 * decorations that had been hidden while the user was immersed in reading 2779 * the book. 2780 * 2781 * @see #setSystemUiVisibility(int) 2782 */ 2783 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2784 2785 /** 2786 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2787 * flags, we would like a stable view of the content insets given to 2788 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2789 * will always represent the worst case that the application can expect 2790 * as a continuous state. In the stock Android UI this is the space for 2791 * the system bar, nav bar, and status bar, but not more transient elements 2792 * such as an input method. 2793 * 2794 * The stable layout your UI sees is based on the system UI modes you can 2795 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2796 * then you will get a stable layout for changes of the 2797 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2798 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2799 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2800 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2801 * with a stable layout. (Note that you should avoid using 2802 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2803 * 2804 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2805 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2806 * then a hidden status bar will be considered a "stable" state for purposes 2807 * here. This allows your UI to continually hide the status bar, while still 2808 * using the system UI flags to hide the action bar while still retaining 2809 * a stable layout. Note that changing the window fullscreen flag will never 2810 * provide a stable layout for a clean transition. 2811 * 2812 * <p>If you are using ActionBar in 2813 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2814 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2815 * insets it adds to those given to the application. 2816 */ 2817 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2818 2819 /** 2820 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2821 * to be laid out as if it has requested 2822 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2823 * allows it to avoid artifacts when switching in and out of that mode, at 2824 * the expense that some of its user interface may be covered by screen 2825 * decorations when they are shown. You can perform layout of your inner 2826 * UI elements to account for the navigation system UI through the 2827 * {@link #fitSystemWindows(Rect)} method. 2828 */ 2829 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2830 2831 /** 2832 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2833 * to be laid out as if it has requested 2834 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2835 * allows it to avoid artifacts when switching in and out of that mode, at 2836 * the expense that some of its user interface may be covered by screen 2837 * decorations when they are shown. You can perform layout of your inner 2838 * UI elements to account for non-fullscreen system UI through the 2839 * {@link #fitSystemWindows(Rect)} method. 2840 */ 2841 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2842 2843 /** 2844 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2845 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2846 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2847 * user interaction. 2848 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2849 * has an effect when used in combination with that flag.</p> 2850 */ 2851 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2852 2853 /** 2854 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2855 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2856 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2857 * experience while also hiding the system bars. If this flag is not set, 2858 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2859 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2860 * if the user swipes from the top of the screen. 2861 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2862 * system gestures, such as swiping from the top of the screen. These transient system bars 2863 * will overlay app’s content, may have some degree of transparency, and will automatically 2864 * hide after a short timeout. 2865 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2866 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2867 * with one or both of those flags.</p> 2868 */ 2869 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2870 2871 /** 2872 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2873 * is compatible with light status bar backgrounds. 2874 * 2875 * <p>For this to take effect, the window must request 2876 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2877 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2878 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2879 * FLAG_TRANSLUCENT_STATUS}. 2880 * 2881 * @see android.R.attr#windowLightStatusBar 2882 */ 2883 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2884 2885 /** 2886 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2887 */ 2888 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2889 2890 /** 2891 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2892 */ 2893 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2894 2895 /** 2896 * @hide 2897 * 2898 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2899 * out of the public fields to keep the undefined bits out of the developer's way. 2900 * 2901 * Flag to make the status bar not expandable. Unless you also 2902 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2903 */ 2904 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2905 2906 /** 2907 * @hide 2908 * 2909 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2910 * out of the public fields to keep the undefined bits out of the developer's way. 2911 * 2912 * Flag to hide notification icons and scrolling ticker text. 2913 */ 2914 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2915 2916 /** 2917 * @hide 2918 * 2919 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2920 * out of the public fields to keep the undefined bits out of the developer's way. 2921 * 2922 * Flag to disable incoming notification alerts. This will not block 2923 * icons, but it will block sound, vibrating and other visual or aural notifications. 2924 */ 2925 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2926 2927 /** 2928 * @hide 2929 * 2930 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2931 * out of the public fields to keep the undefined bits out of the developer's way. 2932 * 2933 * Flag to hide only the scrolling ticker. Note that 2934 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2935 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2936 */ 2937 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 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 hide the center system info area. 2946 */ 2947 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2948 2949 /** 2950 * @hide 2951 * 2952 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2953 * out of the public fields to keep the undefined bits out of the developer's way. 2954 * 2955 * Flag to hide only the home button. Don't use this 2956 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2957 */ 2958 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2959 2960 /** 2961 * @hide 2962 * 2963 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2964 * out of the public fields to keep the undefined bits out of the developer's way. 2965 * 2966 * Flag to hide only the back button. Don't use this 2967 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2968 */ 2969 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2970 2971 /** 2972 * @hide 2973 * 2974 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2975 * out of the public fields to keep the undefined bits out of the developer's way. 2976 * 2977 * Flag to hide only the clock. You might use this if your activity has 2978 * its own clock making the status bar's clock redundant. 2979 */ 2980 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2981 2982 /** 2983 * @hide 2984 * 2985 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2986 * out of the public fields to keep the undefined bits out of the developer's way. 2987 * 2988 * Flag to hide only the recent apps button. Don't use this 2989 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2990 */ 2991 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2992 2993 /** 2994 * @hide 2995 * 2996 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2997 * out of the public fields to keep the undefined bits out of the developer's way. 2998 * 2999 * Flag to disable the global search gesture. Don't use this 3000 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3001 */ 3002 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3003 3004 /** 3005 * @hide 3006 * 3007 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3008 * out of the public fields to keep the undefined bits out of the developer's way. 3009 * 3010 * Flag to specify that the status bar is displayed in transient mode. 3011 */ 3012 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3013 3014 /** 3015 * @hide 3016 * 3017 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3018 * out of the public fields to keep the undefined bits out of the developer's way. 3019 * 3020 * Flag to specify that the navigation bar is displayed in transient mode. 3021 */ 3022 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3023 3024 /** 3025 * @hide 3026 * 3027 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3028 * out of the public fields to keep the undefined bits out of the developer's way. 3029 * 3030 * Flag to specify that the hidden status bar would like to be shown. 3031 */ 3032 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3033 3034 /** 3035 * @hide 3036 * 3037 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3038 * out of the public fields to keep the undefined bits out of the developer's way. 3039 * 3040 * Flag to specify that the hidden navigation bar would like to be shown. 3041 */ 3042 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3043 3044 /** 3045 * @hide 3046 * 3047 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3048 * out of the public fields to keep the undefined bits out of the developer's way. 3049 * 3050 * Flag to specify that the status bar is displayed in translucent mode. 3051 */ 3052 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3053 3054 /** 3055 * @hide 3056 * 3057 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3058 * out of the public fields to keep the undefined bits out of the developer's way. 3059 * 3060 * Flag to specify that the navigation bar is displayed in translucent mode. 3061 */ 3062 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3063 3064 /** 3065 * @hide 3066 * 3067 * Whether Recents is visible or not. 3068 */ 3069 public static final int RECENT_APPS_VISIBLE = 0x00004000; 3070 3071 /** 3072 * @hide 3073 * 3074 * Whether the TV's picture-in-picture is visible or not. 3075 */ 3076 public static final int TV_PICTURE_IN_PICTURE_VISIBLE = 0x00010000; 3077 3078 /** 3079 * @hide 3080 * 3081 * Makes navigation bar transparent (but not the status bar). 3082 */ 3083 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3084 3085 /** 3086 * @hide 3087 * 3088 * Makes status bar transparent (but not the navigation bar). 3089 */ 3090 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3091 3092 /** 3093 * @hide 3094 * 3095 * Makes both status bar and navigation bar transparent. 3096 */ 3097 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3098 | STATUS_BAR_TRANSPARENT; 3099 3100 /** 3101 * @hide 3102 */ 3103 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3104 3105 /** 3106 * These are the system UI flags that can be cleared by events outside 3107 * of an application. Currently this is just the ability to tap on the 3108 * screen while hiding the navigation bar to have it return. 3109 * @hide 3110 */ 3111 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3112 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3113 | SYSTEM_UI_FLAG_FULLSCREEN; 3114 3115 /** 3116 * Flags that can impact the layout in relation to system UI. 3117 */ 3118 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3119 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3120 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3121 3122 /** @hide */ 3123 @IntDef(flag = true, 3124 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3125 @Retention(RetentionPolicy.SOURCE) 3126 public @interface FindViewFlags {} 3127 3128 /** 3129 * Find views that render the specified text. 3130 * 3131 * @see #findViewsWithText(ArrayList, CharSequence, int) 3132 */ 3133 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3134 3135 /** 3136 * Find find views that contain the specified content description. 3137 * 3138 * @see #findViewsWithText(ArrayList, CharSequence, int) 3139 */ 3140 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3141 3142 /** 3143 * Find views that contain {@link AccessibilityNodeProvider}. Such 3144 * a View is a root of virtual view hierarchy and may contain the searched 3145 * text. If this flag is set Views with providers are automatically 3146 * added and it is a responsibility of the client to call the APIs of 3147 * the provider to determine whether the virtual tree rooted at this View 3148 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3149 * representing the virtual views with this text. 3150 * 3151 * @see #findViewsWithText(ArrayList, CharSequence, int) 3152 * 3153 * @hide 3154 */ 3155 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3156 3157 /** 3158 * The undefined cursor position. 3159 * 3160 * @hide 3161 */ 3162 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3163 3164 /** 3165 * Indicates that the screen has changed state and is now off. 3166 * 3167 * @see #onScreenStateChanged(int) 3168 */ 3169 public static final int SCREEN_STATE_OFF = 0x0; 3170 3171 /** 3172 * Indicates that the screen has changed state and is now on. 3173 * 3174 * @see #onScreenStateChanged(int) 3175 */ 3176 public static final int SCREEN_STATE_ON = 0x1; 3177 3178 /** 3179 * Indicates no axis of view scrolling. 3180 */ 3181 public static final int SCROLL_AXIS_NONE = 0; 3182 3183 /** 3184 * Indicates scrolling along the horizontal axis. 3185 */ 3186 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3187 3188 /** 3189 * Indicates scrolling along the vertical axis. 3190 */ 3191 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3192 3193 /** 3194 * Controls the over-scroll mode for this view. 3195 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3196 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3197 * and {@link #OVER_SCROLL_NEVER}. 3198 */ 3199 private int mOverScrollMode; 3200 3201 /** 3202 * The parent this view is attached to. 3203 * {@hide} 3204 * 3205 * @see #getParent() 3206 */ 3207 protected ViewParent mParent; 3208 3209 /** 3210 * {@hide} 3211 */ 3212 AttachInfo mAttachInfo; 3213 3214 /** 3215 * {@hide} 3216 */ 3217 @ViewDebug.ExportedProperty(flagMapping = { 3218 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3219 name = "FORCE_LAYOUT"), 3220 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3221 name = "LAYOUT_REQUIRED"), 3222 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3223 name = "DRAWING_CACHE_INVALID", outputIf = false), 3224 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3225 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3226 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3227 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3228 }, formatToHexString = true) 3229 int mPrivateFlags; 3230 int mPrivateFlags2; 3231 int mPrivateFlags3; 3232 3233 /** 3234 * This view's request for the visibility of the status bar. 3235 * @hide 3236 */ 3237 @ViewDebug.ExportedProperty(flagMapping = { 3238 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3239 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3240 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3241 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3242 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3243 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3244 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3245 equals = SYSTEM_UI_FLAG_VISIBLE, 3246 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3247 }, formatToHexString = true) 3248 int mSystemUiVisibility; 3249 3250 /** 3251 * Reference count for transient state. 3252 * @see #setHasTransientState(boolean) 3253 */ 3254 int mTransientStateCount = 0; 3255 3256 /** 3257 * Count of how many windows this view has been attached to. 3258 */ 3259 int mWindowAttachCount; 3260 3261 /** 3262 * The layout parameters associated with this view and used by the parent 3263 * {@link android.view.ViewGroup} to determine how this view should be 3264 * laid out. 3265 * {@hide} 3266 */ 3267 protected ViewGroup.LayoutParams mLayoutParams; 3268 3269 /** 3270 * The view flags hold various views states. 3271 * {@hide} 3272 */ 3273 @ViewDebug.ExportedProperty(formatToHexString = true) 3274 int mViewFlags; 3275 3276 static class TransformationInfo { 3277 /** 3278 * The transform matrix for the View. This transform is calculated internally 3279 * based on the translation, rotation, and scale properties. 3280 * 3281 * Do *not* use this variable directly; instead call getMatrix(), which will 3282 * load the value from the View's RenderNode. 3283 */ 3284 private final Matrix mMatrix = new Matrix(); 3285 3286 /** 3287 * The inverse transform matrix for the View. This transform is calculated 3288 * internally based on the translation, rotation, and scale properties. 3289 * 3290 * Do *not* use this variable directly; instead call getInverseMatrix(), 3291 * which will load the value from the View's RenderNode. 3292 */ 3293 private Matrix mInverseMatrix; 3294 3295 /** 3296 * The opacity of the View. This is a value from 0 to 1, where 0 means 3297 * completely transparent and 1 means completely opaque. 3298 */ 3299 @ViewDebug.ExportedProperty 3300 float mAlpha = 1f; 3301 3302 /** 3303 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3304 * property only used by transitions, which is composited with the other alpha 3305 * values to calculate the final visual alpha value. 3306 */ 3307 float mTransitionAlpha = 1f; 3308 } 3309 3310 TransformationInfo mTransformationInfo; 3311 3312 /** 3313 * Current clip bounds. to which all drawing of this view are constrained. 3314 */ 3315 Rect mClipBounds = null; 3316 3317 private boolean mLastIsOpaque; 3318 3319 /** 3320 * The distance in pixels from the left edge of this view's parent 3321 * to the left edge of this view. 3322 * {@hide} 3323 */ 3324 @ViewDebug.ExportedProperty(category = "layout") 3325 protected int mLeft; 3326 /** 3327 * The distance in pixels from the left edge of this view's parent 3328 * to the right edge of this view. 3329 * {@hide} 3330 */ 3331 @ViewDebug.ExportedProperty(category = "layout") 3332 protected int mRight; 3333 /** 3334 * The distance in pixels from the top edge of this view's parent 3335 * to the top edge of this view. 3336 * {@hide} 3337 */ 3338 @ViewDebug.ExportedProperty(category = "layout") 3339 protected int mTop; 3340 /** 3341 * The distance in pixels from the top edge of this view's parent 3342 * to the bottom edge of this view. 3343 * {@hide} 3344 */ 3345 @ViewDebug.ExportedProperty(category = "layout") 3346 protected int mBottom; 3347 3348 /** 3349 * The offset, in pixels, by which the content of this view is scrolled 3350 * horizontally. 3351 * {@hide} 3352 */ 3353 @ViewDebug.ExportedProperty(category = "scrolling") 3354 protected int mScrollX; 3355 /** 3356 * The offset, in pixels, by which the content of this view is scrolled 3357 * vertically. 3358 * {@hide} 3359 */ 3360 @ViewDebug.ExportedProperty(category = "scrolling") 3361 protected int mScrollY; 3362 3363 /** 3364 * The left padding in pixels, that is the distance in pixels between the 3365 * left edge of this view and the left edge of its content. 3366 * {@hide} 3367 */ 3368 @ViewDebug.ExportedProperty(category = "padding") 3369 protected int mPaddingLeft = 0; 3370 /** 3371 * The right padding in pixels, that is the distance in pixels between the 3372 * right edge of this view and the right edge of its content. 3373 * {@hide} 3374 */ 3375 @ViewDebug.ExportedProperty(category = "padding") 3376 protected int mPaddingRight = 0; 3377 /** 3378 * The top padding in pixels, that is the distance in pixels between the 3379 * top edge of this view and the top edge of its content. 3380 * {@hide} 3381 */ 3382 @ViewDebug.ExportedProperty(category = "padding") 3383 protected int mPaddingTop; 3384 /** 3385 * The bottom padding in pixels, that is the distance in pixels between the 3386 * bottom edge of this view and the bottom edge of its content. 3387 * {@hide} 3388 */ 3389 @ViewDebug.ExportedProperty(category = "padding") 3390 protected int mPaddingBottom; 3391 3392 /** 3393 * The layout insets in pixels, that is the distance in pixels between the 3394 * visible edges of this view its bounds. 3395 */ 3396 private Insets mLayoutInsets; 3397 3398 /** 3399 * Briefly describes the view and is primarily used for accessibility support. 3400 */ 3401 private CharSequence mContentDescription; 3402 3403 /** 3404 * Specifies the id of a view for which this view serves as a label for 3405 * accessibility purposes. 3406 */ 3407 private int mLabelForId = View.NO_ID; 3408 3409 /** 3410 * Predicate for matching labeled view id with its label for 3411 * accessibility purposes. 3412 */ 3413 private MatchLabelForPredicate mMatchLabelForPredicate; 3414 3415 /** 3416 * Specifies a view before which this one is visited in accessibility traversal. 3417 */ 3418 private int mAccessibilityTraversalBeforeId = NO_ID; 3419 3420 /** 3421 * Specifies a view after which this one is visited in accessibility traversal. 3422 */ 3423 private int mAccessibilityTraversalAfterId = NO_ID; 3424 3425 /** 3426 * Predicate for matching a view by its id. 3427 */ 3428 private MatchIdPredicate mMatchIdPredicate; 3429 3430 /** 3431 * Cache the paddingRight set by the user to append to the scrollbar's size. 3432 * 3433 * @hide 3434 */ 3435 @ViewDebug.ExportedProperty(category = "padding") 3436 protected int mUserPaddingRight; 3437 3438 /** 3439 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3440 * 3441 * @hide 3442 */ 3443 @ViewDebug.ExportedProperty(category = "padding") 3444 protected int mUserPaddingBottom; 3445 3446 /** 3447 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3448 * 3449 * @hide 3450 */ 3451 @ViewDebug.ExportedProperty(category = "padding") 3452 protected int mUserPaddingLeft; 3453 3454 /** 3455 * Cache the paddingStart set by the user to append to the scrollbar's size. 3456 * 3457 */ 3458 @ViewDebug.ExportedProperty(category = "padding") 3459 int mUserPaddingStart; 3460 3461 /** 3462 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3463 * 3464 */ 3465 @ViewDebug.ExportedProperty(category = "padding") 3466 int mUserPaddingEnd; 3467 3468 /** 3469 * Cache initial left padding. 3470 * 3471 * @hide 3472 */ 3473 int mUserPaddingLeftInitial; 3474 3475 /** 3476 * Cache initial right padding. 3477 * 3478 * @hide 3479 */ 3480 int mUserPaddingRightInitial; 3481 3482 /** 3483 * Default undefined padding 3484 */ 3485 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3486 3487 /** 3488 * Cache if a left padding has been defined 3489 */ 3490 private boolean mLeftPaddingDefined = false; 3491 3492 /** 3493 * Cache if a right padding has been defined 3494 */ 3495 private boolean mRightPaddingDefined = false; 3496 3497 /** 3498 * @hide 3499 */ 3500 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3501 /** 3502 * @hide 3503 */ 3504 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3505 3506 private LongSparseLongArray mMeasureCache; 3507 3508 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3509 private Drawable mBackground; 3510 private TintInfo mBackgroundTint; 3511 3512 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3513 private ForegroundInfo mForegroundInfo; 3514 3515 private Drawable mScrollIndicatorDrawable; 3516 3517 /** 3518 * RenderNode used for backgrounds. 3519 * <p> 3520 * When non-null and valid, this is expected to contain an up-to-date copy 3521 * of the background drawable. It is cleared on temporary detach, and reset 3522 * on cleanup. 3523 */ 3524 private RenderNode mBackgroundRenderNode; 3525 3526 private int mBackgroundResource; 3527 private boolean mBackgroundSizeChanged; 3528 3529 private String mTransitionName; 3530 3531 static class TintInfo { 3532 ColorStateList mTintList; 3533 PorterDuff.Mode mTintMode; 3534 boolean mHasTintMode; 3535 boolean mHasTintList; 3536 } 3537 3538 private static class ForegroundInfo { 3539 private Drawable mDrawable; 3540 private TintInfo mTintInfo; 3541 private int mGravity = Gravity.FILL; 3542 private boolean mInsidePadding = true; 3543 private boolean mBoundsChanged = true; 3544 private final Rect mSelfBounds = new Rect(); 3545 private final Rect mOverlayBounds = new Rect(); 3546 } 3547 3548 static class ListenerInfo { 3549 /** 3550 * Listener used to dispatch focus change events. 3551 * This field should be made private, so it is hidden from the SDK. 3552 * {@hide} 3553 */ 3554 protected OnFocusChangeListener mOnFocusChangeListener; 3555 3556 /** 3557 * Listeners for layout change events. 3558 */ 3559 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3560 3561 protected OnScrollChangeListener mOnScrollChangeListener; 3562 3563 /** 3564 * Listeners for attach events. 3565 */ 3566 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3567 3568 /** 3569 * Listener used to dispatch click events. 3570 * This field should be made private, so it is hidden from the SDK. 3571 * {@hide} 3572 */ 3573 public OnClickListener mOnClickListener; 3574 3575 /** 3576 * Listener used to dispatch long click events. 3577 * This field should be made private, so it is hidden from the SDK. 3578 * {@hide} 3579 */ 3580 protected OnLongClickListener mOnLongClickListener; 3581 3582 /** 3583 * Listener used to dispatch context click events. This field should be made private, so it 3584 * is hidden from the SDK. 3585 * {@hide} 3586 */ 3587 protected OnContextClickListener mOnContextClickListener; 3588 3589 /** 3590 * Listener used to build the context menu. 3591 * This field should be made private, so it is hidden from the SDK. 3592 * {@hide} 3593 */ 3594 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3595 3596 private OnKeyListener mOnKeyListener; 3597 3598 private OnTouchListener mOnTouchListener; 3599 3600 private OnHoverListener mOnHoverListener; 3601 3602 private OnGenericMotionListener mOnGenericMotionListener; 3603 3604 private OnDragListener mOnDragListener; 3605 3606 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3607 3608 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3609 } 3610 3611 ListenerInfo mListenerInfo; 3612 3613 // Temporary values used to hold (x,y) coordinates when delegating from the 3614 // two-arg performLongClick() method to the legacy no-arg version. 3615 private float mLongClickX = Float.NaN; 3616 private float mLongClickY = Float.NaN; 3617 3618 /** 3619 * The application environment this view lives in. 3620 * This field should be made private, so it is hidden from the SDK. 3621 * {@hide} 3622 */ 3623 @ViewDebug.ExportedProperty(deepExport = true) 3624 protected Context mContext; 3625 3626 private final Resources mResources; 3627 3628 private ScrollabilityCache mScrollCache; 3629 3630 private int[] mDrawableState = null; 3631 3632 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3633 3634 /** 3635 * Animator that automatically runs based on state changes. 3636 */ 3637 private StateListAnimator mStateListAnimator; 3638 3639 /** 3640 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3641 * the user may specify which view to go to next. 3642 */ 3643 private int mNextFocusLeftId = View.NO_ID; 3644 3645 /** 3646 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3647 * the user may specify which view to go to next. 3648 */ 3649 private int mNextFocusRightId = View.NO_ID; 3650 3651 /** 3652 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3653 * the user may specify which view to go to next. 3654 */ 3655 private int mNextFocusUpId = View.NO_ID; 3656 3657 /** 3658 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3659 * the user may specify which view to go to next. 3660 */ 3661 private int mNextFocusDownId = View.NO_ID; 3662 3663 /** 3664 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3665 * the user may specify which view to go to next. 3666 */ 3667 int mNextFocusForwardId = View.NO_ID; 3668 3669 private CheckForLongPress mPendingCheckForLongPress; 3670 private CheckForTap mPendingCheckForTap = null; 3671 private PerformClick mPerformClick; 3672 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3673 3674 private UnsetPressedState mUnsetPressedState; 3675 3676 /** 3677 * Whether the long press's action has been invoked. The tap's action is invoked on the 3678 * up event while a long press is invoked as soon as the long press duration is reached, so 3679 * a long press could be performed before the tap is checked, in which case the tap's action 3680 * should not be invoked. 3681 */ 3682 private boolean mHasPerformedLongPress; 3683 3684 /** 3685 * Whether a context click button is currently pressed down. This is true when the stylus is 3686 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3687 * pressed. This is false once the button is released or if the stylus has been lifted. 3688 */ 3689 private boolean mInContextButtonPress; 3690 3691 /** 3692 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3693 * true after a stylus button press has occured, when the next up event should not be recognized 3694 * as a tap. 3695 */ 3696 private boolean mIgnoreNextUpEvent; 3697 3698 /** 3699 * The minimum height of the view. We'll try our best to have the height 3700 * of this view to at least this amount. 3701 */ 3702 @ViewDebug.ExportedProperty(category = "measurement") 3703 private int mMinHeight; 3704 3705 /** 3706 * The minimum width of the view. We'll try our best to have the width 3707 * of this view to at least this amount. 3708 */ 3709 @ViewDebug.ExportedProperty(category = "measurement") 3710 private int mMinWidth; 3711 3712 /** 3713 * The delegate to handle touch events that are physically in this view 3714 * but should be handled by another view. 3715 */ 3716 private TouchDelegate mTouchDelegate = null; 3717 3718 /** 3719 * Solid color to use as a background when creating the drawing cache. Enables 3720 * the cache to use 16 bit bitmaps instead of 32 bit. 3721 */ 3722 private int mDrawingCacheBackgroundColor = 0; 3723 3724 /** 3725 * Special tree observer used when mAttachInfo is null. 3726 */ 3727 private ViewTreeObserver mFloatingTreeObserver; 3728 3729 /** 3730 * Cache the touch slop from the context that created the view. 3731 */ 3732 private int mTouchSlop; 3733 3734 /** 3735 * Object that handles automatic animation of view properties. 3736 */ 3737 private ViewPropertyAnimator mAnimator = null; 3738 3739 /** 3740 * List of registered FrameMetricsObservers. 3741 */ 3742 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3743 3744 /** 3745 * Flag indicating that a drag can cross window boundaries. When 3746 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3747 * with this flag set, all visible applications will be able to participate 3748 * in the drag operation and receive the dragged content. 3749 * 3750 * If this is the only flag set, then the drag recipient will only have access to text data 3751 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3752 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags. 3753 */ 3754 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3755 3756 /** 3757 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3758 * request read access to the content URI(s) contained in the {@link ClipData} object. 3759 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3760 */ 3761 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3762 3763 /** 3764 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3765 * request write access to the content URI(s) contained in the {@link ClipData} object. 3766 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3767 */ 3768 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3769 3770 /** 3771 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3772 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3773 * reboots until explicitly revoked with 3774 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3775 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3776 */ 3777 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3778 Intent.FLAG_GRANT_PERSISTABLE_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 applies to any URI that is a prefix 3783 * match against the original granted URI. 3784 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3785 */ 3786 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3787 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3788 3789 /** 3790 * Flag indicating that the drag shadow will be opaque. When 3791 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3792 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3793 */ 3794 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3795 3796 /** 3797 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3798 */ 3799 private float mVerticalScrollFactor; 3800 3801 /** 3802 * Position of the vertical scroll bar. 3803 */ 3804 private int mVerticalScrollbarPosition; 3805 3806 /** 3807 * Position the scroll bar at the default position as determined by the system. 3808 */ 3809 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3810 3811 /** 3812 * Position the scroll bar along the left edge. 3813 */ 3814 public static final int SCROLLBAR_POSITION_LEFT = 1; 3815 3816 /** 3817 * Position the scroll bar along the right edge. 3818 */ 3819 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3820 3821 /** 3822 * Indicates that the view does not have a layer. 3823 * 3824 * @see #getLayerType() 3825 * @see #setLayerType(int, android.graphics.Paint) 3826 * @see #LAYER_TYPE_SOFTWARE 3827 * @see #LAYER_TYPE_HARDWARE 3828 */ 3829 public static final int LAYER_TYPE_NONE = 0; 3830 3831 /** 3832 * <p>Indicates that the view has a software layer. A software layer is backed 3833 * by a bitmap and causes the view to be rendered using Android's software 3834 * rendering pipeline, even if hardware acceleration is enabled.</p> 3835 * 3836 * <p>Software layers have various usages:</p> 3837 * <p>When the application is not using hardware acceleration, a software layer 3838 * is useful to apply a specific color filter and/or blending mode and/or 3839 * translucency to a view and all its children.</p> 3840 * <p>When the application is using hardware acceleration, a software layer 3841 * is useful to render drawing primitives not supported by the hardware 3842 * accelerated pipeline. It can also be used to cache a complex view tree 3843 * into a texture and reduce the complexity of drawing operations. For instance, 3844 * when animating a complex view tree with a translation, a software layer can 3845 * be used to render the view tree only once.</p> 3846 * <p>Software layers should be avoided when the affected view tree updates 3847 * often. Every update will require to re-render the software layer, which can 3848 * potentially be slow (particularly when hardware acceleration is turned on 3849 * since the layer will have to be uploaded into a hardware texture after every 3850 * update.)</p> 3851 * 3852 * @see #getLayerType() 3853 * @see #setLayerType(int, android.graphics.Paint) 3854 * @see #LAYER_TYPE_NONE 3855 * @see #LAYER_TYPE_HARDWARE 3856 */ 3857 public static final int LAYER_TYPE_SOFTWARE = 1; 3858 3859 /** 3860 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3861 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3862 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3863 * rendering pipeline, but only if hardware acceleration is turned on for the 3864 * view hierarchy. When hardware acceleration is turned off, hardware layers 3865 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3866 * 3867 * <p>A hardware layer is useful to apply a specific color filter and/or 3868 * blending mode and/or translucency to a view and all its children.</p> 3869 * <p>A hardware layer can be used to cache a complex view tree into a 3870 * texture and reduce the complexity of drawing operations. For instance, 3871 * when animating a complex view tree with a translation, a hardware layer can 3872 * be used to render the view tree only once.</p> 3873 * <p>A hardware layer can also be used to increase the rendering quality when 3874 * rotation transformations are applied on a view. It can also be used to 3875 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3876 * 3877 * @see #getLayerType() 3878 * @see #setLayerType(int, android.graphics.Paint) 3879 * @see #LAYER_TYPE_NONE 3880 * @see #LAYER_TYPE_SOFTWARE 3881 */ 3882 public static final int LAYER_TYPE_HARDWARE = 2; 3883 3884 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3885 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3886 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3887 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3888 }) 3889 int mLayerType = LAYER_TYPE_NONE; 3890 Paint mLayerPaint; 3891 3892 /** 3893 * Set to true when drawing cache is enabled and cannot be created. 3894 * 3895 * @hide 3896 */ 3897 public boolean mCachingFailed; 3898 private Bitmap mDrawingCache; 3899 private Bitmap mUnscaledDrawingCache; 3900 3901 /** 3902 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3903 * <p> 3904 * When non-null and valid, this is expected to contain an up-to-date copy 3905 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3906 * cleanup. 3907 */ 3908 final RenderNode mRenderNode; 3909 private Runnable mRenderNodeDetachedCallback; 3910 3911 /** 3912 * Set to true when the view is sending hover accessibility events because it 3913 * is the innermost hovered view. 3914 */ 3915 private boolean mSendingHoverAccessibilityEvents; 3916 3917 /** 3918 * Delegate for injecting accessibility functionality. 3919 */ 3920 AccessibilityDelegate mAccessibilityDelegate; 3921 3922 /** 3923 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3924 * and add/remove objects to/from the overlay directly through the Overlay methods. 3925 */ 3926 ViewOverlay mOverlay; 3927 3928 /** 3929 * The currently active parent view for receiving delegated nested scrolling events. 3930 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3931 * by {@link #stopNestedScroll()} at the same point where we clear 3932 * requestDisallowInterceptTouchEvent. 3933 */ 3934 private ViewParent mNestedScrollingParent; 3935 3936 /** 3937 * Consistency verifier for debugging purposes. 3938 * @hide 3939 */ 3940 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3941 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3942 new InputEventConsistencyVerifier(this, 0) : null; 3943 3944 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3945 3946 private int[] mTempNestedScrollConsumed; 3947 3948 /** 3949 * An overlay is going to draw this View instead of being drawn as part of this 3950 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3951 * when this view is invalidated. 3952 */ 3953 GhostView mGhostView; 3954 3955 /** 3956 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3957 * @hide 3958 */ 3959 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3960 public String[] mAttributes; 3961 3962 /** 3963 * Maps a Resource id to its name. 3964 */ 3965 private static SparseArray<String> mAttributeMap; 3966 3967 /** 3968 * Queue of pending runnables. Used to postpone calls to post() until this 3969 * view is attached and has a handler. 3970 */ 3971 private HandlerActionQueue mRunQueue; 3972 3973 /** 3974 * The pointer icon when the mouse hovers on this view. The default is null. 3975 */ 3976 private PointerIcon mPointerIcon; 3977 3978 /** 3979 * @hide 3980 */ 3981 String mStartActivityRequestWho; 3982 3983 /** 3984 * Simple constructor to use when creating a view from code. 3985 * 3986 * @param context The Context the view is running in, through which it can 3987 * access the current theme, resources, etc. 3988 */ 3989 public View(Context context) { 3990 mContext = context; 3991 mResources = context != null ? context.getResources() : null; 3992 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3993 // Set some flags defaults 3994 mPrivateFlags2 = 3995 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3996 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3997 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3998 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3999 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4000 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4001 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4002 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4003 mUserPaddingStart = UNDEFINED_PADDING; 4004 mUserPaddingEnd = UNDEFINED_PADDING; 4005 mRenderNode = RenderNode.create(getClass().getName(), this); 4006 4007 if (!sCompatibilityDone && context != null) { 4008 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4009 4010 // Older apps may need this compatibility hack for measurement. 4011 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4012 4013 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4014 // of whether a layout was requested on that View. 4015 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4016 4017 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4018 4019 // In M and newer, our widgets can pass a "hint" value in the size 4020 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4021 // know what the expected parent size is going to be, so e.g. list items can size 4022 // themselves at 1/3 the size of their container. It breaks older apps though, 4023 // specifically apps that use some popular open source libraries. 4024 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4025 4026 // Old versions of the platform would give different results from 4027 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4028 // modes, so we always need to run an additional EXACTLY pass. 4029 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4030 4031 // Prior to N, layout params could change without requiring a 4032 // subsequent call to setLayoutParams() and they would usually 4033 // work. Partial layout breaks this assumption. 4034 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4035 4036 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4037 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4038 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4039 4040 sCompatibilityDone = true; 4041 } 4042 } 4043 4044 /** 4045 * Constructor that is called when inflating a view from XML. This is called 4046 * when a view is being constructed from an XML file, supplying attributes 4047 * that were specified in the XML file. This version uses a default style of 4048 * 0, so the only attribute values applied are those in the Context's Theme 4049 * and the given AttributeSet. 4050 * 4051 * <p> 4052 * The method onFinishInflate() will be called after all children have been 4053 * added. 4054 * 4055 * @param context The Context the view is running in, through which it can 4056 * access the current theme, resources, etc. 4057 * @param attrs The attributes of the XML tag that is inflating the view. 4058 * @see #View(Context, AttributeSet, int) 4059 */ 4060 public View(Context context, @Nullable AttributeSet attrs) { 4061 this(context, attrs, 0); 4062 } 4063 4064 /** 4065 * Perform inflation from XML and apply a class-specific base style from a 4066 * theme attribute. This constructor of View allows subclasses to use their 4067 * own base style when they are inflating. For example, a Button class's 4068 * constructor would call this version of the super class constructor and 4069 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4070 * allows the theme's button style to modify all of the base view attributes 4071 * (in particular its background) as well as the Button class's attributes. 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 * @param defStyleAttr An attribute in the current theme that contains a 4077 * reference to a style resource that supplies default values for 4078 * the view. Can be 0 to not look for defaults. 4079 * @see #View(Context, AttributeSet) 4080 */ 4081 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4082 this(context, attrs, defStyleAttr, 0); 4083 } 4084 4085 /** 4086 * Perform inflation from XML and apply a class-specific base style from a 4087 * theme attribute or style resource. This constructor of View allows 4088 * subclasses to use their own base style when they are inflating. 4089 * <p> 4090 * When determining the final value of a particular attribute, there are 4091 * four inputs that come into play: 4092 * <ol> 4093 * <li>Any attribute values in the given AttributeSet. 4094 * <li>The style resource specified in the AttributeSet (named "style"). 4095 * <li>The default style specified by <var>defStyleAttr</var>. 4096 * <li>The default style specified by <var>defStyleRes</var>. 4097 * <li>The base values in this theme. 4098 * </ol> 4099 * <p> 4100 * Each of these inputs is considered in-order, with the first listed taking 4101 * precedence over the following ones. In other words, if in the 4102 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4103 * , then the button's text will <em>always</em> be black, regardless of 4104 * what is specified in any of the styles. 4105 * 4106 * @param context The Context the view is running in, through which it can 4107 * access the current theme, resources, etc. 4108 * @param attrs The attributes of the XML tag that is inflating the view. 4109 * @param defStyleAttr An attribute in the current theme that contains a 4110 * reference to a style resource that supplies default values for 4111 * the view. Can be 0 to not look for defaults. 4112 * @param defStyleRes A resource identifier of a style resource that 4113 * supplies default values for the view, used only if 4114 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4115 * to not look for defaults. 4116 * @see #View(Context, AttributeSet, int) 4117 */ 4118 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4119 this(context); 4120 4121 final TypedArray a = context.obtainStyledAttributes( 4122 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4123 4124 if (mDebugViewAttributes) { 4125 saveAttributeData(attrs, a); 4126 } 4127 4128 Drawable background = null; 4129 4130 int leftPadding = -1; 4131 int topPadding = -1; 4132 int rightPadding = -1; 4133 int bottomPadding = -1; 4134 int startPadding = UNDEFINED_PADDING; 4135 int endPadding = UNDEFINED_PADDING; 4136 4137 int padding = -1; 4138 4139 int viewFlagValues = 0; 4140 int viewFlagMasks = 0; 4141 4142 boolean setScrollContainer = false; 4143 4144 int x = 0; 4145 int y = 0; 4146 4147 float tx = 0; 4148 float ty = 0; 4149 float tz = 0; 4150 float elevation = 0; 4151 float rotation = 0; 4152 float rotationX = 0; 4153 float rotationY = 0; 4154 float sx = 1f; 4155 float sy = 1f; 4156 boolean transformSet = false; 4157 4158 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4159 int overScrollMode = mOverScrollMode; 4160 boolean initializeScrollbars = false; 4161 boolean initializeScrollIndicators = false; 4162 4163 boolean startPaddingDefined = false; 4164 boolean endPaddingDefined = false; 4165 boolean leftPaddingDefined = false; 4166 boolean rightPaddingDefined = false; 4167 4168 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4169 4170 final int N = a.getIndexCount(); 4171 for (int i = 0; i < N; i++) { 4172 int attr = a.getIndex(i); 4173 switch (attr) { 4174 case com.android.internal.R.styleable.View_background: 4175 background = a.getDrawable(attr); 4176 break; 4177 case com.android.internal.R.styleable.View_padding: 4178 padding = a.getDimensionPixelSize(attr, -1); 4179 mUserPaddingLeftInitial = padding; 4180 mUserPaddingRightInitial = padding; 4181 leftPaddingDefined = true; 4182 rightPaddingDefined = true; 4183 break; 4184 case com.android.internal.R.styleable.View_paddingLeft: 4185 leftPadding = a.getDimensionPixelSize(attr, -1); 4186 mUserPaddingLeftInitial = leftPadding; 4187 leftPaddingDefined = true; 4188 break; 4189 case com.android.internal.R.styleable.View_paddingTop: 4190 topPadding = a.getDimensionPixelSize(attr, -1); 4191 break; 4192 case com.android.internal.R.styleable.View_paddingRight: 4193 rightPadding = a.getDimensionPixelSize(attr, -1); 4194 mUserPaddingRightInitial = rightPadding; 4195 rightPaddingDefined = true; 4196 break; 4197 case com.android.internal.R.styleable.View_paddingBottom: 4198 bottomPadding = a.getDimensionPixelSize(attr, -1); 4199 break; 4200 case com.android.internal.R.styleable.View_paddingStart: 4201 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4202 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4203 break; 4204 case com.android.internal.R.styleable.View_paddingEnd: 4205 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4206 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4207 break; 4208 case com.android.internal.R.styleable.View_scrollX: 4209 x = a.getDimensionPixelOffset(attr, 0); 4210 break; 4211 case com.android.internal.R.styleable.View_scrollY: 4212 y = a.getDimensionPixelOffset(attr, 0); 4213 break; 4214 case com.android.internal.R.styleable.View_alpha: 4215 setAlpha(a.getFloat(attr, 1f)); 4216 break; 4217 case com.android.internal.R.styleable.View_transformPivotX: 4218 setPivotX(a.getDimensionPixelOffset(attr, 0)); 4219 break; 4220 case com.android.internal.R.styleable.View_transformPivotY: 4221 setPivotY(a.getDimensionPixelOffset(attr, 0)); 4222 break; 4223 case com.android.internal.R.styleable.View_translationX: 4224 tx = a.getDimensionPixelOffset(attr, 0); 4225 transformSet = true; 4226 break; 4227 case com.android.internal.R.styleable.View_translationY: 4228 ty = a.getDimensionPixelOffset(attr, 0); 4229 transformSet = true; 4230 break; 4231 case com.android.internal.R.styleable.View_translationZ: 4232 tz = a.getDimensionPixelOffset(attr, 0); 4233 transformSet = true; 4234 break; 4235 case com.android.internal.R.styleable.View_elevation: 4236 elevation = a.getDimensionPixelOffset(attr, 0); 4237 transformSet = true; 4238 break; 4239 case com.android.internal.R.styleable.View_rotation: 4240 rotation = a.getFloat(attr, 0); 4241 transformSet = true; 4242 break; 4243 case com.android.internal.R.styleable.View_rotationX: 4244 rotationX = a.getFloat(attr, 0); 4245 transformSet = true; 4246 break; 4247 case com.android.internal.R.styleable.View_rotationY: 4248 rotationY = a.getFloat(attr, 0); 4249 transformSet = true; 4250 break; 4251 case com.android.internal.R.styleable.View_scaleX: 4252 sx = a.getFloat(attr, 1f); 4253 transformSet = true; 4254 break; 4255 case com.android.internal.R.styleable.View_scaleY: 4256 sy = a.getFloat(attr, 1f); 4257 transformSet = true; 4258 break; 4259 case com.android.internal.R.styleable.View_id: 4260 mID = a.getResourceId(attr, NO_ID); 4261 break; 4262 case com.android.internal.R.styleable.View_tag: 4263 mTag = a.getText(attr); 4264 break; 4265 case com.android.internal.R.styleable.View_fitsSystemWindows: 4266 if (a.getBoolean(attr, false)) { 4267 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4268 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4269 } 4270 break; 4271 case com.android.internal.R.styleable.View_focusable: 4272 if (a.getBoolean(attr, false)) { 4273 viewFlagValues |= FOCUSABLE; 4274 viewFlagMasks |= FOCUSABLE_MASK; 4275 } 4276 break; 4277 case com.android.internal.R.styleable.View_focusableInTouchMode: 4278 if (a.getBoolean(attr, false)) { 4279 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4280 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4281 } 4282 break; 4283 case com.android.internal.R.styleable.View_clickable: 4284 if (a.getBoolean(attr, false)) { 4285 viewFlagValues |= CLICKABLE; 4286 viewFlagMasks |= CLICKABLE; 4287 } 4288 break; 4289 case com.android.internal.R.styleable.View_longClickable: 4290 if (a.getBoolean(attr, false)) { 4291 viewFlagValues |= LONG_CLICKABLE; 4292 viewFlagMasks |= LONG_CLICKABLE; 4293 } 4294 break; 4295 case com.android.internal.R.styleable.View_contextClickable: 4296 if (a.getBoolean(attr, false)) { 4297 viewFlagValues |= CONTEXT_CLICKABLE; 4298 viewFlagMasks |= CONTEXT_CLICKABLE; 4299 } 4300 break; 4301 case com.android.internal.R.styleable.View_saveEnabled: 4302 if (!a.getBoolean(attr, true)) { 4303 viewFlagValues |= SAVE_DISABLED; 4304 viewFlagMasks |= SAVE_DISABLED_MASK; 4305 } 4306 break; 4307 case com.android.internal.R.styleable.View_duplicateParentState: 4308 if (a.getBoolean(attr, false)) { 4309 viewFlagValues |= DUPLICATE_PARENT_STATE; 4310 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4311 } 4312 break; 4313 case com.android.internal.R.styleable.View_visibility: 4314 final int visibility = a.getInt(attr, 0); 4315 if (visibility != 0) { 4316 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4317 viewFlagMasks |= VISIBILITY_MASK; 4318 } 4319 break; 4320 case com.android.internal.R.styleable.View_layoutDirection: 4321 // Clear any layout direction flags (included resolved bits) already set 4322 mPrivateFlags2 &= 4323 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4324 // Set the layout direction flags depending on the value of the attribute 4325 final int layoutDirection = a.getInt(attr, -1); 4326 final int value = (layoutDirection != -1) ? 4327 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4328 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4329 break; 4330 case com.android.internal.R.styleable.View_drawingCacheQuality: 4331 final int cacheQuality = a.getInt(attr, 0); 4332 if (cacheQuality != 0) { 4333 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4334 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4335 } 4336 break; 4337 case com.android.internal.R.styleable.View_contentDescription: 4338 setContentDescription(a.getString(attr)); 4339 break; 4340 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4341 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4342 break; 4343 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4344 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4345 break; 4346 case com.android.internal.R.styleable.View_labelFor: 4347 setLabelFor(a.getResourceId(attr, NO_ID)); 4348 break; 4349 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4350 if (!a.getBoolean(attr, true)) { 4351 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4352 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4353 } 4354 break; 4355 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4356 if (!a.getBoolean(attr, true)) { 4357 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4358 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4359 } 4360 break; 4361 case R.styleable.View_scrollbars: 4362 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4363 if (scrollbars != SCROLLBARS_NONE) { 4364 viewFlagValues |= scrollbars; 4365 viewFlagMasks |= SCROLLBARS_MASK; 4366 initializeScrollbars = true; 4367 } 4368 break; 4369 //noinspection deprecation 4370 case R.styleable.View_fadingEdge: 4371 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4372 // Ignore the attribute starting with ICS 4373 break; 4374 } 4375 // With builds < ICS, fall through and apply fading edges 4376 case R.styleable.View_requiresFadingEdge: 4377 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4378 if (fadingEdge != FADING_EDGE_NONE) { 4379 viewFlagValues |= fadingEdge; 4380 viewFlagMasks |= FADING_EDGE_MASK; 4381 initializeFadingEdgeInternal(a); 4382 } 4383 break; 4384 case R.styleable.View_scrollbarStyle: 4385 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4386 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4387 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4388 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4389 } 4390 break; 4391 case R.styleable.View_isScrollContainer: 4392 setScrollContainer = true; 4393 if (a.getBoolean(attr, false)) { 4394 setScrollContainer(true); 4395 } 4396 break; 4397 case com.android.internal.R.styleable.View_keepScreenOn: 4398 if (a.getBoolean(attr, false)) { 4399 viewFlagValues |= KEEP_SCREEN_ON; 4400 viewFlagMasks |= KEEP_SCREEN_ON; 4401 } 4402 break; 4403 case R.styleable.View_filterTouchesWhenObscured: 4404 if (a.getBoolean(attr, false)) { 4405 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4406 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4407 } 4408 break; 4409 case R.styleable.View_nextFocusLeft: 4410 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4411 break; 4412 case R.styleable.View_nextFocusRight: 4413 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4414 break; 4415 case R.styleable.View_nextFocusUp: 4416 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4417 break; 4418 case R.styleable.View_nextFocusDown: 4419 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4420 break; 4421 case R.styleable.View_nextFocusForward: 4422 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4423 break; 4424 case R.styleable.View_minWidth: 4425 mMinWidth = a.getDimensionPixelSize(attr, 0); 4426 break; 4427 case R.styleable.View_minHeight: 4428 mMinHeight = a.getDimensionPixelSize(attr, 0); 4429 break; 4430 case R.styleable.View_onClick: 4431 if (context.isRestricted()) { 4432 throw new IllegalStateException("The android:onClick attribute cannot " 4433 + "be used within a restricted context"); 4434 } 4435 4436 final String handlerName = a.getString(attr); 4437 if (handlerName != null) { 4438 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4439 } 4440 break; 4441 case R.styleable.View_overScrollMode: 4442 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4443 break; 4444 case R.styleable.View_verticalScrollbarPosition: 4445 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4446 break; 4447 case R.styleable.View_layerType: 4448 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4449 break; 4450 case R.styleable.View_textDirection: 4451 // Clear any text direction flag already set 4452 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4453 // Set the text direction flags depending on the value of the attribute 4454 final int textDirection = a.getInt(attr, -1); 4455 if (textDirection != -1) { 4456 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4457 } 4458 break; 4459 case R.styleable.View_textAlignment: 4460 // Clear any text alignment flag already set 4461 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4462 // Set the text alignment flag depending on the value of the attribute 4463 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4464 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4465 break; 4466 case R.styleable.View_importantForAccessibility: 4467 setImportantForAccessibility(a.getInt(attr, 4468 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4469 break; 4470 case R.styleable.View_accessibilityLiveRegion: 4471 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4472 break; 4473 case R.styleable.View_transitionName: 4474 setTransitionName(a.getString(attr)); 4475 break; 4476 case R.styleable.View_nestedScrollingEnabled: 4477 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4478 break; 4479 case R.styleable.View_stateListAnimator: 4480 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4481 a.getResourceId(attr, 0))); 4482 break; 4483 case R.styleable.View_backgroundTint: 4484 // This will get applied later during setBackground(). 4485 if (mBackgroundTint == null) { 4486 mBackgroundTint = new TintInfo(); 4487 } 4488 mBackgroundTint.mTintList = a.getColorStateList( 4489 R.styleable.View_backgroundTint); 4490 mBackgroundTint.mHasTintList = true; 4491 break; 4492 case R.styleable.View_backgroundTintMode: 4493 // This will get applied later during setBackground(). 4494 if (mBackgroundTint == null) { 4495 mBackgroundTint = new TintInfo(); 4496 } 4497 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4498 R.styleable.View_backgroundTintMode, -1), null); 4499 mBackgroundTint.mHasTintMode = true; 4500 break; 4501 case R.styleable.View_outlineProvider: 4502 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4503 PROVIDER_BACKGROUND)); 4504 break; 4505 case R.styleable.View_foreground: 4506 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4507 setForeground(a.getDrawable(attr)); 4508 } 4509 break; 4510 case R.styleable.View_foregroundGravity: 4511 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4512 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4513 } 4514 break; 4515 case R.styleable.View_foregroundTintMode: 4516 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4517 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4518 } 4519 break; 4520 case R.styleable.View_foregroundTint: 4521 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4522 setForegroundTintList(a.getColorStateList(attr)); 4523 } 4524 break; 4525 case R.styleable.View_foregroundInsidePadding: 4526 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4527 if (mForegroundInfo == null) { 4528 mForegroundInfo = new ForegroundInfo(); 4529 } 4530 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4531 mForegroundInfo.mInsidePadding); 4532 } 4533 break; 4534 case R.styleable.View_scrollIndicators: 4535 final int scrollIndicators = 4536 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4537 & SCROLL_INDICATORS_PFLAG3_MASK; 4538 if (scrollIndicators != 0) { 4539 mPrivateFlags3 |= scrollIndicators; 4540 initializeScrollIndicators = true; 4541 } 4542 break; 4543 case R.styleable.View_pointerShape: 4544 final int resourceId = a.getResourceId(attr, 0); 4545 if (resourceId != 0) { 4546 setPointerIcon(PointerIcon.loadCustomIcon( 4547 context.getResources(), resourceId)); 4548 } else { 4549 final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED); 4550 if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) { 4551 setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape)); 4552 } 4553 } 4554 break; 4555 case R.styleable.View_forceHasOverlappingRendering: 4556 if (a.peekValue(attr) != null) { 4557 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4558 } 4559 break; 4560 4561 } 4562 } 4563 4564 setOverScrollMode(overScrollMode); 4565 4566 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4567 // the resolved layout direction). Those cached values will be used later during padding 4568 // resolution. 4569 mUserPaddingStart = startPadding; 4570 mUserPaddingEnd = endPadding; 4571 4572 if (background != null) { 4573 setBackground(background); 4574 } 4575 4576 // setBackground above will record that padding is currently provided by the background. 4577 // If we have padding specified via xml, record that here instead and use it. 4578 mLeftPaddingDefined = leftPaddingDefined; 4579 mRightPaddingDefined = rightPaddingDefined; 4580 4581 if (padding >= 0) { 4582 leftPadding = padding; 4583 topPadding = padding; 4584 rightPadding = padding; 4585 bottomPadding = padding; 4586 mUserPaddingLeftInitial = padding; 4587 mUserPaddingRightInitial = padding; 4588 } 4589 4590 if (isRtlCompatibilityMode()) { 4591 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4592 // left / right padding are used if defined (meaning here nothing to do). If they are not 4593 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4594 // start / end and resolve them as left / right (layout direction is not taken into account). 4595 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4596 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4597 // defined. 4598 if (!mLeftPaddingDefined && startPaddingDefined) { 4599 leftPadding = startPadding; 4600 } 4601 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4602 if (!mRightPaddingDefined && endPaddingDefined) { 4603 rightPadding = endPadding; 4604 } 4605 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4606 } else { 4607 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4608 // values defined. Otherwise, left /right values are used. 4609 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4610 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4611 // defined. 4612 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4613 4614 if (mLeftPaddingDefined && !hasRelativePadding) { 4615 mUserPaddingLeftInitial = leftPadding; 4616 } 4617 if (mRightPaddingDefined && !hasRelativePadding) { 4618 mUserPaddingRightInitial = rightPadding; 4619 } 4620 } 4621 4622 internalSetPadding( 4623 mUserPaddingLeftInitial, 4624 topPadding >= 0 ? topPadding : mPaddingTop, 4625 mUserPaddingRightInitial, 4626 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4627 4628 if (viewFlagMasks != 0) { 4629 setFlags(viewFlagValues, viewFlagMasks); 4630 } 4631 4632 if (initializeScrollbars) { 4633 initializeScrollbarsInternal(a); 4634 } 4635 4636 if (initializeScrollIndicators) { 4637 initializeScrollIndicatorsInternal(); 4638 } 4639 4640 a.recycle(); 4641 4642 // Needs to be called after mViewFlags is set 4643 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4644 recomputePadding(); 4645 } 4646 4647 if (x != 0 || y != 0) { 4648 scrollTo(x, y); 4649 } 4650 4651 if (transformSet) { 4652 setTranslationX(tx); 4653 setTranslationY(ty); 4654 setTranslationZ(tz); 4655 setElevation(elevation); 4656 setRotation(rotation); 4657 setRotationX(rotationX); 4658 setRotationY(rotationY); 4659 setScaleX(sx); 4660 setScaleY(sy); 4661 } 4662 4663 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4664 setScrollContainer(true); 4665 } 4666 4667 computeOpaqueFlags(); 4668 } 4669 4670 /** 4671 * An implementation of OnClickListener that attempts to lazily load a 4672 * named click handling method from a parent or ancestor context. 4673 */ 4674 private static class DeclaredOnClickListener implements OnClickListener { 4675 private final View mHostView; 4676 private final String mMethodName; 4677 4678 private Method mResolvedMethod; 4679 private Context mResolvedContext; 4680 4681 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4682 mHostView = hostView; 4683 mMethodName = methodName; 4684 } 4685 4686 @Override 4687 public void onClick(@NonNull View v) { 4688 if (mResolvedMethod == null) { 4689 resolveMethod(mHostView.getContext(), mMethodName); 4690 } 4691 4692 try { 4693 mResolvedMethod.invoke(mResolvedContext, v); 4694 } catch (IllegalAccessException e) { 4695 throw new IllegalStateException( 4696 "Could not execute non-public method for android:onClick", e); 4697 } catch (InvocationTargetException e) { 4698 throw new IllegalStateException( 4699 "Could not execute method for android:onClick", e); 4700 } 4701 } 4702 4703 @NonNull 4704 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4705 while (context != null) { 4706 try { 4707 if (!context.isRestricted()) { 4708 final Method method = context.getClass().getMethod(mMethodName, View.class); 4709 if (method != null) { 4710 mResolvedMethod = method; 4711 mResolvedContext = context; 4712 return; 4713 } 4714 } 4715 } catch (NoSuchMethodException e) { 4716 // Failed to find method, keep searching up the hierarchy. 4717 } 4718 4719 if (context instanceof ContextWrapper) { 4720 context = ((ContextWrapper) context).getBaseContext(); 4721 } else { 4722 // Can't search up the hierarchy, null out and fail. 4723 context = null; 4724 } 4725 } 4726 4727 final int id = mHostView.getId(); 4728 final String idText = id == NO_ID ? "" : " with id '" 4729 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4730 throw new IllegalStateException("Could not find method " + mMethodName 4731 + "(View) in a parent or ancestor Context for android:onClick " 4732 + "attribute defined on view " + mHostView.getClass() + idText); 4733 } 4734 } 4735 4736 /** 4737 * Non-public constructor for use in testing 4738 */ 4739 View() { 4740 mResources = null; 4741 mRenderNode = RenderNode.create(getClass().getName(), this); 4742 } 4743 4744 private static SparseArray<String> getAttributeMap() { 4745 if (mAttributeMap == null) { 4746 mAttributeMap = new SparseArray<>(); 4747 } 4748 return mAttributeMap; 4749 } 4750 4751 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4752 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4753 final int indexCount = t.getIndexCount(); 4754 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4755 4756 int i = 0; 4757 4758 // Store raw XML attributes. 4759 for (int j = 0; j < attrsCount; ++j) { 4760 attributes[i] = attrs.getAttributeName(j); 4761 attributes[i + 1] = attrs.getAttributeValue(j); 4762 i += 2; 4763 } 4764 4765 // Store resolved styleable attributes. 4766 final Resources res = t.getResources(); 4767 final SparseArray<String> attributeMap = getAttributeMap(); 4768 for (int j = 0; j < indexCount; ++j) { 4769 final int index = t.getIndex(j); 4770 if (!t.hasValueOrEmpty(index)) { 4771 // Value is undefined. Skip it. 4772 continue; 4773 } 4774 4775 final int resourceId = t.getResourceId(index, 0); 4776 if (resourceId == 0) { 4777 // Value is not a reference. Skip it. 4778 continue; 4779 } 4780 4781 String resourceName = attributeMap.get(resourceId); 4782 if (resourceName == null) { 4783 try { 4784 resourceName = res.getResourceName(resourceId); 4785 } catch (Resources.NotFoundException e) { 4786 resourceName = "0x" + Integer.toHexString(resourceId); 4787 } 4788 attributeMap.put(resourceId, resourceName); 4789 } 4790 4791 attributes[i] = resourceName; 4792 attributes[i + 1] = t.getString(index); 4793 i += 2; 4794 } 4795 4796 // Trim to fit contents. 4797 final String[] trimmed = new String[i]; 4798 System.arraycopy(attributes, 0, trimmed, 0, i); 4799 mAttributes = trimmed; 4800 } 4801 4802 public String toString() { 4803 StringBuilder out = new StringBuilder(128); 4804 out.append(getClass().getName()); 4805 out.append('{'); 4806 out.append(Integer.toHexString(System.identityHashCode(this))); 4807 out.append(' '); 4808 switch (mViewFlags&VISIBILITY_MASK) { 4809 case VISIBLE: out.append('V'); break; 4810 case INVISIBLE: out.append('I'); break; 4811 case GONE: out.append('G'); break; 4812 default: out.append('.'); break; 4813 } 4814 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4815 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4816 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4817 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4818 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4819 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4820 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4821 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4822 out.append(' '); 4823 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4824 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4825 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4826 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4827 out.append('p'); 4828 } else { 4829 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4830 } 4831 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4832 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4833 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4834 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4835 out.append(' '); 4836 out.append(mLeft); 4837 out.append(','); 4838 out.append(mTop); 4839 out.append('-'); 4840 out.append(mRight); 4841 out.append(','); 4842 out.append(mBottom); 4843 final int id = getId(); 4844 if (id != NO_ID) { 4845 out.append(" #"); 4846 out.append(Integer.toHexString(id)); 4847 final Resources r = mResources; 4848 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4849 try { 4850 String pkgname; 4851 switch (id&0xff000000) { 4852 case 0x7f000000: 4853 pkgname="app"; 4854 break; 4855 case 0x01000000: 4856 pkgname="android"; 4857 break; 4858 default: 4859 pkgname = r.getResourcePackageName(id); 4860 break; 4861 } 4862 String typename = r.getResourceTypeName(id); 4863 String entryname = r.getResourceEntryName(id); 4864 out.append(" "); 4865 out.append(pkgname); 4866 out.append(":"); 4867 out.append(typename); 4868 out.append("/"); 4869 out.append(entryname); 4870 } catch (Resources.NotFoundException e) { 4871 } 4872 } 4873 } 4874 out.append("}"); 4875 return out.toString(); 4876 } 4877 4878 /** 4879 * <p> 4880 * Initializes the fading edges from a given set of styled attributes. This 4881 * method should be called by subclasses that need fading edges and when an 4882 * instance of these subclasses is created programmatically rather than 4883 * being inflated from XML. This method is automatically called when the XML 4884 * is inflated. 4885 * </p> 4886 * 4887 * @param a the styled attributes set to initialize the fading edges from 4888 * 4889 * @removed 4890 */ 4891 protected void initializeFadingEdge(TypedArray a) { 4892 // This method probably shouldn't have been included in the SDK to begin with. 4893 // It relies on 'a' having been initialized using an attribute filter array that is 4894 // not publicly available to the SDK. The old method has been renamed 4895 // to initializeFadingEdgeInternal and hidden for framework use only; 4896 // this one initializes using defaults to make it safe to call for apps. 4897 4898 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4899 4900 initializeFadingEdgeInternal(arr); 4901 4902 arr.recycle(); 4903 } 4904 4905 /** 4906 * <p> 4907 * Initializes the fading edges from a given set of styled attributes. This 4908 * method should be called by subclasses that need fading edges and when an 4909 * instance of these subclasses is created programmatically rather than 4910 * being inflated from XML. This method is automatically called when the XML 4911 * is inflated. 4912 * </p> 4913 * 4914 * @param a the styled attributes set to initialize the fading edges from 4915 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4916 */ 4917 protected void initializeFadingEdgeInternal(TypedArray a) { 4918 initScrollCache(); 4919 4920 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4921 R.styleable.View_fadingEdgeLength, 4922 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4923 } 4924 4925 /** 4926 * Returns the size of the vertical faded edges used to indicate that more 4927 * content in this view is visible. 4928 * 4929 * @return The size in pixels of the vertical faded edge or 0 if vertical 4930 * faded edges are not enabled for this view. 4931 * @attr ref android.R.styleable#View_fadingEdgeLength 4932 */ 4933 public int getVerticalFadingEdgeLength() { 4934 if (isVerticalFadingEdgeEnabled()) { 4935 ScrollabilityCache cache = mScrollCache; 4936 if (cache != null) { 4937 return cache.fadingEdgeLength; 4938 } 4939 } 4940 return 0; 4941 } 4942 4943 /** 4944 * Set the size of the faded edge used to indicate that more content in this 4945 * view is available. Will not change whether the fading edge is enabled; use 4946 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4947 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4948 * for the vertical or horizontal fading edges. 4949 * 4950 * @param length The size in pixels of the faded edge used to indicate that more 4951 * content in this view is visible. 4952 */ 4953 public void setFadingEdgeLength(int length) { 4954 initScrollCache(); 4955 mScrollCache.fadingEdgeLength = length; 4956 } 4957 4958 /** 4959 * Returns the size of the horizontal faded edges used to indicate that more 4960 * content in this view is visible. 4961 * 4962 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4963 * faded edges are not enabled for this view. 4964 * @attr ref android.R.styleable#View_fadingEdgeLength 4965 */ 4966 public int getHorizontalFadingEdgeLength() { 4967 if (isHorizontalFadingEdgeEnabled()) { 4968 ScrollabilityCache cache = mScrollCache; 4969 if (cache != null) { 4970 return cache.fadingEdgeLength; 4971 } 4972 } 4973 return 0; 4974 } 4975 4976 /** 4977 * Returns the width of the vertical scrollbar. 4978 * 4979 * @return The width in pixels of the vertical scrollbar or 0 if there 4980 * is no vertical scrollbar. 4981 */ 4982 public int getVerticalScrollbarWidth() { 4983 ScrollabilityCache cache = mScrollCache; 4984 if (cache != null) { 4985 ScrollBarDrawable scrollBar = cache.scrollBar; 4986 if (scrollBar != null) { 4987 int size = scrollBar.getSize(true); 4988 if (size <= 0) { 4989 size = cache.scrollBarSize; 4990 } 4991 return size; 4992 } 4993 return 0; 4994 } 4995 return 0; 4996 } 4997 4998 /** 4999 * Returns the height of the horizontal scrollbar. 5000 * 5001 * @return The height in pixels of the horizontal scrollbar or 0 if 5002 * there is no horizontal scrollbar. 5003 */ 5004 protected int getHorizontalScrollbarHeight() { 5005 ScrollabilityCache cache = mScrollCache; 5006 if (cache != null) { 5007 ScrollBarDrawable scrollBar = cache.scrollBar; 5008 if (scrollBar != null) { 5009 int size = scrollBar.getSize(false); 5010 if (size <= 0) { 5011 size = cache.scrollBarSize; 5012 } 5013 return size; 5014 } 5015 return 0; 5016 } 5017 return 0; 5018 } 5019 5020 /** 5021 * <p> 5022 * Initializes the scrollbars from a given set of styled attributes. This 5023 * method should be called by subclasses that need scrollbars and when an 5024 * instance of these subclasses is created programmatically rather than 5025 * being inflated from XML. This method is automatically called when the XML 5026 * is inflated. 5027 * </p> 5028 * 5029 * @param a the styled attributes set to initialize the scrollbars from 5030 * 5031 * @removed 5032 */ 5033 protected void initializeScrollbars(TypedArray a) { 5034 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5035 // using the View filter array which is not available to the SDK. As such, internal 5036 // framework usage now uses initializeScrollbarsInternal and we grab a default 5037 // TypedArray with the right filter instead here. 5038 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5039 5040 initializeScrollbarsInternal(arr); 5041 5042 // We ignored the method parameter. Recycle the one we actually did use. 5043 arr.recycle(); 5044 } 5045 5046 /** 5047 * <p> 5048 * Initializes the scrollbars from a given set of styled attributes. This 5049 * method should be called by subclasses that need scrollbars and when an 5050 * instance of these subclasses is created programmatically rather than 5051 * being inflated from XML. This method is automatically called when the XML 5052 * is inflated. 5053 * </p> 5054 * 5055 * @param a the styled attributes set to initialize the scrollbars from 5056 * @hide 5057 */ 5058 protected void initializeScrollbarsInternal(TypedArray a) { 5059 initScrollCache(); 5060 5061 final ScrollabilityCache scrollabilityCache = mScrollCache; 5062 5063 if (scrollabilityCache.scrollBar == null) { 5064 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5065 scrollabilityCache.scrollBar.setState(getDrawableState()); 5066 scrollabilityCache.scrollBar.setCallback(this); 5067 } 5068 5069 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5070 5071 if (!fadeScrollbars) { 5072 scrollabilityCache.state = ScrollabilityCache.ON; 5073 } 5074 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5075 5076 5077 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5078 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5079 .getScrollBarFadeDuration()); 5080 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5081 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5082 ViewConfiguration.getScrollDefaultDelay()); 5083 5084 5085 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5086 com.android.internal.R.styleable.View_scrollbarSize, 5087 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5088 5089 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5090 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5091 5092 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5093 if (thumb != null) { 5094 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5095 } 5096 5097 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5098 false); 5099 if (alwaysDraw) { 5100 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5101 } 5102 5103 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5104 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5105 5106 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5107 if (thumb != null) { 5108 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5109 } 5110 5111 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5112 false); 5113 if (alwaysDraw) { 5114 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5115 } 5116 5117 // Apply layout direction to the new Drawables if needed 5118 final int layoutDirection = getLayoutDirection(); 5119 if (track != null) { 5120 track.setLayoutDirection(layoutDirection); 5121 } 5122 if (thumb != null) { 5123 thumb.setLayoutDirection(layoutDirection); 5124 } 5125 5126 // Re-apply user/background padding so that scrollbar(s) get added 5127 resolvePadding(); 5128 } 5129 5130 private void initializeScrollIndicatorsInternal() { 5131 // Some day maybe we'll break this into top/left/start/etc. and let the 5132 // client control it. Until then, you can have any scroll indicator you 5133 // want as long as it's a 1dp foreground-colored rectangle. 5134 if (mScrollIndicatorDrawable == null) { 5135 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5136 } 5137 } 5138 5139 /** 5140 * <p> 5141 * Initalizes the scrollability cache if necessary. 5142 * </p> 5143 */ 5144 private void initScrollCache() { 5145 if (mScrollCache == null) { 5146 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5147 } 5148 } 5149 5150 private ScrollabilityCache getScrollCache() { 5151 initScrollCache(); 5152 return mScrollCache; 5153 } 5154 5155 /** 5156 * Set the position of the vertical scroll bar. Should be one of 5157 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5158 * {@link #SCROLLBAR_POSITION_RIGHT}. 5159 * 5160 * @param position Where the vertical scroll bar should be positioned. 5161 */ 5162 public void setVerticalScrollbarPosition(int position) { 5163 if (mVerticalScrollbarPosition != position) { 5164 mVerticalScrollbarPosition = position; 5165 computeOpaqueFlags(); 5166 resolvePadding(); 5167 } 5168 } 5169 5170 /** 5171 * @return The position where the vertical scroll bar will show, if applicable. 5172 * @see #setVerticalScrollbarPosition(int) 5173 */ 5174 public int getVerticalScrollbarPosition() { 5175 return mVerticalScrollbarPosition; 5176 } 5177 5178 boolean isOnScrollbar(float x, float y) { 5179 if (mScrollCache == null) { 5180 return false; 5181 } 5182 x += getScrollX(); 5183 y += getScrollY(); 5184 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5185 final Rect bounds = mScrollCache.mScrollBarBounds; 5186 getVerticalScrollBarBounds(bounds); 5187 if (bounds.contains((int)x, (int)y)) { 5188 return true; 5189 } 5190 } 5191 if (isHorizontalScrollBarEnabled()) { 5192 final Rect bounds = mScrollCache.mScrollBarBounds; 5193 getHorizontalScrollBarBounds(bounds); 5194 if (bounds.contains((int)x, (int)y)) { 5195 return true; 5196 } 5197 } 5198 return false; 5199 } 5200 5201 boolean isOnScrollbarThumb(float x, float y) { 5202 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5203 } 5204 5205 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5206 if (mScrollCache == null) { 5207 return false; 5208 } 5209 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5210 x += getScrollX(); 5211 y += getScrollY(); 5212 final Rect bounds = mScrollCache.mScrollBarBounds; 5213 getVerticalScrollBarBounds(bounds); 5214 final int range = computeVerticalScrollRange(); 5215 final int offset = computeVerticalScrollOffset(); 5216 final int extent = computeVerticalScrollExtent(); 5217 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5218 extent, range); 5219 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5220 extent, range, offset); 5221 final int thumbTop = bounds.top + thumbOffset; 5222 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5223 && y <= thumbTop + thumbLength) { 5224 return true; 5225 } 5226 } 5227 return false; 5228 } 5229 5230 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5231 if (mScrollCache == null) { 5232 return false; 5233 } 5234 if (isHorizontalScrollBarEnabled()) { 5235 x += getScrollX(); 5236 y += getScrollY(); 5237 final Rect bounds = mScrollCache.mScrollBarBounds; 5238 getHorizontalScrollBarBounds(bounds); 5239 final int range = computeHorizontalScrollRange(); 5240 final int offset = computeHorizontalScrollOffset(); 5241 final int extent = computeHorizontalScrollExtent(); 5242 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5243 extent, range); 5244 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5245 extent, range, offset); 5246 final int thumbLeft = bounds.left + thumbOffset; 5247 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5248 && y <= bounds.bottom) { 5249 return true; 5250 } 5251 } 5252 return false; 5253 } 5254 5255 boolean isDraggingScrollBar() { 5256 return mScrollCache != null 5257 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5258 } 5259 5260 /** 5261 * Sets the state of all scroll indicators. 5262 * <p> 5263 * See {@link #setScrollIndicators(int, int)} for usage information. 5264 * 5265 * @param indicators a bitmask of indicators that should be enabled, or 5266 * {@code 0} to disable all indicators 5267 * @see #setScrollIndicators(int, int) 5268 * @see #getScrollIndicators() 5269 * @attr ref android.R.styleable#View_scrollIndicators 5270 */ 5271 public void setScrollIndicators(@ScrollIndicators int indicators) { 5272 setScrollIndicators(indicators, 5273 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5274 } 5275 5276 /** 5277 * Sets the state of the scroll indicators specified by the mask. To change 5278 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5279 * <p> 5280 * When a scroll indicator is enabled, it will be displayed if the view 5281 * can scroll in the direction of the indicator. 5282 * <p> 5283 * Multiple indicator types may be enabled or disabled by passing the 5284 * logical OR of the desired types. If multiple types are specified, they 5285 * will all be set to the same enabled state. 5286 * <p> 5287 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5288 * 5289 * @param indicators the indicator direction, or the logical OR of multiple 5290 * indicator directions. One or more of: 5291 * <ul> 5292 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5293 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5294 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5295 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5296 * <li>{@link #SCROLL_INDICATOR_START}</li> 5297 * <li>{@link #SCROLL_INDICATOR_END}</li> 5298 * </ul> 5299 * @see #setScrollIndicators(int) 5300 * @see #getScrollIndicators() 5301 * @attr ref android.R.styleable#View_scrollIndicators 5302 */ 5303 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5304 // Shift and sanitize mask. 5305 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5306 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5307 5308 // Shift and mask indicators. 5309 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5310 indicators &= mask; 5311 5312 // Merge with non-masked flags. 5313 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5314 5315 if (mPrivateFlags3 != updatedFlags) { 5316 mPrivateFlags3 = updatedFlags; 5317 5318 if (indicators != 0) { 5319 initializeScrollIndicatorsInternal(); 5320 } 5321 invalidate(); 5322 } 5323 } 5324 5325 /** 5326 * Returns a bitmask representing the enabled scroll indicators. 5327 * <p> 5328 * For example, if the top and left scroll indicators are enabled and all 5329 * other indicators are disabled, the return value will be 5330 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5331 * <p> 5332 * To check whether the bottom scroll indicator is enabled, use the value 5333 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5334 * 5335 * @return a bitmask representing the enabled scroll indicators 5336 */ 5337 @ScrollIndicators 5338 public int getScrollIndicators() { 5339 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5340 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5341 } 5342 5343 ListenerInfo getListenerInfo() { 5344 if (mListenerInfo != null) { 5345 return mListenerInfo; 5346 } 5347 mListenerInfo = new ListenerInfo(); 5348 return mListenerInfo; 5349 } 5350 5351 /** 5352 * Register a callback to be invoked when the scroll X or Y positions of 5353 * this view change. 5354 * <p> 5355 * <b>Note:</b> Some views handle scrolling independently from View and may 5356 * have their own separate listeners for scroll-type events. For example, 5357 * {@link android.widget.ListView ListView} allows clients to register an 5358 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5359 * to listen for changes in list scroll position. 5360 * 5361 * @param l The listener to notify when the scroll X or Y position changes. 5362 * @see android.view.View#getScrollX() 5363 * @see android.view.View#getScrollY() 5364 */ 5365 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5366 getListenerInfo().mOnScrollChangeListener = l; 5367 } 5368 5369 /** 5370 * Register a callback to be invoked when focus of this view changed. 5371 * 5372 * @param l The callback that will run. 5373 */ 5374 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5375 getListenerInfo().mOnFocusChangeListener = l; 5376 } 5377 5378 /** 5379 * Add a listener that will be called when the bounds of the view change due to 5380 * layout processing. 5381 * 5382 * @param listener The listener that will be called when layout bounds change. 5383 */ 5384 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5385 ListenerInfo li = getListenerInfo(); 5386 if (li.mOnLayoutChangeListeners == null) { 5387 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5388 } 5389 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5390 li.mOnLayoutChangeListeners.add(listener); 5391 } 5392 } 5393 5394 /** 5395 * Remove a listener for layout changes. 5396 * 5397 * @param listener The listener for layout bounds change. 5398 */ 5399 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5400 ListenerInfo li = mListenerInfo; 5401 if (li == null || li.mOnLayoutChangeListeners == null) { 5402 return; 5403 } 5404 li.mOnLayoutChangeListeners.remove(listener); 5405 } 5406 5407 /** 5408 * Add a listener for attach state changes. 5409 * 5410 * This listener will be called whenever this view is attached or detached 5411 * from a window. Remove the listener using 5412 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5413 * 5414 * @param listener Listener to attach 5415 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5416 */ 5417 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5418 ListenerInfo li = getListenerInfo(); 5419 if (li.mOnAttachStateChangeListeners == null) { 5420 li.mOnAttachStateChangeListeners 5421 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5422 } 5423 li.mOnAttachStateChangeListeners.add(listener); 5424 } 5425 5426 /** 5427 * Remove a listener for attach state changes. The listener will receive no further 5428 * notification of window attach/detach events. 5429 * 5430 * @param listener Listener to remove 5431 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5432 */ 5433 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5434 ListenerInfo li = mListenerInfo; 5435 if (li == null || li.mOnAttachStateChangeListeners == null) { 5436 return; 5437 } 5438 li.mOnAttachStateChangeListeners.remove(listener); 5439 } 5440 5441 /** 5442 * Returns the focus-change callback registered for this view. 5443 * 5444 * @return The callback, or null if one is not registered. 5445 */ 5446 public OnFocusChangeListener getOnFocusChangeListener() { 5447 ListenerInfo li = mListenerInfo; 5448 return li != null ? li.mOnFocusChangeListener : null; 5449 } 5450 5451 /** 5452 * Register a callback to be invoked when this view is clicked. If this view is not 5453 * clickable, it becomes clickable. 5454 * 5455 * @param l The callback that will run 5456 * 5457 * @see #setClickable(boolean) 5458 */ 5459 public void setOnClickListener(@Nullable OnClickListener l) { 5460 if (!isClickable()) { 5461 setClickable(true); 5462 } 5463 getListenerInfo().mOnClickListener = l; 5464 } 5465 5466 /** 5467 * Return whether this view has an attached OnClickListener. Returns 5468 * true if there is a listener, false if there is none. 5469 */ 5470 public boolean hasOnClickListeners() { 5471 ListenerInfo li = mListenerInfo; 5472 return (li != null && li.mOnClickListener != null); 5473 } 5474 5475 /** 5476 * Register a callback to be invoked when this view is clicked and held. If this view is not 5477 * long clickable, it becomes long clickable. 5478 * 5479 * @param l The callback that will run 5480 * 5481 * @see #setLongClickable(boolean) 5482 */ 5483 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5484 if (!isLongClickable()) { 5485 setLongClickable(true); 5486 } 5487 getListenerInfo().mOnLongClickListener = l; 5488 } 5489 5490 /** 5491 * Register a callback to be invoked when this view is context clicked. If the view is not 5492 * context clickable, it becomes context clickable. 5493 * 5494 * @param l The callback that will run 5495 * @see #setContextClickable(boolean) 5496 */ 5497 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5498 if (!isContextClickable()) { 5499 setContextClickable(true); 5500 } 5501 getListenerInfo().mOnContextClickListener = l; 5502 } 5503 5504 /** 5505 * Register a callback to be invoked when the context menu for this view is 5506 * being built. If this view is not long clickable, it becomes long clickable. 5507 * 5508 * @param l The callback that will run 5509 * 5510 */ 5511 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5512 if (!isLongClickable()) { 5513 setLongClickable(true); 5514 } 5515 getListenerInfo().mOnCreateContextMenuListener = l; 5516 } 5517 5518 /** 5519 * Set an observer to collect stats for each frame rendered for this view. 5520 * 5521 * @hide 5522 */ 5523 public void addFrameMetricsListener(Window window, 5524 Window.OnFrameMetricsAvailableListener listener, 5525 Handler handler) { 5526 if (mAttachInfo != null) { 5527 if (mAttachInfo.mHardwareRenderer != null) { 5528 if (mFrameMetricsObservers == null) { 5529 mFrameMetricsObservers = new ArrayList<>(); 5530 } 5531 5532 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5533 handler.getLooper(), listener); 5534 mFrameMetricsObservers.add(fmo); 5535 mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo); 5536 } else { 5537 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5538 } 5539 } else { 5540 if (mFrameMetricsObservers == null) { 5541 mFrameMetricsObservers = new ArrayList<>(); 5542 } 5543 5544 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5545 handler.getLooper(), listener); 5546 mFrameMetricsObservers.add(fmo); 5547 } 5548 } 5549 5550 /** 5551 * Remove observer configured to collect frame stats for this view. 5552 * 5553 * @hide 5554 */ 5555 public void removeFrameMetricsListener( 5556 Window.OnFrameMetricsAvailableListener listener) { 5557 ThreadedRenderer renderer = getHardwareRenderer(); 5558 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5559 if (fmo == null) { 5560 throw new IllegalArgumentException( 5561 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 5562 } 5563 5564 if (mFrameMetricsObservers != null) { 5565 mFrameMetricsObservers.remove(fmo); 5566 if (renderer != null) { 5567 renderer.removeFrameMetricsObserver(fmo); 5568 } 5569 } 5570 } 5571 5572 private void registerPendingFrameMetricsObservers() { 5573 if (mFrameMetricsObservers != null) { 5574 ThreadedRenderer renderer = getHardwareRenderer(); 5575 if (renderer != null) { 5576 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5577 renderer.addFrameMetricsObserver(fmo); 5578 } 5579 } else { 5580 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5581 } 5582 } 5583 } 5584 5585 private FrameMetricsObserver findFrameMetricsObserver( 5586 Window.OnFrameMetricsAvailableListener listener) { 5587 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5588 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5589 if (observer.mListener == listener) { 5590 return observer; 5591 } 5592 } 5593 5594 return null; 5595 } 5596 5597 /** 5598 * Call this view's OnClickListener, if it is defined. Performs all normal 5599 * actions associated with clicking: reporting accessibility event, playing 5600 * a sound, etc. 5601 * 5602 * @return True there was an assigned OnClickListener that was called, false 5603 * otherwise is returned. 5604 */ 5605 public boolean performClick() { 5606 final boolean result; 5607 final ListenerInfo li = mListenerInfo; 5608 if (li != null && li.mOnClickListener != null) { 5609 playSoundEffect(SoundEffectConstants.CLICK); 5610 li.mOnClickListener.onClick(this); 5611 result = true; 5612 } else { 5613 result = false; 5614 } 5615 5616 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5617 return result; 5618 } 5619 5620 /** 5621 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5622 * this only calls the listener, and does not do any associated clicking 5623 * actions like reporting an accessibility event. 5624 * 5625 * @return True there was an assigned OnClickListener that was called, false 5626 * otherwise is returned. 5627 */ 5628 public boolean callOnClick() { 5629 ListenerInfo li = mListenerInfo; 5630 if (li != null && li.mOnClickListener != null) { 5631 li.mOnClickListener.onClick(this); 5632 return true; 5633 } 5634 return false; 5635 } 5636 5637 /** 5638 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5639 * context menu if the OnLongClickListener did not consume the event. 5640 * 5641 * @return {@code true} if one of the above receivers consumed the event, 5642 * {@code false} otherwise 5643 */ 5644 public boolean performLongClick() { 5645 return performLongClickInternal(mLongClickX, mLongClickY); 5646 } 5647 5648 /** 5649 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5650 * context menu if the OnLongClickListener did not consume the event, 5651 * anchoring it to an (x,y) coordinate. 5652 * 5653 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5654 * to disable anchoring 5655 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5656 * to disable anchoring 5657 * @return {@code true} if one of the above receivers consumed the event, 5658 * {@code false} otherwise 5659 */ 5660 public boolean performLongClick(float x, float y) { 5661 mLongClickX = x; 5662 mLongClickY = y; 5663 final boolean handled = performLongClick(); 5664 mLongClickX = Float.NaN; 5665 mLongClickY = Float.NaN; 5666 return handled; 5667 } 5668 5669 /** 5670 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5671 * context menu if the OnLongClickListener did not consume the event, 5672 * optionally anchoring it to an (x,y) coordinate. 5673 * 5674 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5675 * to disable anchoring 5676 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5677 * to disable anchoring 5678 * @return {@code true} if one of the above receivers consumed the event, 5679 * {@code false} otherwise 5680 */ 5681 private boolean performLongClickInternal(float x, float y) { 5682 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5683 5684 boolean handled = false; 5685 final ListenerInfo li = mListenerInfo; 5686 if (li != null && li.mOnLongClickListener != null) { 5687 handled = li.mOnLongClickListener.onLongClick(View.this); 5688 } 5689 if (!handled) { 5690 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5691 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5692 } 5693 if (handled) { 5694 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5695 } 5696 return handled; 5697 } 5698 5699 /** 5700 * Call this view's OnContextClickListener, if it is defined. 5701 * 5702 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5703 * otherwise. 5704 */ 5705 public boolean performContextClick() { 5706 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5707 5708 boolean handled = false; 5709 ListenerInfo li = mListenerInfo; 5710 if (li != null && li.mOnContextClickListener != null) { 5711 handled = li.mOnContextClickListener.onContextClick(View.this); 5712 } 5713 if (handled) { 5714 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5715 } 5716 return handled; 5717 } 5718 5719 /** 5720 * Performs button-related actions during a touch down event. 5721 * 5722 * @param event The event. 5723 * @return True if the down was consumed. 5724 * 5725 * @hide 5726 */ 5727 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5728 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5729 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5730 showContextMenu(event.getX(), event.getY()); 5731 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5732 return true; 5733 } 5734 return false; 5735 } 5736 5737 /** 5738 * Shows the context menu for this view. 5739 * 5740 * @return {@code true} if the context menu was shown, {@code false} 5741 * otherwise 5742 * @see #showContextMenu(float, float) 5743 */ 5744 public boolean showContextMenu() { 5745 return getParent().showContextMenuForChild(this); 5746 } 5747 5748 /** 5749 * Shows the context menu for this view anchored to the specified 5750 * view-relative coordinate. 5751 * 5752 * @param x the X coordinate in pixels relative to the view to which the 5753 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5754 * @param y the Y coordinate in pixels relative to the view to which the 5755 * menu should be anchored, or {@link Float#NaN} to disable anchoring 5756 * @return {@code true} if the context menu was shown, {@code false} 5757 * otherwise 5758 */ 5759 public boolean showContextMenu(float x, float y) { 5760 return getParent().showContextMenuForChild(this, x, y); 5761 } 5762 5763 /** 5764 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5765 * 5766 * @param callback Callback that will control the lifecycle of the action mode 5767 * @return The new action mode if it is started, null otherwise 5768 * 5769 * @see ActionMode 5770 * @see #startActionMode(android.view.ActionMode.Callback, int) 5771 */ 5772 public ActionMode startActionMode(ActionMode.Callback callback) { 5773 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5774 } 5775 5776 /** 5777 * Start an action mode with the given type. 5778 * 5779 * @param callback Callback that will control the lifecycle of the action mode 5780 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5781 * @return The new action mode if it is started, null otherwise 5782 * 5783 * @see ActionMode 5784 */ 5785 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5786 ViewParent parent = getParent(); 5787 if (parent == null) return null; 5788 try { 5789 return parent.startActionModeForChild(this, callback, type); 5790 } catch (AbstractMethodError ame) { 5791 // Older implementations of custom views might not implement this. 5792 return parent.startActionModeForChild(this, callback); 5793 } 5794 } 5795 5796 /** 5797 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5798 * Context, creating a unique View identifier to retrieve the result. 5799 * 5800 * @param intent The Intent to be started. 5801 * @param requestCode The request code to use. 5802 * @hide 5803 */ 5804 public void startActivityForResult(Intent intent, int requestCode) { 5805 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5806 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5807 } 5808 5809 /** 5810 * If this View corresponds to the calling who, dispatches the activity result. 5811 * @param who The identifier for the targeted View to receive the result. 5812 * @param requestCode The integer request code originally supplied to 5813 * startActivityForResult(), allowing you to identify who this 5814 * result came from. 5815 * @param resultCode The integer result code returned by the child activity 5816 * through its setResult(). 5817 * @param data An Intent, which can return result data to the caller 5818 * (various data can be attached to Intent "extras"). 5819 * @return {@code true} if the activity result was dispatched. 5820 * @hide 5821 */ 5822 public boolean dispatchActivityResult( 5823 String who, int requestCode, int resultCode, Intent data) { 5824 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5825 onActivityResult(requestCode, resultCode, data); 5826 mStartActivityRequestWho = null; 5827 return true; 5828 } 5829 return false; 5830 } 5831 5832 /** 5833 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5834 * 5835 * @param requestCode The integer request code originally supplied to 5836 * startActivityForResult(), allowing you to identify who this 5837 * result came from. 5838 * @param resultCode The integer result code returned by the child activity 5839 * through its setResult(). 5840 * @param data An Intent, which can return result data to the caller 5841 * (various data can be attached to Intent "extras"). 5842 * @hide 5843 */ 5844 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5845 // Do nothing. 5846 } 5847 5848 /** 5849 * Register a callback to be invoked when a hardware key is pressed in this view. 5850 * Key presses in software input methods will generally not trigger the methods of 5851 * this listener. 5852 * @param l the key listener to attach to this view 5853 */ 5854 public void setOnKeyListener(OnKeyListener l) { 5855 getListenerInfo().mOnKeyListener = l; 5856 } 5857 5858 /** 5859 * Register a callback to be invoked when a touch event is sent to this view. 5860 * @param l the touch listener to attach to this view 5861 */ 5862 public void setOnTouchListener(OnTouchListener l) { 5863 getListenerInfo().mOnTouchListener = l; 5864 } 5865 5866 /** 5867 * Register a callback to be invoked when a generic motion event is sent to this view. 5868 * @param l the generic motion listener to attach to this view 5869 */ 5870 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5871 getListenerInfo().mOnGenericMotionListener = l; 5872 } 5873 5874 /** 5875 * Register a callback to be invoked when a hover event is sent to this view. 5876 * @param l the hover listener to attach to this view 5877 */ 5878 public void setOnHoverListener(OnHoverListener l) { 5879 getListenerInfo().mOnHoverListener = l; 5880 } 5881 5882 /** 5883 * Register a drag event listener callback object for this View. The parameter is 5884 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5885 * View, the system calls the 5886 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5887 * @param l An implementation of {@link android.view.View.OnDragListener}. 5888 */ 5889 public void setOnDragListener(OnDragListener l) { 5890 getListenerInfo().mOnDragListener = l; 5891 } 5892 5893 /** 5894 * Give this view focus. This will cause 5895 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5896 * 5897 * Note: this does not check whether this {@link View} should get focus, it just 5898 * gives it focus no matter what. It should only be called internally by framework 5899 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5900 * 5901 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5902 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5903 * focus moved when requestFocus() is called. It may not always 5904 * apply, in which case use the default View.FOCUS_DOWN. 5905 * @param previouslyFocusedRect The rectangle of the view that had focus 5906 * prior in this View's coordinate system. 5907 */ 5908 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5909 if (DBG) { 5910 System.out.println(this + " requestFocus()"); 5911 } 5912 5913 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5914 mPrivateFlags |= PFLAG_FOCUSED; 5915 5916 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5917 5918 if (mParent != null) { 5919 mParent.requestChildFocus(this, this); 5920 } 5921 5922 if (mAttachInfo != null) { 5923 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5924 } 5925 5926 onFocusChanged(true, direction, previouslyFocusedRect); 5927 refreshDrawableState(); 5928 } 5929 } 5930 5931 /** 5932 * Populates <code>outRect</code> with the hotspot bounds. By default, 5933 * the hotspot bounds are identical to the screen bounds. 5934 * 5935 * @param outRect rect to populate with hotspot bounds 5936 * @hide Only for internal use by views and widgets. 5937 */ 5938 public void getHotspotBounds(Rect outRect) { 5939 final Drawable background = getBackground(); 5940 if (background != null) { 5941 background.getHotspotBounds(outRect); 5942 } else { 5943 getBoundsOnScreen(outRect); 5944 } 5945 } 5946 5947 /** 5948 * Request that a rectangle of this view be visible on the screen, 5949 * scrolling if necessary just enough. 5950 * 5951 * <p>A View should call this if it maintains some notion of which part 5952 * of its content is interesting. For example, a text editing view 5953 * should call this when its cursor moves. 5954 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5955 * It should not be affected by which part of the View is currently visible or its scroll 5956 * position. 5957 * 5958 * @param rectangle The rectangle in the View's content coordinate space 5959 * @return Whether any parent scrolled. 5960 */ 5961 public boolean requestRectangleOnScreen(Rect rectangle) { 5962 return requestRectangleOnScreen(rectangle, false); 5963 } 5964 5965 /** 5966 * Request that a rectangle of this view be visible on the screen, 5967 * scrolling if necessary just enough. 5968 * 5969 * <p>A View should call this if it maintains some notion of which part 5970 * of its content is interesting. For example, a text editing view 5971 * should call this when its cursor moves. 5972 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5973 * It should not be affected by which part of the View is currently visible or its scroll 5974 * position. 5975 * <p>When <code>immediate</code> is set to true, scrolling will not be 5976 * animated. 5977 * 5978 * @param rectangle The rectangle in the View's content coordinate space 5979 * @param immediate True to forbid animated scrolling, false otherwise 5980 * @return Whether any parent scrolled. 5981 */ 5982 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5983 if (mParent == null) { 5984 return false; 5985 } 5986 5987 View child = this; 5988 5989 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5990 position.set(rectangle); 5991 5992 ViewParent parent = mParent; 5993 boolean scrolled = false; 5994 while (parent != null) { 5995 rectangle.set((int) position.left, (int) position.top, 5996 (int) position.right, (int) position.bottom); 5997 5998 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 5999 6000 if (!(parent instanceof View)) { 6001 break; 6002 } 6003 6004 // move it from child's content coordinate space to parent's content coordinate space 6005 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6006 6007 child = (View) parent; 6008 parent = child.getParent(); 6009 } 6010 6011 return scrolled; 6012 } 6013 6014 /** 6015 * Called when this view wants to give up focus. If focus is cleared 6016 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6017 * <p> 6018 * <strong>Note:</strong> When a View clears focus the framework is trying 6019 * to give focus to the first focusable View from the top. Hence, if this 6020 * View is the first from the top that can take focus, then all callbacks 6021 * related to clearing focus will be invoked after which the framework will 6022 * give focus to this view. 6023 * </p> 6024 */ 6025 public void clearFocus() { 6026 if (DBG) { 6027 System.out.println(this + " clearFocus()"); 6028 } 6029 6030 clearFocusInternal(null, true, true); 6031 } 6032 6033 /** 6034 * Clears focus from the view, optionally propagating the change up through 6035 * the parent hierarchy and requesting that the root view place new focus. 6036 * 6037 * @param propagate whether to propagate the change up through the parent 6038 * hierarchy 6039 * @param refocus when propagate is true, specifies whether to request the 6040 * root view place new focus 6041 */ 6042 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6043 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6044 mPrivateFlags &= ~PFLAG_FOCUSED; 6045 6046 if (propagate && mParent != null) { 6047 mParent.clearChildFocus(this); 6048 } 6049 6050 onFocusChanged(false, 0, null); 6051 refreshDrawableState(); 6052 6053 if (propagate && (!refocus || !rootViewRequestFocus())) { 6054 notifyGlobalFocusCleared(this); 6055 } 6056 } 6057 } 6058 6059 void notifyGlobalFocusCleared(View oldFocus) { 6060 if (oldFocus != null && mAttachInfo != null) { 6061 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6062 } 6063 } 6064 6065 boolean rootViewRequestFocus() { 6066 final View root = getRootView(); 6067 return root != null && root.requestFocus(); 6068 } 6069 6070 /** 6071 * Called internally by the view system when a new view is getting focus. 6072 * This is what clears the old focus. 6073 * <p> 6074 * <b>NOTE:</b> The parent view's focused child must be updated manually 6075 * after calling this method. Otherwise, the view hierarchy may be left in 6076 * an inconstent state. 6077 */ 6078 void unFocus(View focused) { 6079 if (DBG) { 6080 System.out.println(this + " unFocus()"); 6081 } 6082 6083 clearFocusInternal(focused, false, false); 6084 } 6085 6086 /** 6087 * Returns true if this view has focus itself, or is the ancestor of the 6088 * view that has focus. 6089 * 6090 * @return True if this view has or contains focus, false otherwise. 6091 */ 6092 @ViewDebug.ExportedProperty(category = "focus") 6093 public boolean hasFocus() { 6094 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6095 } 6096 6097 /** 6098 * Returns true if this view is focusable or if it contains a reachable View 6099 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6100 * is a View whose parents do not block descendants focus. 6101 * 6102 * Only {@link #VISIBLE} views are considered focusable. 6103 * 6104 * @return True if the view is focusable or if the view contains a focusable 6105 * View, false otherwise. 6106 * 6107 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6108 * @see ViewGroup#getTouchscreenBlocksFocus() 6109 */ 6110 public boolean hasFocusable() { 6111 if (!isFocusableInTouchMode()) { 6112 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6113 final ViewGroup g = (ViewGroup) p; 6114 if (g.shouldBlockFocusForTouchscreen()) { 6115 return false; 6116 } 6117 } 6118 } 6119 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6120 } 6121 6122 /** 6123 * Called by the view system when the focus state of this view changes. 6124 * When the focus change event is caused by directional navigation, direction 6125 * and previouslyFocusedRect provide insight into where the focus is coming from. 6126 * When overriding, be sure to call up through to the super class so that 6127 * the standard focus handling will occur. 6128 * 6129 * @param gainFocus True if the View has focus; false otherwise. 6130 * @param direction The direction focus has moved when requestFocus() 6131 * is called to give this view focus. Values are 6132 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6133 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6134 * It may not always apply, in which case use the default. 6135 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6136 * system, of the previously focused view. If applicable, this will be 6137 * passed in as finer grained information about where the focus is coming 6138 * from (in addition to direction). Will be <code>null</code> otherwise. 6139 */ 6140 @CallSuper 6141 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6142 @Nullable Rect previouslyFocusedRect) { 6143 if (gainFocus) { 6144 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6145 } else { 6146 notifyViewAccessibilityStateChangedIfNeeded( 6147 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6148 } 6149 6150 InputMethodManager imm = InputMethodManager.peekInstance(); 6151 if (!gainFocus) { 6152 if (isPressed()) { 6153 setPressed(false); 6154 } 6155 if (imm != null && mAttachInfo != null 6156 && mAttachInfo.mHasWindowFocus) { 6157 imm.focusOut(this); 6158 } 6159 onFocusLost(); 6160 } else if (imm != null && mAttachInfo != null 6161 && mAttachInfo.mHasWindowFocus) { 6162 imm.focusIn(this); 6163 } 6164 6165 invalidate(true); 6166 ListenerInfo li = mListenerInfo; 6167 if (li != null && li.mOnFocusChangeListener != null) { 6168 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6169 } 6170 6171 if (mAttachInfo != null) { 6172 mAttachInfo.mKeyDispatchState.reset(this); 6173 } 6174 } 6175 6176 /** 6177 * Sends an accessibility event of the given type. If accessibility is 6178 * not enabled this method has no effect. The default implementation calls 6179 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6180 * to populate information about the event source (this View), then calls 6181 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6182 * populate the text content of the event source including its descendants, 6183 * and last calls 6184 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6185 * on its parent to request sending of the event to interested parties. 6186 * <p> 6187 * If an {@link AccessibilityDelegate} has been specified via calling 6188 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6189 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6190 * responsible for handling this call. 6191 * </p> 6192 * 6193 * @param eventType The type of the event to send, as defined by several types from 6194 * {@link android.view.accessibility.AccessibilityEvent}, such as 6195 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6196 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6197 * 6198 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6199 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6200 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6201 * @see AccessibilityDelegate 6202 */ 6203 public void sendAccessibilityEvent(int eventType) { 6204 if (mAccessibilityDelegate != null) { 6205 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6206 } else { 6207 sendAccessibilityEventInternal(eventType); 6208 } 6209 } 6210 6211 /** 6212 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6213 * {@link AccessibilityEvent} to make an announcement which is related to some 6214 * sort of a context change for which none of the events representing UI transitions 6215 * is a good fit. For example, announcing a new page in a book. If accessibility 6216 * is not enabled this method does nothing. 6217 * 6218 * @param text The announcement text. 6219 */ 6220 public void announceForAccessibility(CharSequence text) { 6221 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6222 AccessibilityEvent event = AccessibilityEvent.obtain( 6223 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6224 onInitializeAccessibilityEvent(event); 6225 event.getText().add(text); 6226 event.setContentDescription(null); 6227 mParent.requestSendAccessibilityEvent(this, event); 6228 } 6229 } 6230 6231 /** 6232 * @see #sendAccessibilityEvent(int) 6233 * 6234 * Note: Called from the default {@link AccessibilityDelegate}. 6235 * 6236 * @hide 6237 */ 6238 public void sendAccessibilityEventInternal(int eventType) { 6239 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6240 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6241 } 6242 } 6243 6244 /** 6245 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6246 * takes as an argument an empty {@link AccessibilityEvent} and does not 6247 * perform a check whether accessibility is enabled. 6248 * <p> 6249 * If an {@link AccessibilityDelegate} has been specified via calling 6250 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6251 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6252 * is responsible for handling this call. 6253 * </p> 6254 * 6255 * @param event The event to send. 6256 * 6257 * @see #sendAccessibilityEvent(int) 6258 */ 6259 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6260 if (mAccessibilityDelegate != null) { 6261 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6262 } else { 6263 sendAccessibilityEventUncheckedInternal(event); 6264 } 6265 } 6266 6267 /** 6268 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6269 * 6270 * Note: Called from the default {@link AccessibilityDelegate}. 6271 * 6272 * @hide 6273 */ 6274 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6275 if (!isShown()) { 6276 return; 6277 } 6278 onInitializeAccessibilityEvent(event); 6279 // Only a subset of accessibility events populates text content. 6280 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6281 dispatchPopulateAccessibilityEvent(event); 6282 } 6283 // In the beginning we called #isShown(), so we know that getParent() is not null. 6284 getParent().requestSendAccessibilityEvent(this, event); 6285 } 6286 6287 /** 6288 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6289 * to its children for adding their text content to the event. Note that the 6290 * event text is populated in a separate dispatch path since we add to the 6291 * event not only the text of the source but also the text of all its descendants. 6292 * A typical implementation will call 6293 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6294 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6295 * on each child. Override this method if custom population of the event text 6296 * content is required. 6297 * <p> 6298 * If an {@link AccessibilityDelegate} has been specified via calling 6299 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6300 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6301 * is responsible for handling this call. 6302 * </p> 6303 * <p> 6304 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6305 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6306 * </p> 6307 * 6308 * @param event The event. 6309 * 6310 * @return True if the event population was completed. 6311 */ 6312 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6313 if (mAccessibilityDelegate != null) { 6314 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6315 } else { 6316 return dispatchPopulateAccessibilityEventInternal(event); 6317 } 6318 } 6319 6320 /** 6321 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6322 * 6323 * Note: Called from the default {@link AccessibilityDelegate}. 6324 * 6325 * @hide 6326 */ 6327 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6328 onPopulateAccessibilityEvent(event); 6329 return false; 6330 } 6331 6332 /** 6333 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6334 * giving a chance to this View to populate the accessibility event with its 6335 * text content. While this method is free to modify event 6336 * attributes other than text content, doing so should normally be performed in 6337 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6338 * <p> 6339 * Example: Adding formatted date string to an accessibility event in addition 6340 * to the text added by the super implementation: 6341 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6342 * super.onPopulateAccessibilityEvent(event); 6343 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6344 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6345 * mCurrentDate.getTimeInMillis(), flags); 6346 * event.getText().add(selectedDateUtterance); 6347 * }</pre> 6348 * <p> 6349 * If an {@link AccessibilityDelegate} has been specified via calling 6350 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6351 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6352 * is responsible for handling this call. 6353 * </p> 6354 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6355 * information to the event, in case the default implementation has basic information to add. 6356 * </p> 6357 * 6358 * @param event The accessibility event which to populate. 6359 * 6360 * @see #sendAccessibilityEvent(int) 6361 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6362 */ 6363 @CallSuper 6364 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6365 if (mAccessibilityDelegate != null) { 6366 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6367 } else { 6368 onPopulateAccessibilityEventInternal(event); 6369 } 6370 } 6371 6372 /** 6373 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6374 * 6375 * Note: Called from the default {@link AccessibilityDelegate}. 6376 * 6377 * @hide 6378 */ 6379 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6380 } 6381 6382 /** 6383 * Initializes an {@link AccessibilityEvent} with information about 6384 * this View which is the event source. In other words, the source of 6385 * an accessibility event is the view whose state change triggered firing 6386 * the event. 6387 * <p> 6388 * Example: Setting the password property of an event in addition 6389 * to properties set by the super implementation: 6390 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6391 * super.onInitializeAccessibilityEvent(event); 6392 * event.setPassword(true); 6393 * }</pre> 6394 * <p> 6395 * If an {@link AccessibilityDelegate} has been specified via calling 6396 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6397 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6398 * is responsible for handling this call. 6399 * </p> 6400 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6401 * information to the event, in case the default implementation has basic information to add. 6402 * </p> 6403 * @param event The event to initialize. 6404 * 6405 * @see #sendAccessibilityEvent(int) 6406 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6407 */ 6408 @CallSuper 6409 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6410 if (mAccessibilityDelegate != null) { 6411 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6412 } else { 6413 onInitializeAccessibilityEventInternal(event); 6414 } 6415 } 6416 6417 /** 6418 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6419 * 6420 * Note: Called from the default {@link AccessibilityDelegate}. 6421 * 6422 * @hide 6423 */ 6424 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6425 event.setSource(this); 6426 event.setClassName(getAccessibilityClassName()); 6427 event.setPackageName(getContext().getPackageName()); 6428 event.setEnabled(isEnabled()); 6429 event.setContentDescription(mContentDescription); 6430 6431 switch (event.getEventType()) { 6432 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6433 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6434 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6435 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6436 event.setItemCount(focusablesTempList.size()); 6437 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6438 if (mAttachInfo != null) { 6439 focusablesTempList.clear(); 6440 } 6441 } break; 6442 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6443 CharSequence text = getIterableTextForAccessibility(); 6444 if (text != null && text.length() > 0) { 6445 event.setFromIndex(getAccessibilitySelectionStart()); 6446 event.setToIndex(getAccessibilitySelectionEnd()); 6447 event.setItemCount(text.length()); 6448 } 6449 } break; 6450 } 6451 } 6452 6453 /** 6454 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6455 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6456 * This method is responsible for obtaining an accessibility node info from a 6457 * pool of reusable instances and calling 6458 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6459 * initialize the former. 6460 * <p> 6461 * Note: The client is responsible for recycling the obtained instance by calling 6462 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6463 * </p> 6464 * 6465 * @return A populated {@link AccessibilityNodeInfo}. 6466 * 6467 * @see AccessibilityNodeInfo 6468 */ 6469 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6470 if (mAccessibilityDelegate != null) { 6471 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6472 } else { 6473 return createAccessibilityNodeInfoInternal(); 6474 } 6475 } 6476 6477 /** 6478 * @see #createAccessibilityNodeInfo() 6479 * 6480 * @hide 6481 */ 6482 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6483 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6484 if (provider != null) { 6485 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6486 } else { 6487 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6488 onInitializeAccessibilityNodeInfo(info); 6489 return info; 6490 } 6491 } 6492 6493 /** 6494 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6495 * The base implementation sets: 6496 * <ul> 6497 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6498 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6499 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6500 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6501 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6502 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6503 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6504 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6505 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6506 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6507 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6508 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6509 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6510 * </ul> 6511 * <p> 6512 * Subclasses should override this method, call the super implementation, 6513 * and set additional attributes. 6514 * </p> 6515 * <p> 6516 * If an {@link AccessibilityDelegate} has been specified via calling 6517 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6518 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6519 * is responsible for handling this call. 6520 * </p> 6521 * 6522 * @param info The instance to initialize. 6523 */ 6524 @CallSuper 6525 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6526 if (mAccessibilityDelegate != null) { 6527 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6528 } else { 6529 onInitializeAccessibilityNodeInfoInternal(info); 6530 } 6531 } 6532 6533 /** 6534 * Gets the location of this view in screen coordinates. 6535 * 6536 * @param outRect The output location 6537 * @hide 6538 */ 6539 public void getBoundsOnScreen(Rect outRect) { 6540 getBoundsOnScreen(outRect, false); 6541 } 6542 6543 /** 6544 * Gets the location of this view in screen coordinates. 6545 * 6546 * @param outRect The output location 6547 * @param clipToParent Whether to clip child bounds to the parent ones. 6548 * @hide 6549 */ 6550 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6551 if (mAttachInfo == null) { 6552 return; 6553 } 6554 6555 RectF position = mAttachInfo.mTmpTransformRect; 6556 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6557 6558 if (!hasIdentityMatrix()) { 6559 getMatrix().mapRect(position); 6560 } 6561 6562 position.offset(mLeft, mTop); 6563 6564 ViewParent parent = mParent; 6565 while (parent instanceof View) { 6566 View parentView = (View) parent; 6567 6568 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6569 6570 if (clipToParent) { 6571 position.left = Math.max(position.left, 0); 6572 position.top = Math.max(position.top, 0); 6573 position.right = Math.min(position.right, parentView.getWidth()); 6574 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6575 } 6576 6577 if (!parentView.hasIdentityMatrix()) { 6578 parentView.getMatrix().mapRect(position); 6579 } 6580 6581 position.offset(parentView.mLeft, parentView.mTop); 6582 6583 parent = parentView.mParent; 6584 } 6585 6586 if (parent instanceof ViewRootImpl) { 6587 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6588 position.offset(0, -viewRootImpl.mCurScrollY); 6589 } 6590 6591 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6592 6593 outRect.set(Math.round(position.left), Math.round(position.top), 6594 Math.round(position.right), Math.round(position.bottom)); 6595 } 6596 6597 /** 6598 * Return the class name of this object to be used for accessibility purposes. 6599 * Subclasses should only override this if they are implementing something that 6600 * should be seen as a completely new class of view when used by accessibility, 6601 * unrelated to the class it is deriving from. This is used to fill in 6602 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6603 */ 6604 public CharSequence getAccessibilityClassName() { 6605 return View.class.getName(); 6606 } 6607 6608 /** 6609 * Called when assist structure is being retrieved from a view as part of 6610 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6611 * @param structure Fill in with structured view data. The default implementation 6612 * fills in all data that can be inferred from the view itself. 6613 */ 6614 public void onProvideStructure(ViewStructure structure) { 6615 final int id = mID; 6616 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6617 && (id&0x0000ffff) != 0) { 6618 String pkg, type, entry; 6619 try { 6620 final Resources res = getResources(); 6621 entry = res.getResourceEntryName(id); 6622 type = res.getResourceTypeName(id); 6623 pkg = res.getResourcePackageName(id); 6624 } catch (Resources.NotFoundException e) { 6625 entry = type = pkg = null; 6626 } 6627 structure.setId(id, pkg, type, entry); 6628 } else { 6629 structure.setId(id, null, null, null); 6630 } 6631 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6632 if (!hasIdentityMatrix()) { 6633 structure.setTransformation(getMatrix()); 6634 } 6635 structure.setElevation(getZ()); 6636 structure.setVisibility(getVisibility()); 6637 structure.setEnabled(isEnabled()); 6638 if (isClickable()) { 6639 structure.setClickable(true); 6640 } 6641 if (isFocusable()) { 6642 structure.setFocusable(true); 6643 } 6644 if (isFocused()) { 6645 structure.setFocused(true); 6646 } 6647 if (isAccessibilityFocused()) { 6648 structure.setAccessibilityFocused(true); 6649 } 6650 if (isSelected()) { 6651 structure.setSelected(true); 6652 } 6653 if (isActivated()) { 6654 structure.setActivated(true); 6655 } 6656 if (isLongClickable()) { 6657 structure.setLongClickable(true); 6658 } 6659 if (this instanceof Checkable) { 6660 structure.setCheckable(true); 6661 if (((Checkable)this).isChecked()) { 6662 structure.setChecked(true); 6663 } 6664 } 6665 if (isContextClickable()) { 6666 structure.setContextClickable(true); 6667 } 6668 structure.setClassName(getAccessibilityClassName().toString()); 6669 structure.setContentDescription(getContentDescription()); 6670 } 6671 6672 /** 6673 * Called when assist structure is being retrieved from a view as part of 6674 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6675 * generate additional virtual structure under this view. The defaullt implementation 6676 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6677 * view's virtual accessibility nodes, if any. You can override this for a more 6678 * optimal implementation providing this data. 6679 */ 6680 public void onProvideVirtualStructure(ViewStructure structure) { 6681 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6682 if (provider != null) { 6683 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6684 structure.setChildCount(1); 6685 ViewStructure root = structure.newChild(0); 6686 populateVirtualStructure(root, provider, info); 6687 info.recycle(); 6688 } 6689 } 6690 6691 private void populateVirtualStructure(ViewStructure structure, 6692 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6693 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6694 null, null, null); 6695 Rect rect = structure.getTempRect(); 6696 info.getBoundsInParent(rect); 6697 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6698 structure.setVisibility(VISIBLE); 6699 structure.setEnabled(info.isEnabled()); 6700 if (info.isClickable()) { 6701 structure.setClickable(true); 6702 } 6703 if (info.isFocusable()) { 6704 structure.setFocusable(true); 6705 } 6706 if (info.isFocused()) { 6707 structure.setFocused(true); 6708 } 6709 if (info.isAccessibilityFocused()) { 6710 structure.setAccessibilityFocused(true); 6711 } 6712 if (info.isSelected()) { 6713 structure.setSelected(true); 6714 } 6715 if (info.isLongClickable()) { 6716 structure.setLongClickable(true); 6717 } 6718 if (info.isCheckable()) { 6719 structure.setCheckable(true); 6720 if (info.isChecked()) { 6721 structure.setChecked(true); 6722 } 6723 } 6724 if (info.isContextClickable()) { 6725 structure.setContextClickable(true); 6726 } 6727 CharSequence cname = info.getClassName(); 6728 structure.setClassName(cname != null ? cname.toString() : null); 6729 structure.setContentDescription(info.getContentDescription()); 6730 if (info.getText() != null || info.getError() != null) { 6731 structure.setText(info.getText(), info.getTextSelectionStart(), 6732 info.getTextSelectionEnd()); 6733 } 6734 final int NCHILDREN = info.getChildCount(); 6735 if (NCHILDREN > 0) { 6736 structure.setChildCount(NCHILDREN); 6737 for (int i=0; i<NCHILDREN; i++) { 6738 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6739 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6740 ViewStructure child = structure.newChild(i); 6741 populateVirtualStructure(child, provider, cinfo); 6742 cinfo.recycle(); 6743 } 6744 } 6745 } 6746 6747 /** 6748 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6749 * implementation calls {@link #onProvideStructure} and 6750 * {@link #onProvideVirtualStructure}. 6751 */ 6752 public void dispatchProvideStructure(ViewStructure structure) { 6753 if (!isAssistBlocked()) { 6754 onProvideStructure(structure); 6755 onProvideVirtualStructure(structure); 6756 } else { 6757 structure.setClassName(getAccessibilityClassName().toString()); 6758 structure.setAssistBlocked(true); 6759 } 6760 } 6761 6762 /** 6763 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6764 * 6765 * Note: Called from the default {@link AccessibilityDelegate}. 6766 * 6767 * @hide 6768 */ 6769 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6770 if (mAttachInfo == null) { 6771 return; 6772 } 6773 6774 Rect bounds = mAttachInfo.mTmpInvalRect; 6775 6776 getDrawingRect(bounds); 6777 info.setBoundsInParent(bounds); 6778 6779 getBoundsOnScreen(bounds, true); 6780 info.setBoundsInScreen(bounds); 6781 6782 ViewParent parent = getParentForAccessibility(); 6783 if (parent instanceof View) { 6784 info.setParent((View) parent); 6785 } 6786 6787 if (mID != View.NO_ID) { 6788 View rootView = getRootView(); 6789 if (rootView == null) { 6790 rootView = this; 6791 } 6792 6793 View label = rootView.findLabelForView(this, mID); 6794 if (label != null) { 6795 info.setLabeledBy(label); 6796 } 6797 6798 if ((mAttachInfo.mAccessibilityFetchFlags 6799 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6800 && Resources.resourceHasPackage(mID)) { 6801 try { 6802 String viewId = getResources().getResourceName(mID); 6803 info.setViewIdResourceName(viewId); 6804 } catch (Resources.NotFoundException nfe) { 6805 /* ignore */ 6806 } 6807 } 6808 } 6809 6810 if (mLabelForId != View.NO_ID) { 6811 View rootView = getRootView(); 6812 if (rootView == null) { 6813 rootView = this; 6814 } 6815 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6816 if (labeled != null) { 6817 info.setLabelFor(labeled); 6818 } 6819 } 6820 6821 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6822 View rootView = getRootView(); 6823 if (rootView == null) { 6824 rootView = this; 6825 } 6826 View next = rootView.findViewInsideOutShouldExist(this, 6827 mAccessibilityTraversalBeforeId); 6828 if (next != null && next.includeForAccessibility()) { 6829 info.setTraversalBefore(next); 6830 } 6831 } 6832 6833 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6834 View rootView = getRootView(); 6835 if (rootView == null) { 6836 rootView = this; 6837 } 6838 View next = rootView.findViewInsideOutShouldExist(this, 6839 mAccessibilityTraversalAfterId); 6840 if (next != null && next.includeForAccessibility()) { 6841 info.setTraversalAfter(next); 6842 } 6843 } 6844 6845 info.setVisibleToUser(isVisibleToUser()); 6846 6847 if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags 6848 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) { 6849 info.setImportantForAccessibility(isImportantForAccessibility()); 6850 } else { 6851 info.setImportantForAccessibility(true); 6852 } 6853 6854 info.setPackageName(mContext.getPackageName()); 6855 info.setClassName(getAccessibilityClassName()); 6856 info.setContentDescription(getContentDescription()); 6857 6858 info.setEnabled(isEnabled()); 6859 info.setClickable(isClickable()); 6860 info.setFocusable(isFocusable()); 6861 info.setFocused(isFocused()); 6862 info.setAccessibilityFocused(isAccessibilityFocused()); 6863 info.setSelected(isSelected()); 6864 info.setLongClickable(isLongClickable()); 6865 info.setContextClickable(isContextClickable()); 6866 info.setLiveRegion(getAccessibilityLiveRegion()); 6867 6868 // TODO: These make sense only if we are in an AdapterView but all 6869 // views can be selected. Maybe from accessibility perspective 6870 // we should report as selectable view in an AdapterView. 6871 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6872 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6873 6874 if (isFocusable()) { 6875 if (isFocused()) { 6876 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6877 } else { 6878 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6879 } 6880 } 6881 6882 if (!isAccessibilityFocused()) { 6883 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6884 } else { 6885 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6886 } 6887 6888 if (isClickable() && isEnabled()) { 6889 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6890 } 6891 6892 if (isLongClickable() && isEnabled()) { 6893 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6894 } 6895 6896 if (isContextClickable() && isEnabled()) { 6897 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6898 } 6899 6900 CharSequence text = getIterableTextForAccessibility(); 6901 if (text != null && text.length() > 0) { 6902 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6903 6904 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6905 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6906 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6907 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6908 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6909 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6910 } 6911 6912 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6913 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6914 } 6915 6916 /** 6917 * Determine the order in which this view will be drawn relative to its siblings for a11y 6918 * 6919 * @param info The info whose drawing order should be populated 6920 */ 6921 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6922 /* 6923 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6924 * drawing order may not be well-defined, and some Views with custom drawing order may 6925 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6926 */ 6927 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6928 info.setDrawingOrder(0); 6929 return; 6930 } 6931 int drawingOrderInParent = 1; 6932 // Iterate up the hierarchy if parents are not important for a11y 6933 View viewAtDrawingLevel = this; 6934 final ViewParent parent = getParentForAccessibility(); 6935 while (viewAtDrawingLevel != parent) { 6936 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6937 if (!(currentParent instanceof ViewGroup)) { 6938 // Should only happen for the Decor 6939 drawingOrderInParent = 0; 6940 break; 6941 } else { 6942 final ViewGroup parentGroup = (ViewGroup) currentParent; 6943 final int childCount = parentGroup.getChildCount(); 6944 if (childCount > 1) { 6945 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6946 if (preorderedList != null) { 6947 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6948 for (int i = 0; i < childDrawIndex; i++) { 6949 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6950 } 6951 } else { 6952 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 6953 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 6954 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 6955 .getChildDrawingOrder(childCount, childIndex) : childIndex; 6956 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 6957 if (childDrawIndex != 0) { 6958 for (int i = 0; i < numChildrenToIterate; i++) { 6959 final int otherDrawIndex = (customOrder ? 6960 parentGroup.getChildDrawingOrder(childCount, i) : i); 6961 if (otherDrawIndex < childDrawIndex) { 6962 drawingOrderInParent += 6963 numViewsForAccessibility(parentGroup.getChildAt(i)); 6964 } 6965 } 6966 } 6967 } 6968 } 6969 } 6970 viewAtDrawingLevel = (View) currentParent; 6971 } 6972 info.setDrawingOrder(drawingOrderInParent); 6973 } 6974 6975 private static int numViewsForAccessibility(View view) { 6976 if (view != null) { 6977 if (view.includeForAccessibility()) { 6978 return 1; 6979 } else if (view instanceof ViewGroup) { 6980 return ((ViewGroup) view).getNumChildrenForAccessibility(); 6981 } 6982 } 6983 return 0; 6984 } 6985 6986 private View findLabelForView(View view, int labeledId) { 6987 if (mMatchLabelForPredicate == null) { 6988 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6989 } 6990 mMatchLabelForPredicate.mLabeledId = labeledId; 6991 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6992 } 6993 6994 /** 6995 * Computes whether this view is visible to the user. Such a view is 6996 * attached, visible, all its predecessors are visible, it is not clipped 6997 * entirely by its predecessors, and has an alpha greater than zero. 6998 * 6999 * @return Whether the view is visible on the screen. 7000 * 7001 * @hide 7002 */ 7003 protected boolean isVisibleToUser() { 7004 return isVisibleToUser(null); 7005 } 7006 7007 /** 7008 * Computes whether the given portion of this view is visible to the user. 7009 * Such a view is attached, visible, all its predecessors are visible, 7010 * has an alpha greater than zero, and the specified portion is not 7011 * clipped entirely by its predecessors. 7012 * 7013 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7014 * <code>null</code>, and the entire view will be tested in this case. 7015 * When <code>true</code> is returned by the function, the actual visible 7016 * region will be stored in this parameter; that is, if boundInView is fully 7017 * contained within the view, no modification will be made, otherwise regions 7018 * outside of the visible area of the view will be clipped. 7019 * 7020 * @return Whether the specified portion of the view is visible on the screen. 7021 * 7022 * @hide 7023 */ 7024 protected boolean isVisibleToUser(Rect boundInView) { 7025 if (mAttachInfo != null) { 7026 // Attached to invisible window means this view is not visible. 7027 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7028 return false; 7029 } 7030 // An invisible predecessor or one with alpha zero means 7031 // that this view is not visible to the user. 7032 Object current = this; 7033 while (current instanceof View) { 7034 View view = (View) current; 7035 // We have attach info so this view is attached and there is no 7036 // need to check whether we reach to ViewRootImpl on the way up. 7037 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7038 view.getVisibility() != VISIBLE) { 7039 return false; 7040 } 7041 current = view.mParent; 7042 } 7043 // Check if the view is entirely covered by its predecessors. 7044 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7045 Point offset = mAttachInfo.mPoint; 7046 if (!getGlobalVisibleRect(visibleRect, offset)) { 7047 return false; 7048 } 7049 // Check if the visible portion intersects the rectangle of interest. 7050 if (boundInView != null) { 7051 visibleRect.offset(-offset.x, -offset.y); 7052 return boundInView.intersect(visibleRect); 7053 } 7054 return true; 7055 } 7056 return false; 7057 } 7058 7059 /** 7060 * Returns the delegate for implementing accessibility support via 7061 * composition. For more details see {@link AccessibilityDelegate}. 7062 * 7063 * @return The delegate, or null if none set. 7064 * 7065 * @hide 7066 */ 7067 public AccessibilityDelegate getAccessibilityDelegate() { 7068 return mAccessibilityDelegate; 7069 } 7070 7071 /** 7072 * Sets a delegate for implementing accessibility support via composition 7073 * (as opposed to inheritance). For more details, see 7074 * {@link AccessibilityDelegate}. 7075 * <p> 7076 * <strong>Note:</strong> On platform versions prior to 7077 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7078 * views in the {@code android.widget.*} package are called <i>before</i> 7079 * host methods. This prevents certain properties such as class name from 7080 * being modified by overriding 7081 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7082 * as any changes will be overwritten by the host class. 7083 * <p> 7084 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7085 * methods are called <i>after</i> host methods, which all properties to be 7086 * modified without being overwritten by the host class. 7087 * 7088 * @param delegate the object to which accessibility method calls should be 7089 * delegated 7090 * @see AccessibilityDelegate 7091 */ 7092 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7093 mAccessibilityDelegate = delegate; 7094 } 7095 7096 /** 7097 * Gets the provider for managing a virtual view hierarchy rooted at this View 7098 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7099 * that explore the window content. 7100 * <p> 7101 * If this method returns an instance, this instance is responsible for managing 7102 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7103 * View including the one representing the View itself. Similarly the returned 7104 * instance is responsible for performing accessibility actions on any virtual 7105 * view or the root view itself. 7106 * </p> 7107 * <p> 7108 * If an {@link AccessibilityDelegate} has been specified via calling 7109 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7110 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7111 * is responsible for handling this call. 7112 * </p> 7113 * 7114 * @return The provider. 7115 * 7116 * @see AccessibilityNodeProvider 7117 */ 7118 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7119 if (mAccessibilityDelegate != null) { 7120 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7121 } else { 7122 return null; 7123 } 7124 } 7125 7126 /** 7127 * Gets the unique identifier of this view on the screen for accessibility purposes. 7128 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7129 * 7130 * @return The view accessibility id. 7131 * 7132 * @hide 7133 */ 7134 public int getAccessibilityViewId() { 7135 if (mAccessibilityViewId == NO_ID) { 7136 mAccessibilityViewId = sNextAccessibilityViewId++; 7137 } 7138 return mAccessibilityViewId; 7139 } 7140 7141 /** 7142 * Gets the unique identifier of the window in which this View reseides. 7143 * 7144 * @return The window accessibility id. 7145 * 7146 * @hide 7147 */ 7148 public int getAccessibilityWindowId() { 7149 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7150 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7151 } 7152 7153 /** 7154 * Returns the {@link View}'s content description. 7155 * <p> 7156 * <strong>Note:</strong> Do not override this method, as it will have no 7157 * effect on the content description presented to accessibility services. 7158 * You must call {@link #setContentDescription(CharSequence)} to modify the 7159 * content description. 7160 * 7161 * @return the content description 7162 * @see #setContentDescription(CharSequence) 7163 * @attr ref android.R.styleable#View_contentDescription 7164 */ 7165 @ViewDebug.ExportedProperty(category = "accessibility") 7166 public CharSequence getContentDescription() { 7167 return mContentDescription; 7168 } 7169 7170 /** 7171 * Sets the {@link View}'s content description. 7172 * <p> 7173 * A content description briefly describes the view and is primarily used 7174 * for accessibility support to determine how a view should be presented to 7175 * the user. In the case of a view with no textual representation, such as 7176 * {@link android.widget.ImageButton}, a useful content description 7177 * explains what the view does. For example, an image button with a phone 7178 * icon that is used to place a call may use "Call" as its content 7179 * description. An image of a floppy disk that is used to save a file may 7180 * use "Save". 7181 * 7182 * @param contentDescription The content description. 7183 * @see #getContentDescription() 7184 * @attr ref android.R.styleable#View_contentDescription 7185 */ 7186 @RemotableViewMethod 7187 public void setContentDescription(CharSequence contentDescription) { 7188 if (mContentDescription == null) { 7189 if (contentDescription == null) { 7190 return; 7191 } 7192 } else if (mContentDescription.equals(contentDescription)) { 7193 return; 7194 } 7195 mContentDescription = contentDescription; 7196 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7197 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7198 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7199 notifySubtreeAccessibilityStateChangedIfNeeded(); 7200 } else { 7201 notifyViewAccessibilityStateChangedIfNeeded( 7202 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7203 } 7204 } 7205 7206 /** 7207 * Sets the id of a view before which this one is visited in accessibility traversal. 7208 * A screen-reader must visit the content of this view before the content of the one 7209 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7210 * will traverse the entire content of B before traversing the entire content of A, 7211 * regardles of what traversal strategy it is using. 7212 * <p> 7213 * Views that do not have specified before/after relationships are traversed in order 7214 * determined by the screen-reader. 7215 * </p> 7216 * <p> 7217 * Setting that this view is before a view that is not important for accessibility 7218 * or if this view is not important for accessibility will have no effect as the 7219 * screen-reader is not aware of unimportant views. 7220 * </p> 7221 * 7222 * @param beforeId The id of a view this one precedes in accessibility traversal. 7223 * 7224 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7225 * 7226 * @see #setImportantForAccessibility(int) 7227 */ 7228 @RemotableViewMethod 7229 public void setAccessibilityTraversalBefore(int beforeId) { 7230 if (mAccessibilityTraversalBeforeId == beforeId) { 7231 return; 7232 } 7233 mAccessibilityTraversalBeforeId = beforeId; 7234 notifyViewAccessibilityStateChangedIfNeeded( 7235 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7236 } 7237 7238 /** 7239 * Gets the id of a view before which this one is visited in accessibility traversal. 7240 * 7241 * @return The id of a view this one precedes in accessibility traversal if 7242 * specified, otherwise {@link #NO_ID}. 7243 * 7244 * @see #setAccessibilityTraversalBefore(int) 7245 */ 7246 public int getAccessibilityTraversalBefore() { 7247 return mAccessibilityTraversalBeforeId; 7248 } 7249 7250 /** 7251 * Sets the id of a view after which this one is visited in accessibility traversal. 7252 * A screen-reader must visit the content of the other view before the content of this 7253 * one. For example, if view B is set to be after view A, then a screen-reader 7254 * will traverse the entire content of A before traversing the entire content of B, 7255 * regardles of what traversal strategy it is using. 7256 * <p> 7257 * Views that do not have specified before/after relationships are traversed in order 7258 * determined by the screen-reader. 7259 * </p> 7260 * <p> 7261 * Setting that this view is after a view that is not important for accessibility 7262 * or if this view is not important for accessibility will have no effect as the 7263 * screen-reader is not aware of unimportant views. 7264 * </p> 7265 * 7266 * @param afterId The id of a view this one succedees in accessibility traversal. 7267 * 7268 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7269 * 7270 * @see #setImportantForAccessibility(int) 7271 */ 7272 @RemotableViewMethod 7273 public void setAccessibilityTraversalAfter(int afterId) { 7274 if (mAccessibilityTraversalAfterId == afterId) { 7275 return; 7276 } 7277 mAccessibilityTraversalAfterId = afterId; 7278 notifyViewAccessibilityStateChangedIfNeeded( 7279 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7280 } 7281 7282 /** 7283 * Gets the id of a view after which this one is visited in accessibility traversal. 7284 * 7285 * @return The id of a view this one succeedes in accessibility traversal if 7286 * specified, otherwise {@link #NO_ID}. 7287 * 7288 * @see #setAccessibilityTraversalAfter(int) 7289 */ 7290 public int getAccessibilityTraversalAfter() { 7291 return mAccessibilityTraversalAfterId; 7292 } 7293 7294 /** 7295 * Gets the id of a view for which this view serves as a label for 7296 * accessibility purposes. 7297 * 7298 * @return The labeled view id. 7299 */ 7300 @ViewDebug.ExportedProperty(category = "accessibility") 7301 public int getLabelFor() { 7302 return mLabelForId; 7303 } 7304 7305 /** 7306 * Sets the id of a view for which this view serves as a label for 7307 * accessibility purposes. 7308 * 7309 * @param id The labeled view id. 7310 */ 7311 @RemotableViewMethod 7312 public void setLabelFor(@IdRes int id) { 7313 if (mLabelForId == id) { 7314 return; 7315 } 7316 mLabelForId = id; 7317 if (mLabelForId != View.NO_ID 7318 && mID == View.NO_ID) { 7319 mID = generateViewId(); 7320 } 7321 notifyViewAccessibilityStateChangedIfNeeded( 7322 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7323 } 7324 7325 /** 7326 * Invoked whenever this view loses focus, either by losing window focus or by losing 7327 * focus within its window. This method can be used to clear any state tied to the 7328 * focus. For instance, if a button is held pressed with the trackball and the window 7329 * loses focus, this method can be used to cancel the press. 7330 * 7331 * Subclasses of View overriding this method should always call super.onFocusLost(). 7332 * 7333 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7334 * @see #onWindowFocusChanged(boolean) 7335 * 7336 * @hide pending API council approval 7337 */ 7338 @CallSuper 7339 protected void onFocusLost() { 7340 resetPressedState(); 7341 } 7342 7343 private void resetPressedState() { 7344 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7345 return; 7346 } 7347 7348 if (isPressed()) { 7349 setPressed(false); 7350 7351 if (!mHasPerformedLongPress) { 7352 removeLongPressCallback(); 7353 } 7354 } 7355 } 7356 7357 /** 7358 * Returns true if this view has focus 7359 * 7360 * @return True if this view has focus, false otherwise. 7361 */ 7362 @ViewDebug.ExportedProperty(category = "focus") 7363 public boolean isFocused() { 7364 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7365 } 7366 7367 /** 7368 * Find the view in the hierarchy rooted at this view that currently has 7369 * focus. 7370 * 7371 * @return The view that currently has focus, or null if no focused view can 7372 * be found. 7373 */ 7374 public View findFocus() { 7375 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7376 } 7377 7378 /** 7379 * Indicates whether this view is one of the set of scrollable containers in 7380 * its window. 7381 * 7382 * @return whether this view is one of the set of scrollable containers in 7383 * its window 7384 * 7385 * @attr ref android.R.styleable#View_isScrollContainer 7386 */ 7387 public boolean isScrollContainer() { 7388 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7389 } 7390 7391 /** 7392 * Change whether this view is one of the set of scrollable containers in 7393 * its window. This will be used to determine whether the window can 7394 * resize or must pan when a soft input area is open -- scrollable 7395 * containers allow the window to use resize mode since the container 7396 * will appropriately shrink. 7397 * 7398 * @attr ref android.R.styleable#View_isScrollContainer 7399 */ 7400 public void setScrollContainer(boolean isScrollContainer) { 7401 if (isScrollContainer) { 7402 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7403 mAttachInfo.mScrollContainers.add(this); 7404 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7405 } 7406 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7407 } else { 7408 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7409 mAttachInfo.mScrollContainers.remove(this); 7410 } 7411 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7412 } 7413 } 7414 7415 /** 7416 * Returns the quality of the drawing cache. 7417 * 7418 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7419 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7420 * 7421 * @see #setDrawingCacheQuality(int) 7422 * @see #setDrawingCacheEnabled(boolean) 7423 * @see #isDrawingCacheEnabled() 7424 * 7425 * @attr ref android.R.styleable#View_drawingCacheQuality 7426 */ 7427 @DrawingCacheQuality 7428 public int getDrawingCacheQuality() { 7429 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7430 } 7431 7432 /** 7433 * Set the drawing cache quality of this view. This value is used only when the 7434 * drawing cache is enabled 7435 * 7436 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7437 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7438 * 7439 * @see #getDrawingCacheQuality() 7440 * @see #setDrawingCacheEnabled(boolean) 7441 * @see #isDrawingCacheEnabled() 7442 * 7443 * @attr ref android.R.styleable#View_drawingCacheQuality 7444 */ 7445 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7446 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7447 } 7448 7449 /** 7450 * Returns whether the screen should remain on, corresponding to the current 7451 * value of {@link #KEEP_SCREEN_ON}. 7452 * 7453 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7454 * 7455 * @see #setKeepScreenOn(boolean) 7456 * 7457 * @attr ref android.R.styleable#View_keepScreenOn 7458 */ 7459 public boolean getKeepScreenOn() { 7460 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7461 } 7462 7463 /** 7464 * Controls whether the screen should remain on, modifying the 7465 * value of {@link #KEEP_SCREEN_ON}. 7466 * 7467 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7468 * 7469 * @see #getKeepScreenOn() 7470 * 7471 * @attr ref android.R.styleable#View_keepScreenOn 7472 */ 7473 public void setKeepScreenOn(boolean keepScreenOn) { 7474 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7475 } 7476 7477 /** 7478 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7479 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7480 * 7481 * @attr ref android.R.styleable#View_nextFocusLeft 7482 */ 7483 public int getNextFocusLeftId() { 7484 return mNextFocusLeftId; 7485 } 7486 7487 /** 7488 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7489 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7490 * decide automatically. 7491 * 7492 * @attr ref android.R.styleable#View_nextFocusLeft 7493 */ 7494 public void setNextFocusLeftId(int nextFocusLeftId) { 7495 mNextFocusLeftId = nextFocusLeftId; 7496 } 7497 7498 /** 7499 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7500 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7501 * 7502 * @attr ref android.R.styleable#View_nextFocusRight 7503 */ 7504 public int getNextFocusRightId() { 7505 return mNextFocusRightId; 7506 } 7507 7508 /** 7509 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7510 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7511 * decide automatically. 7512 * 7513 * @attr ref android.R.styleable#View_nextFocusRight 7514 */ 7515 public void setNextFocusRightId(int nextFocusRightId) { 7516 mNextFocusRightId = nextFocusRightId; 7517 } 7518 7519 /** 7520 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7521 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7522 * 7523 * @attr ref android.R.styleable#View_nextFocusUp 7524 */ 7525 public int getNextFocusUpId() { 7526 return mNextFocusUpId; 7527 } 7528 7529 /** 7530 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7531 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7532 * decide automatically. 7533 * 7534 * @attr ref android.R.styleable#View_nextFocusUp 7535 */ 7536 public void setNextFocusUpId(int nextFocusUpId) { 7537 mNextFocusUpId = nextFocusUpId; 7538 } 7539 7540 /** 7541 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7542 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7543 * 7544 * @attr ref android.R.styleable#View_nextFocusDown 7545 */ 7546 public int getNextFocusDownId() { 7547 return mNextFocusDownId; 7548 } 7549 7550 /** 7551 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7552 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7553 * decide automatically. 7554 * 7555 * @attr ref android.R.styleable#View_nextFocusDown 7556 */ 7557 public void setNextFocusDownId(int nextFocusDownId) { 7558 mNextFocusDownId = nextFocusDownId; 7559 } 7560 7561 /** 7562 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7563 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7564 * 7565 * @attr ref android.R.styleable#View_nextFocusForward 7566 */ 7567 public int getNextFocusForwardId() { 7568 return mNextFocusForwardId; 7569 } 7570 7571 /** 7572 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7573 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7574 * decide automatically. 7575 * 7576 * @attr ref android.R.styleable#View_nextFocusForward 7577 */ 7578 public void setNextFocusForwardId(int nextFocusForwardId) { 7579 mNextFocusForwardId = nextFocusForwardId; 7580 } 7581 7582 /** 7583 * Returns the visibility of this view and all of its ancestors 7584 * 7585 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7586 */ 7587 public boolean isShown() { 7588 View current = this; 7589 //noinspection ConstantConditions 7590 do { 7591 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7592 return false; 7593 } 7594 ViewParent parent = current.mParent; 7595 if (parent == null) { 7596 return false; // We are not attached to the view root 7597 } 7598 if (!(parent instanceof View)) { 7599 return true; 7600 } 7601 current = (View) parent; 7602 } while (current != null); 7603 7604 return false; 7605 } 7606 7607 /** 7608 * Called by the view hierarchy when the content insets for a window have 7609 * changed, to allow it to adjust its content to fit within those windows. 7610 * The content insets tell you the space that the status bar, input method, 7611 * and other system windows infringe on the application's window. 7612 * 7613 * <p>You do not normally need to deal with this function, since the default 7614 * window decoration given to applications takes care of applying it to the 7615 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7616 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7617 * and your content can be placed under those system elements. You can then 7618 * use this method within your view hierarchy if you have parts of your UI 7619 * which you would like to ensure are not being covered. 7620 * 7621 * <p>The default implementation of this method simply applies the content 7622 * insets to the view's padding, consuming that content (modifying the 7623 * insets to be 0), and returning true. This behavior is off by default, but can 7624 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7625 * 7626 * <p>This function's traversal down the hierarchy is depth-first. The same content 7627 * insets object is propagated down the hierarchy, so any changes made to it will 7628 * be seen by all following views (including potentially ones above in 7629 * the hierarchy since this is a depth-first traversal). The first view 7630 * that returns true will abort the entire traversal. 7631 * 7632 * <p>The default implementation works well for a situation where it is 7633 * used with a container that covers the entire window, allowing it to 7634 * apply the appropriate insets to its content on all edges. If you need 7635 * a more complicated layout (such as two different views fitting system 7636 * windows, one on the top of the window, and one on the bottom), 7637 * you can override the method and handle the insets however you would like. 7638 * Note that the insets provided by the framework are always relative to the 7639 * far edges of the window, not accounting for the location of the called view 7640 * within that window. (In fact when this method is called you do not yet know 7641 * where the layout will place the view, as it is done before layout happens.) 7642 * 7643 * <p>Note: unlike many View methods, there is no dispatch phase to this 7644 * call. If you are overriding it in a ViewGroup and want to allow the 7645 * call to continue to your children, you must be sure to call the super 7646 * implementation. 7647 * 7648 * <p>Here is a sample layout that makes use of fitting system windows 7649 * to have controls for a video view placed inside of the window decorations 7650 * that it hides and shows. This can be used with code like the second 7651 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7652 * 7653 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7654 * 7655 * @param insets Current content insets of the window. Prior to 7656 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7657 * the insets or else you and Android will be unhappy. 7658 * 7659 * @return {@code true} if this view applied the insets and it should not 7660 * continue propagating further down the hierarchy, {@code false} otherwise. 7661 * @see #getFitsSystemWindows() 7662 * @see #setFitsSystemWindows(boolean) 7663 * @see #setSystemUiVisibility(int) 7664 * 7665 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7666 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7667 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7668 * to implement handling their own insets. 7669 */ 7670 protected boolean fitSystemWindows(Rect insets) { 7671 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7672 if (insets == null) { 7673 // Null insets by definition have already been consumed. 7674 // This call cannot apply insets since there are none to apply, 7675 // so return false. 7676 return false; 7677 } 7678 // If we're not in the process of dispatching the newer apply insets call, 7679 // that means we're not in the compatibility path. Dispatch into the newer 7680 // apply insets path and take things from there. 7681 try { 7682 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7683 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7684 } finally { 7685 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7686 } 7687 } else { 7688 // We're being called from the newer apply insets path. 7689 // Perform the standard fallback behavior. 7690 return fitSystemWindowsInt(insets); 7691 } 7692 } 7693 7694 private boolean fitSystemWindowsInt(Rect insets) { 7695 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7696 mUserPaddingStart = UNDEFINED_PADDING; 7697 mUserPaddingEnd = UNDEFINED_PADDING; 7698 Rect localInsets = sThreadLocal.get(); 7699 if (localInsets == null) { 7700 localInsets = new Rect(); 7701 sThreadLocal.set(localInsets); 7702 } 7703 boolean res = computeFitSystemWindows(insets, localInsets); 7704 mUserPaddingLeftInitial = localInsets.left; 7705 mUserPaddingRightInitial = localInsets.right; 7706 internalSetPadding(localInsets.left, localInsets.top, 7707 localInsets.right, localInsets.bottom); 7708 return res; 7709 } 7710 return false; 7711 } 7712 7713 /** 7714 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7715 * 7716 * <p>This method should be overridden by views that wish to apply a policy different from or 7717 * in addition to the default behavior. Clients that wish to force a view subtree 7718 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7719 * 7720 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7721 * it will be called during dispatch instead of this method. The listener may optionally 7722 * call this method from its own implementation if it wishes to apply the view's default 7723 * insets policy in addition to its own.</p> 7724 * 7725 * <p>Implementations of this method should either return the insets parameter unchanged 7726 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7727 * that this view applied itself. This allows new inset types added in future platform 7728 * versions to pass through existing implementations unchanged without being erroneously 7729 * consumed.</p> 7730 * 7731 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7732 * property is set then the view will consume the system window insets and apply them 7733 * as padding for the view.</p> 7734 * 7735 * @param insets Insets to apply 7736 * @return The supplied insets with any applied insets consumed 7737 */ 7738 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7739 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7740 // We weren't called from within a direct call to fitSystemWindows, 7741 // call into it as a fallback in case we're in a class that overrides it 7742 // and has logic to perform. 7743 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7744 return insets.consumeSystemWindowInsets(); 7745 } 7746 } else { 7747 // We were called from within a direct call to fitSystemWindows. 7748 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7749 return insets.consumeSystemWindowInsets(); 7750 } 7751 } 7752 return insets; 7753 } 7754 7755 /** 7756 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7757 * window insets to this view. The listener's 7758 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7759 * method will be called instead of the view's 7760 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7761 * 7762 * @param listener Listener to set 7763 * 7764 * @see #onApplyWindowInsets(WindowInsets) 7765 */ 7766 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7767 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7768 } 7769 7770 /** 7771 * Request to apply the given window insets to this view or another view in its subtree. 7772 * 7773 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7774 * obscured by window decorations or overlays. This can include the status and navigation bars, 7775 * action bars, input methods and more. New inset categories may be added in the future. 7776 * The method returns the insets provided minus any that were applied by this view or its 7777 * children.</p> 7778 * 7779 * <p>Clients wishing to provide custom behavior should override the 7780 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7781 * {@link OnApplyWindowInsetsListener} via the 7782 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7783 * method.</p> 7784 * 7785 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7786 * </p> 7787 * 7788 * @param insets Insets to apply 7789 * @return The provided insets minus the insets that were consumed 7790 */ 7791 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7792 try { 7793 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7794 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7795 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7796 } else { 7797 return onApplyWindowInsets(insets); 7798 } 7799 } finally { 7800 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7801 } 7802 } 7803 7804 /** 7805 * Compute the view's coordinate within the surface. 7806 * 7807 * <p>Computes the coordinates of this view in its surface. The argument 7808 * must be an array of two integers. After the method returns, the array 7809 * contains the x and y location in that order.</p> 7810 * @hide 7811 * @param location an array of two integers in which to hold the coordinates 7812 */ 7813 public void getLocationInSurface(@Size(2) int[] location) { 7814 getLocationInWindow(location); 7815 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7816 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7817 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7818 } 7819 } 7820 7821 /** 7822 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7823 * only available if the view is attached. 7824 * 7825 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7826 */ 7827 public WindowInsets getRootWindowInsets() { 7828 if (mAttachInfo != null) { 7829 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7830 } 7831 return null; 7832 } 7833 7834 /** 7835 * @hide Compute the insets that should be consumed by this view and the ones 7836 * that should propagate to those under it. 7837 */ 7838 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7839 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7840 || mAttachInfo == null 7841 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7842 && !mAttachInfo.mOverscanRequested)) { 7843 outLocalInsets.set(inoutInsets); 7844 inoutInsets.set(0, 0, 0, 0); 7845 return true; 7846 } else { 7847 // The application wants to take care of fitting system window for 7848 // the content... however we still need to take care of any overscan here. 7849 final Rect overscan = mAttachInfo.mOverscanInsets; 7850 outLocalInsets.set(overscan); 7851 inoutInsets.left -= overscan.left; 7852 inoutInsets.top -= overscan.top; 7853 inoutInsets.right -= overscan.right; 7854 inoutInsets.bottom -= overscan.bottom; 7855 return false; 7856 } 7857 } 7858 7859 /** 7860 * Compute insets that should be consumed by this view and the ones that should propagate 7861 * to those under it. 7862 * 7863 * @param in Insets currently being processed by this View, likely received as a parameter 7864 * to {@link #onApplyWindowInsets(WindowInsets)}. 7865 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7866 * by this view 7867 * @return Insets that should be passed along to views under this one 7868 */ 7869 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7870 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7871 || mAttachInfo == null 7872 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7873 outLocalInsets.set(in.getSystemWindowInsets()); 7874 return in.consumeSystemWindowInsets(); 7875 } else { 7876 outLocalInsets.set(0, 0, 0, 0); 7877 return in; 7878 } 7879 } 7880 7881 /** 7882 * Sets whether or not this view should account for system screen decorations 7883 * such as the status bar and inset its content; that is, controlling whether 7884 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7885 * executed. See that method for more details. 7886 * 7887 * <p>Note that if you are providing your own implementation of 7888 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7889 * flag to true -- your implementation will be overriding the default 7890 * implementation that checks this flag. 7891 * 7892 * @param fitSystemWindows If true, then the default implementation of 7893 * {@link #fitSystemWindows(Rect)} will be executed. 7894 * 7895 * @attr ref android.R.styleable#View_fitsSystemWindows 7896 * @see #getFitsSystemWindows() 7897 * @see #fitSystemWindows(Rect) 7898 * @see #setSystemUiVisibility(int) 7899 */ 7900 public void setFitsSystemWindows(boolean fitSystemWindows) { 7901 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7902 } 7903 7904 /** 7905 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7906 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7907 * will be executed. 7908 * 7909 * @return {@code true} if the default implementation of 7910 * {@link #fitSystemWindows(Rect)} will be executed. 7911 * 7912 * @attr ref android.R.styleable#View_fitsSystemWindows 7913 * @see #setFitsSystemWindows(boolean) 7914 * @see #fitSystemWindows(Rect) 7915 * @see #setSystemUiVisibility(int) 7916 */ 7917 @ViewDebug.ExportedProperty 7918 public boolean getFitsSystemWindows() { 7919 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7920 } 7921 7922 /** @hide */ 7923 public boolean fitsSystemWindows() { 7924 return getFitsSystemWindows(); 7925 } 7926 7927 /** 7928 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7929 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7930 */ 7931 public void requestFitSystemWindows() { 7932 if (mParent != null) { 7933 mParent.requestFitSystemWindows(); 7934 } 7935 } 7936 7937 /** 7938 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7939 */ 7940 public void requestApplyInsets() { 7941 requestFitSystemWindows(); 7942 } 7943 7944 /** 7945 * For use by PhoneWindow to make its own system window fitting optional. 7946 * @hide 7947 */ 7948 public void makeOptionalFitsSystemWindows() { 7949 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7950 } 7951 7952 /** 7953 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7954 * treat them as such. 7955 * @hide 7956 */ 7957 public void getOutsets(Rect outOutsetRect) { 7958 if (mAttachInfo != null) { 7959 outOutsetRect.set(mAttachInfo.mOutsets); 7960 } else { 7961 outOutsetRect.setEmpty(); 7962 } 7963 } 7964 7965 /** 7966 * Returns the visibility status for this view. 7967 * 7968 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7969 * @attr ref android.R.styleable#View_visibility 7970 */ 7971 @ViewDebug.ExportedProperty(mapping = { 7972 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7973 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7974 @ViewDebug.IntToString(from = GONE, to = "GONE") 7975 }) 7976 @Visibility 7977 public int getVisibility() { 7978 return mViewFlags & VISIBILITY_MASK; 7979 } 7980 7981 /** 7982 * Set the enabled state of this view. 7983 * 7984 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7985 * @attr ref android.R.styleable#View_visibility 7986 */ 7987 @RemotableViewMethod 7988 public void setVisibility(@Visibility int visibility) { 7989 setFlags(visibility, VISIBILITY_MASK); 7990 } 7991 7992 /** 7993 * Returns the enabled status for this view. The interpretation of the 7994 * enabled state varies by subclass. 7995 * 7996 * @return True if this view is enabled, false otherwise. 7997 */ 7998 @ViewDebug.ExportedProperty 7999 public boolean isEnabled() { 8000 return (mViewFlags & ENABLED_MASK) == ENABLED; 8001 } 8002 8003 /** 8004 * Set the enabled state of this view. The interpretation of the enabled 8005 * state varies by subclass. 8006 * 8007 * @param enabled True if this view is enabled, false otherwise. 8008 */ 8009 @RemotableViewMethod 8010 public void setEnabled(boolean enabled) { 8011 if (enabled == isEnabled()) return; 8012 8013 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8014 8015 /* 8016 * The View most likely has to change its appearance, so refresh 8017 * the drawable state. 8018 */ 8019 refreshDrawableState(); 8020 8021 // Invalidate too, since the default behavior for views is to be 8022 // be drawn at 50% alpha rather than to change the drawable. 8023 invalidate(true); 8024 8025 if (!enabled) { 8026 cancelPendingInputEvents(); 8027 } 8028 } 8029 8030 /** 8031 * Set whether this view can receive the focus. 8032 * 8033 * Setting this to false will also ensure that this view is not focusable 8034 * in touch mode. 8035 * 8036 * @param focusable If true, this view can receive the focus. 8037 * 8038 * @see #setFocusableInTouchMode(boolean) 8039 * @attr ref android.R.styleable#View_focusable 8040 */ 8041 public void setFocusable(boolean focusable) { 8042 if (!focusable) { 8043 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8044 } 8045 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8046 } 8047 8048 /** 8049 * Set whether this view can receive focus while in touch mode. 8050 * 8051 * Setting this to true will also ensure that this view is focusable. 8052 * 8053 * @param focusableInTouchMode If true, this view can receive the focus while 8054 * in touch mode. 8055 * 8056 * @see #setFocusable(boolean) 8057 * @attr ref android.R.styleable#View_focusableInTouchMode 8058 */ 8059 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8060 // Focusable in touch mode should always be set before the focusable flag 8061 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8062 // which, in touch mode, will not successfully request focus on this view 8063 // because the focusable in touch mode flag is not set 8064 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8065 if (focusableInTouchMode) { 8066 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8067 } 8068 } 8069 8070 /** 8071 * Set whether this view should have sound effects enabled for events such as 8072 * clicking and touching. 8073 * 8074 * <p>You may wish to disable sound effects for a view if you already play sounds, 8075 * for instance, a dial key that plays dtmf tones. 8076 * 8077 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8078 * @see #isSoundEffectsEnabled() 8079 * @see #playSoundEffect(int) 8080 * @attr ref android.R.styleable#View_soundEffectsEnabled 8081 */ 8082 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8083 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8084 } 8085 8086 /** 8087 * @return whether this view should have sound effects enabled for events such as 8088 * clicking and touching. 8089 * 8090 * @see #setSoundEffectsEnabled(boolean) 8091 * @see #playSoundEffect(int) 8092 * @attr ref android.R.styleable#View_soundEffectsEnabled 8093 */ 8094 @ViewDebug.ExportedProperty 8095 public boolean isSoundEffectsEnabled() { 8096 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8097 } 8098 8099 /** 8100 * Set whether this view should have haptic feedback for events such as 8101 * long presses. 8102 * 8103 * <p>You may wish to disable haptic feedback if your view already controls 8104 * its own haptic feedback. 8105 * 8106 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8107 * @see #isHapticFeedbackEnabled() 8108 * @see #performHapticFeedback(int) 8109 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8110 */ 8111 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8112 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8113 } 8114 8115 /** 8116 * @return whether this view should have haptic feedback enabled for events 8117 * long presses. 8118 * 8119 * @see #setHapticFeedbackEnabled(boolean) 8120 * @see #performHapticFeedback(int) 8121 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8122 */ 8123 @ViewDebug.ExportedProperty 8124 public boolean isHapticFeedbackEnabled() { 8125 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8126 } 8127 8128 /** 8129 * Returns the layout direction for this view. 8130 * 8131 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8132 * {@link #LAYOUT_DIRECTION_RTL}, 8133 * {@link #LAYOUT_DIRECTION_INHERIT} or 8134 * {@link #LAYOUT_DIRECTION_LOCALE}. 8135 * 8136 * @attr ref android.R.styleable#View_layoutDirection 8137 * 8138 * @hide 8139 */ 8140 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8141 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8142 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8143 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8144 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8145 }) 8146 @LayoutDir 8147 public int getRawLayoutDirection() { 8148 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8149 } 8150 8151 /** 8152 * Set the layout direction for this view. This will propagate a reset of layout direction 8153 * resolution to the view's children and resolve layout direction for this view. 8154 * 8155 * @param layoutDirection the layout direction to set. Should be one of: 8156 * 8157 * {@link #LAYOUT_DIRECTION_LTR}, 8158 * {@link #LAYOUT_DIRECTION_RTL}, 8159 * {@link #LAYOUT_DIRECTION_INHERIT}, 8160 * {@link #LAYOUT_DIRECTION_LOCALE}. 8161 * 8162 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8163 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8164 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8165 * 8166 * @attr ref android.R.styleable#View_layoutDirection 8167 */ 8168 @RemotableViewMethod 8169 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8170 if (getRawLayoutDirection() != layoutDirection) { 8171 // Reset the current layout direction and the resolved one 8172 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8173 resetRtlProperties(); 8174 // Set the new layout direction (filtered) 8175 mPrivateFlags2 |= 8176 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8177 // We need to resolve all RTL properties as they all depend on layout direction 8178 resolveRtlPropertiesIfNeeded(); 8179 requestLayout(); 8180 invalidate(true); 8181 } 8182 } 8183 8184 /** 8185 * Returns the resolved layout direction for this view. 8186 * 8187 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8188 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8189 * 8190 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8191 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8192 * 8193 * @attr ref android.R.styleable#View_layoutDirection 8194 */ 8195 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8196 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8197 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8198 }) 8199 @ResolvedLayoutDir 8200 public int getLayoutDirection() { 8201 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8202 if (targetSdkVersion < JELLY_BEAN_MR1) { 8203 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8204 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8205 } 8206 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8207 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8208 } 8209 8210 /** 8211 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8212 * layout attribute and/or the inherited value from the parent 8213 * 8214 * @return true if the layout is right-to-left. 8215 * 8216 * @hide 8217 */ 8218 @ViewDebug.ExportedProperty(category = "layout") 8219 public boolean isLayoutRtl() { 8220 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8221 } 8222 8223 /** 8224 * Indicates whether the view is currently tracking transient state that the 8225 * app should not need to concern itself with saving and restoring, but that 8226 * the framework should take special note to preserve when possible. 8227 * 8228 * <p>A view with transient state cannot be trivially rebound from an external 8229 * data source, such as an adapter binding item views in a list. This may be 8230 * because the view is performing an animation, tracking user selection 8231 * of content, or similar.</p> 8232 * 8233 * @return true if the view has transient state 8234 */ 8235 @ViewDebug.ExportedProperty(category = "layout") 8236 public boolean hasTransientState() { 8237 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8238 } 8239 8240 /** 8241 * Set whether this view is currently tracking transient state that the 8242 * framework should attempt to preserve when possible. This flag is reference counted, 8243 * so every call to setHasTransientState(true) should be paired with a later call 8244 * to setHasTransientState(false). 8245 * 8246 * <p>A view with transient state cannot be trivially rebound from an external 8247 * data source, such as an adapter binding item views in a list. This may be 8248 * because the view is performing an animation, tracking user selection 8249 * of content, or similar.</p> 8250 * 8251 * @param hasTransientState true if this view has transient state 8252 */ 8253 public void setHasTransientState(boolean hasTransientState) { 8254 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8255 mTransientStateCount - 1; 8256 if (mTransientStateCount < 0) { 8257 mTransientStateCount = 0; 8258 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8259 "unmatched pair of setHasTransientState calls"); 8260 } else if ((hasTransientState && mTransientStateCount == 1) || 8261 (!hasTransientState && mTransientStateCount == 0)) { 8262 // update flag if we've just incremented up from 0 or decremented down to 0 8263 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8264 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8265 if (mParent != null) { 8266 try { 8267 mParent.childHasTransientStateChanged(this, hasTransientState); 8268 } catch (AbstractMethodError e) { 8269 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8270 " does not fully implement ViewParent", e); 8271 } 8272 } 8273 } 8274 } 8275 8276 /** 8277 * Returns true if this view is currently attached to a window. 8278 */ 8279 public boolean isAttachedToWindow() { 8280 return mAttachInfo != null; 8281 } 8282 8283 /** 8284 * Returns true if this view has been through at least one layout since it 8285 * was last attached to or detached from a window. 8286 */ 8287 public boolean isLaidOut() { 8288 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8289 } 8290 8291 /** 8292 * If this view doesn't do any drawing on its own, set this flag to 8293 * allow further optimizations. By default, this flag is not set on 8294 * View, but could be set on some View subclasses such as ViewGroup. 8295 * 8296 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8297 * you should clear this flag. 8298 * 8299 * @param willNotDraw whether or not this View draw on its own 8300 */ 8301 public void setWillNotDraw(boolean willNotDraw) { 8302 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8303 } 8304 8305 /** 8306 * Returns whether or not this View draws on its own. 8307 * 8308 * @return true if this view has nothing to draw, false otherwise 8309 */ 8310 @ViewDebug.ExportedProperty(category = "drawing") 8311 public boolean willNotDraw() { 8312 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8313 } 8314 8315 /** 8316 * When a View's drawing cache is enabled, drawing is redirected to an 8317 * offscreen bitmap. Some views, like an ImageView, must be able to 8318 * bypass this mechanism if they already draw a single bitmap, to avoid 8319 * unnecessary usage of the memory. 8320 * 8321 * @param willNotCacheDrawing true if this view does not cache its 8322 * drawing, false otherwise 8323 */ 8324 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8325 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8326 } 8327 8328 /** 8329 * Returns whether or not this View can cache its drawing or not. 8330 * 8331 * @return true if this view does not cache its drawing, false otherwise 8332 */ 8333 @ViewDebug.ExportedProperty(category = "drawing") 8334 public boolean willNotCacheDrawing() { 8335 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8336 } 8337 8338 /** 8339 * Indicates whether this view reacts to click events or not. 8340 * 8341 * @return true if the view is clickable, false otherwise 8342 * 8343 * @see #setClickable(boolean) 8344 * @attr ref android.R.styleable#View_clickable 8345 */ 8346 @ViewDebug.ExportedProperty 8347 public boolean isClickable() { 8348 return (mViewFlags & CLICKABLE) == CLICKABLE; 8349 } 8350 8351 /** 8352 * Enables or disables click events for this view. When a view 8353 * is clickable it will change its state to "pressed" on every click. 8354 * Subclasses should set the view clickable to visually react to 8355 * user's clicks. 8356 * 8357 * @param clickable true to make the view clickable, false otherwise 8358 * 8359 * @see #isClickable() 8360 * @attr ref android.R.styleable#View_clickable 8361 */ 8362 public void setClickable(boolean clickable) { 8363 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8364 } 8365 8366 /** 8367 * Indicates whether this view reacts to long click events or not. 8368 * 8369 * @return true if the view is long clickable, false otherwise 8370 * 8371 * @see #setLongClickable(boolean) 8372 * @attr ref android.R.styleable#View_longClickable 8373 */ 8374 public boolean isLongClickable() { 8375 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8376 } 8377 8378 /** 8379 * Enables or disables long click events for this view. When a view is long 8380 * clickable it reacts to the user holding down the button for a longer 8381 * duration than a tap. This event can either launch the listener or a 8382 * context menu. 8383 * 8384 * @param longClickable true to make the view long clickable, false otherwise 8385 * @see #isLongClickable() 8386 * @attr ref android.R.styleable#View_longClickable 8387 */ 8388 public void setLongClickable(boolean longClickable) { 8389 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8390 } 8391 8392 /** 8393 * Indicates whether this view reacts to context clicks or not. 8394 * 8395 * @return true if the view is context clickable, false otherwise 8396 * @see #setContextClickable(boolean) 8397 * @attr ref android.R.styleable#View_contextClickable 8398 */ 8399 public boolean isContextClickable() { 8400 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8401 } 8402 8403 /** 8404 * Enables or disables context clicking for this view. This event can launch the listener. 8405 * 8406 * @param contextClickable true to make the view react to a context click, false otherwise 8407 * @see #isContextClickable() 8408 * @attr ref android.R.styleable#View_contextClickable 8409 */ 8410 public void setContextClickable(boolean contextClickable) { 8411 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8412 } 8413 8414 /** 8415 * Sets the pressed state for this view and provides a touch coordinate for 8416 * animation hinting. 8417 * 8418 * @param pressed Pass true to set the View's internal state to "pressed", 8419 * or false to reverts the View's internal state from a 8420 * previously set "pressed" state. 8421 * @param x The x coordinate of the touch that caused the press 8422 * @param y The y coordinate of the touch that caused the press 8423 */ 8424 private void setPressed(boolean pressed, float x, float y) { 8425 if (pressed) { 8426 drawableHotspotChanged(x, y); 8427 } 8428 8429 setPressed(pressed); 8430 } 8431 8432 /** 8433 * Sets the pressed state for this view. 8434 * 8435 * @see #isClickable() 8436 * @see #setClickable(boolean) 8437 * 8438 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8439 * the View's internal state from a previously set "pressed" state. 8440 */ 8441 public void setPressed(boolean pressed) { 8442 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8443 8444 if (pressed) { 8445 mPrivateFlags |= PFLAG_PRESSED; 8446 } else { 8447 mPrivateFlags &= ~PFLAG_PRESSED; 8448 } 8449 8450 if (needsRefresh) { 8451 refreshDrawableState(); 8452 } 8453 dispatchSetPressed(pressed); 8454 } 8455 8456 /** 8457 * Dispatch setPressed to all of this View's children. 8458 * 8459 * @see #setPressed(boolean) 8460 * 8461 * @param pressed The new pressed state 8462 */ 8463 protected void dispatchSetPressed(boolean pressed) { 8464 } 8465 8466 /** 8467 * Indicates whether the view is currently in pressed state. Unless 8468 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8469 * the pressed state. 8470 * 8471 * @see #setPressed(boolean) 8472 * @see #isClickable() 8473 * @see #setClickable(boolean) 8474 * 8475 * @return true if the view is currently pressed, false otherwise 8476 */ 8477 @ViewDebug.ExportedProperty 8478 public boolean isPressed() { 8479 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8480 } 8481 8482 /** 8483 * @hide 8484 * Indicates whether this view will participate in data collection through 8485 * {@link ViewStructure}. If true, it will not provide any data 8486 * for itself or its children. If false, the normal data collection will be allowed. 8487 * 8488 * @return Returns false if assist data collection is not blocked, else true. 8489 * 8490 * @see #setAssistBlocked(boolean) 8491 * @attr ref android.R.styleable#View_assistBlocked 8492 */ 8493 public boolean isAssistBlocked() { 8494 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8495 } 8496 8497 /** 8498 * @hide 8499 * Controls whether assist data collection from this view and its children is enabled 8500 * (that is, whether {@link #onProvideStructure} and 8501 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8502 * allowing normal assist collection. Setting this to false will disable assist collection. 8503 * 8504 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8505 * (the default) to allow it. 8506 * 8507 * @see #isAssistBlocked() 8508 * @see #onProvideStructure 8509 * @see #onProvideVirtualStructure 8510 * @attr ref android.R.styleable#View_assistBlocked 8511 */ 8512 public void setAssistBlocked(boolean enabled) { 8513 if (enabled) { 8514 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8515 } else { 8516 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8517 } 8518 } 8519 8520 /** 8521 * Indicates whether this view will save its state (that is, 8522 * whether its {@link #onSaveInstanceState} method will be called). 8523 * 8524 * @return Returns true if the view state saving is enabled, else false. 8525 * 8526 * @see #setSaveEnabled(boolean) 8527 * @attr ref android.R.styleable#View_saveEnabled 8528 */ 8529 public boolean isSaveEnabled() { 8530 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8531 } 8532 8533 /** 8534 * Controls whether the saving of this view's state is 8535 * enabled (that is, whether its {@link #onSaveInstanceState} method 8536 * will be called). Note that even if freezing is enabled, the 8537 * view still must have an id assigned to it (via {@link #setId(int)}) 8538 * for its state to be saved. This flag can only disable the 8539 * saving of this view; any child views may still have their state saved. 8540 * 8541 * @param enabled Set to false to <em>disable</em> state saving, or true 8542 * (the default) to allow it. 8543 * 8544 * @see #isSaveEnabled() 8545 * @see #setId(int) 8546 * @see #onSaveInstanceState() 8547 * @attr ref android.R.styleable#View_saveEnabled 8548 */ 8549 public void setSaveEnabled(boolean enabled) { 8550 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8551 } 8552 8553 /** 8554 * Gets whether the framework should discard touches when the view's 8555 * window is obscured by another visible window. 8556 * Refer to the {@link View} security documentation for more details. 8557 * 8558 * @return True if touch filtering is enabled. 8559 * 8560 * @see #setFilterTouchesWhenObscured(boolean) 8561 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8562 */ 8563 @ViewDebug.ExportedProperty 8564 public boolean getFilterTouchesWhenObscured() { 8565 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8566 } 8567 8568 /** 8569 * Sets whether the framework should discard touches when the view's 8570 * window is obscured by another visible window. 8571 * Refer to the {@link View} security documentation for more details. 8572 * 8573 * @param enabled True if touch filtering should be enabled. 8574 * 8575 * @see #getFilterTouchesWhenObscured 8576 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8577 */ 8578 public void setFilterTouchesWhenObscured(boolean enabled) { 8579 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8580 FILTER_TOUCHES_WHEN_OBSCURED); 8581 } 8582 8583 /** 8584 * Indicates whether the entire hierarchy under this view will save its 8585 * state when a state saving traversal occurs from its parent. The default 8586 * is true; if false, these views will not be saved unless 8587 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8588 * 8589 * @return Returns true if the view state saving from parent is enabled, else false. 8590 * 8591 * @see #setSaveFromParentEnabled(boolean) 8592 */ 8593 public boolean isSaveFromParentEnabled() { 8594 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8595 } 8596 8597 /** 8598 * Controls whether the entire hierarchy under this view will save its 8599 * state when a state saving traversal occurs from its parent. The default 8600 * is true; if false, these views will not be saved unless 8601 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8602 * 8603 * @param enabled Set to false to <em>disable</em> state saving, or true 8604 * (the default) to allow it. 8605 * 8606 * @see #isSaveFromParentEnabled() 8607 * @see #setId(int) 8608 * @see #onSaveInstanceState() 8609 */ 8610 public void setSaveFromParentEnabled(boolean enabled) { 8611 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8612 } 8613 8614 8615 /** 8616 * Returns whether this View is able to take focus. 8617 * 8618 * @return True if this view can take focus, or false otherwise. 8619 * @attr ref android.R.styleable#View_focusable 8620 */ 8621 @ViewDebug.ExportedProperty(category = "focus") 8622 public final boolean isFocusable() { 8623 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8624 } 8625 8626 /** 8627 * When a view is focusable, it may not want to take focus when in touch mode. 8628 * For example, a button would like focus when the user is navigating via a D-pad 8629 * so that the user can click on it, but once the user starts touching the screen, 8630 * the button shouldn't take focus 8631 * @return Whether the view is focusable in touch mode. 8632 * @attr ref android.R.styleable#View_focusableInTouchMode 8633 */ 8634 @ViewDebug.ExportedProperty 8635 public final boolean isFocusableInTouchMode() { 8636 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8637 } 8638 8639 /** 8640 * Find the nearest view in the specified direction that can take focus. 8641 * This does not actually give focus to that view. 8642 * 8643 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8644 * 8645 * @return The nearest focusable in the specified direction, or null if none 8646 * can be found. 8647 */ 8648 public View focusSearch(@FocusRealDirection int direction) { 8649 if (mParent != null) { 8650 return mParent.focusSearch(this, direction); 8651 } else { 8652 return null; 8653 } 8654 } 8655 8656 /** 8657 * This method is the last chance for the focused view and its ancestors to 8658 * respond to an arrow key. This is called when the focused view did not 8659 * consume the key internally, nor could the view system find a new view in 8660 * the requested direction to give focus to. 8661 * 8662 * @param focused The currently focused view. 8663 * @param direction The direction focus wants to move. One of FOCUS_UP, 8664 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8665 * @return True if the this view consumed this unhandled move. 8666 */ 8667 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8668 return false; 8669 } 8670 8671 /** 8672 * If a user manually specified the next view id for a particular direction, 8673 * use the root to look up the view. 8674 * @param root The root view of the hierarchy containing this view. 8675 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8676 * or FOCUS_BACKWARD. 8677 * @return The user specified next view, or null if there is none. 8678 */ 8679 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8680 switch (direction) { 8681 case FOCUS_LEFT: 8682 if (mNextFocusLeftId == View.NO_ID) return null; 8683 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8684 case FOCUS_RIGHT: 8685 if (mNextFocusRightId == View.NO_ID) return null; 8686 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8687 case FOCUS_UP: 8688 if (mNextFocusUpId == View.NO_ID) return null; 8689 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8690 case FOCUS_DOWN: 8691 if (mNextFocusDownId == View.NO_ID) return null; 8692 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8693 case FOCUS_FORWARD: 8694 if (mNextFocusForwardId == View.NO_ID) return null; 8695 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8696 case FOCUS_BACKWARD: { 8697 if (mID == View.NO_ID) return null; 8698 final int id = mID; 8699 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8700 @Override 8701 public boolean apply(View t) { 8702 return t.mNextFocusForwardId == id; 8703 } 8704 }); 8705 } 8706 } 8707 return null; 8708 } 8709 8710 private View findViewInsideOutShouldExist(View root, int id) { 8711 if (mMatchIdPredicate == null) { 8712 mMatchIdPredicate = new MatchIdPredicate(); 8713 } 8714 mMatchIdPredicate.mId = id; 8715 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8716 if (result == null) { 8717 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8718 } 8719 return result; 8720 } 8721 8722 /** 8723 * Find and return all focusable views that are descendants of this view, 8724 * possibly including this view if it is focusable itself. 8725 * 8726 * @param direction The direction of the focus 8727 * @return A list of focusable views 8728 */ 8729 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8730 ArrayList<View> result = new ArrayList<View>(24); 8731 addFocusables(result, direction); 8732 return result; 8733 } 8734 8735 /** 8736 * Add any focusable views that are descendants of this view (possibly 8737 * including this view if it is focusable itself) to views. If we are in touch mode, 8738 * only add views that are also focusable in touch mode. 8739 * 8740 * @param views Focusable views found so far 8741 * @param direction The direction of the focus 8742 */ 8743 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8744 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8745 } 8746 8747 /** 8748 * Adds any focusable views that are descendants of this view (possibly 8749 * including this view if it is focusable itself) to views. This method 8750 * adds all focusable views regardless if we are in touch mode or 8751 * only views focusable in touch mode if we are in touch mode or 8752 * only views that can take accessibility focus if accessibility is enabled 8753 * depending on the focusable mode parameter. 8754 * 8755 * @param views Focusable views found so far or null if all we are interested is 8756 * the number of focusables. 8757 * @param direction The direction of the focus. 8758 * @param focusableMode The type of focusables to be added. 8759 * 8760 * @see #FOCUSABLES_ALL 8761 * @see #FOCUSABLES_TOUCH_MODE 8762 */ 8763 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8764 @FocusableMode int focusableMode) { 8765 if (views == null) { 8766 return; 8767 } 8768 if (!isFocusable()) { 8769 return; 8770 } 8771 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8772 && isInTouchMode() && !isFocusableInTouchMode()) { 8773 return; 8774 } 8775 views.add(this); 8776 } 8777 8778 /** 8779 * Finds the Views that contain given text. The containment is case insensitive. 8780 * The search is performed by either the text that the View renders or the content 8781 * description that describes the view for accessibility purposes and the view does 8782 * not render or both. Clients can specify how the search is to be performed via 8783 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8784 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8785 * 8786 * @param outViews The output list of matching Views. 8787 * @param searched The text to match against. 8788 * 8789 * @see #FIND_VIEWS_WITH_TEXT 8790 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8791 * @see #setContentDescription(CharSequence) 8792 */ 8793 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8794 @FindViewFlags int flags) { 8795 if (getAccessibilityNodeProvider() != null) { 8796 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8797 outViews.add(this); 8798 } 8799 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8800 && (searched != null && searched.length() > 0) 8801 && (mContentDescription != null && mContentDescription.length() > 0)) { 8802 String searchedLowerCase = searched.toString().toLowerCase(); 8803 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8804 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8805 outViews.add(this); 8806 } 8807 } 8808 } 8809 8810 /** 8811 * Find and return all touchable views that are descendants of this view, 8812 * possibly including this view if it is touchable itself. 8813 * 8814 * @return A list of touchable views 8815 */ 8816 public ArrayList<View> getTouchables() { 8817 ArrayList<View> result = new ArrayList<View>(); 8818 addTouchables(result); 8819 return result; 8820 } 8821 8822 /** 8823 * Add any touchable views that are descendants of this view (possibly 8824 * including this view if it is touchable itself) to views. 8825 * 8826 * @param views Touchable views found so far 8827 */ 8828 public void addTouchables(ArrayList<View> views) { 8829 final int viewFlags = mViewFlags; 8830 8831 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8832 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8833 && (viewFlags & ENABLED_MASK) == ENABLED) { 8834 views.add(this); 8835 } 8836 } 8837 8838 /** 8839 * Returns whether this View is accessibility focused. 8840 * 8841 * @return True if this View is accessibility focused. 8842 */ 8843 public boolean isAccessibilityFocused() { 8844 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8845 } 8846 8847 /** 8848 * Call this to try to give accessibility focus to this view. 8849 * 8850 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8851 * returns false or the view is no visible or the view already has accessibility 8852 * focus. 8853 * 8854 * See also {@link #focusSearch(int)}, which is what you call to say that you 8855 * have focus, and you want your parent to look for the next one. 8856 * 8857 * @return Whether this view actually took accessibility focus. 8858 * 8859 * @hide 8860 */ 8861 public boolean requestAccessibilityFocus() { 8862 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8863 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8864 return false; 8865 } 8866 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8867 return false; 8868 } 8869 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8870 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8871 ViewRootImpl viewRootImpl = getViewRootImpl(); 8872 if (viewRootImpl != null) { 8873 viewRootImpl.setAccessibilityFocus(this, null); 8874 } 8875 invalidate(); 8876 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8877 return true; 8878 } 8879 return false; 8880 } 8881 8882 /** 8883 * Call this to try to clear accessibility focus of this view. 8884 * 8885 * See also {@link #focusSearch(int)}, which is what you call to say that you 8886 * have focus, and you want your parent to look for the next one. 8887 * 8888 * @hide 8889 */ 8890 public void clearAccessibilityFocus() { 8891 clearAccessibilityFocusNoCallbacks(0); 8892 8893 // Clear the global reference of accessibility focus if this view or 8894 // any of its descendants had accessibility focus. This will NOT send 8895 // an event or update internal state if focus is cleared from a 8896 // descendant view, which may leave views in inconsistent states. 8897 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8898 if (viewRootImpl != null) { 8899 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8900 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8901 viewRootImpl.setAccessibilityFocus(null, null); 8902 } 8903 } 8904 } 8905 8906 private void sendAccessibilityHoverEvent(int eventType) { 8907 // Since we are not delivering to a client accessibility events from not 8908 // important views (unless the clinet request that) we need to fire the 8909 // event from the deepest view exposed to the client. As a consequence if 8910 // the user crosses a not exposed view the client will see enter and exit 8911 // of the exposed predecessor followed by and enter and exit of that same 8912 // predecessor when entering and exiting the not exposed descendant. This 8913 // is fine since the client has a clear idea which view is hovered at the 8914 // price of a couple more events being sent. This is a simple and 8915 // working solution. 8916 View source = this; 8917 while (true) { 8918 if (source.includeForAccessibility()) { 8919 source.sendAccessibilityEvent(eventType); 8920 return; 8921 } 8922 ViewParent parent = source.getParent(); 8923 if (parent instanceof View) { 8924 source = (View) parent; 8925 } else { 8926 return; 8927 } 8928 } 8929 } 8930 8931 /** 8932 * Clears accessibility focus without calling any callback methods 8933 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8934 * is used separately from that one for clearing accessibility focus when 8935 * giving this focus to another view. 8936 * 8937 * @param action The action, if any, that led to focus being cleared. Set to 8938 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 8939 * the window. 8940 */ 8941 void clearAccessibilityFocusNoCallbacks(int action) { 8942 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8943 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8944 invalidate(); 8945 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8946 AccessibilityEvent event = AccessibilityEvent.obtain( 8947 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8948 event.setAction(action); 8949 if (mAccessibilityDelegate != null) { 8950 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 8951 } else { 8952 sendAccessibilityEventUnchecked(event); 8953 } 8954 } 8955 } 8956 } 8957 8958 /** 8959 * Call this to try to give focus to a specific view or to one of its 8960 * descendants. 8961 * 8962 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8963 * false), or if it is focusable and it is not focusable in touch mode 8964 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8965 * 8966 * See also {@link #focusSearch(int)}, which is what you call to say that you 8967 * have focus, and you want your parent to look for the next one. 8968 * 8969 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8970 * {@link #FOCUS_DOWN} and <code>null</code>. 8971 * 8972 * @return Whether this view or one of its descendants actually took focus. 8973 */ 8974 public final boolean requestFocus() { 8975 return requestFocus(View.FOCUS_DOWN); 8976 } 8977 8978 /** 8979 * Call this to try to give focus to a specific view or to one of its 8980 * descendants and give it a hint about what direction focus is heading. 8981 * 8982 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8983 * false), or if it is focusable and it is not focusable in touch mode 8984 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8985 * 8986 * See also {@link #focusSearch(int)}, which is what you call to say that you 8987 * have focus, and you want your parent to look for the next one. 8988 * 8989 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8990 * <code>null</code> set for the previously focused rectangle. 8991 * 8992 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8993 * @return Whether this view or one of its descendants actually took focus. 8994 */ 8995 public final boolean requestFocus(int direction) { 8996 return requestFocus(direction, null); 8997 } 8998 8999 /** 9000 * Call this to try to give focus to a specific view or to one of its descendants 9001 * and give it hints about the direction and a specific rectangle that the focus 9002 * is coming from. The rectangle can help give larger views a finer grained hint 9003 * about where focus is coming from, and therefore, where to show selection, or 9004 * forward focus change internally. 9005 * 9006 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 9007 * false), or if it is focusable and it is not focusable in touch mode 9008 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 9009 * 9010 * A View will not take focus if it is not visible. 9011 * 9012 * A View will not take focus if one of its parents has 9013 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9014 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9015 * 9016 * See also {@link #focusSearch(int)}, which is what you call to say that you 9017 * have focus, and you want your parent to look for the next one. 9018 * 9019 * You may wish to override this method if your custom {@link View} has an internal 9020 * {@link View} that it wishes to forward the request to. 9021 * 9022 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9023 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9024 * to give a finer grained hint about where focus is coming from. May be null 9025 * if there is no hint. 9026 * @return Whether this view or one of its descendants actually took focus. 9027 */ 9028 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9029 return requestFocusNoSearch(direction, previouslyFocusedRect); 9030 } 9031 9032 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9033 // need to be focusable 9034 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9035 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9036 return false; 9037 } 9038 9039 // need to be focusable in touch mode if in touch mode 9040 if (isInTouchMode() && 9041 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9042 return false; 9043 } 9044 9045 // need to not have any parents blocking us 9046 if (hasAncestorThatBlocksDescendantFocus()) { 9047 return false; 9048 } 9049 9050 handleFocusGainInternal(direction, previouslyFocusedRect); 9051 return true; 9052 } 9053 9054 /** 9055 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9056 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9057 * touch mode to request focus when they are touched. 9058 * 9059 * @return Whether this view or one of its descendants actually took focus. 9060 * 9061 * @see #isInTouchMode() 9062 * 9063 */ 9064 public final boolean requestFocusFromTouch() { 9065 // Leave touch mode if we need to 9066 if (isInTouchMode()) { 9067 ViewRootImpl viewRoot = getViewRootImpl(); 9068 if (viewRoot != null) { 9069 viewRoot.ensureTouchMode(false); 9070 } 9071 } 9072 return requestFocus(View.FOCUS_DOWN); 9073 } 9074 9075 /** 9076 * @return Whether any ancestor of this view blocks descendant focus. 9077 */ 9078 private boolean hasAncestorThatBlocksDescendantFocus() { 9079 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9080 ViewParent ancestor = mParent; 9081 while (ancestor instanceof ViewGroup) { 9082 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9083 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9084 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9085 return true; 9086 } else { 9087 ancestor = vgAncestor.getParent(); 9088 } 9089 } 9090 return false; 9091 } 9092 9093 /** 9094 * Gets the mode for determining whether this View is important for accessibility 9095 * which is if it fires accessibility events and if it is reported to 9096 * accessibility services that query the screen. 9097 * 9098 * @return The mode for determining whether a View is important for accessibility. 9099 * 9100 * @attr ref android.R.styleable#View_importantForAccessibility 9101 * 9102 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9103 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9104 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9105 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9106 */ 9107 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9108 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9109 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9110 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9111 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9112 to = "noHideDescendants") 9113 }) 9114 public int getImportantForAccessibility() { 9115 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9116 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9117 } 9118 9119 /** 9120 * Sets the live region mode for this view. This indicates to accessibility 9121 * services whether they should automatically notify the user about changes 9122 * to the view's content description or text, or to the content descriptions 9123 * or text of the view's children (where applicable). 9124 * <p> 9125 * For example, in a login screen with a TextView that displays an "incorrect 9126 * password" notification, that view should be marked as a live region with 9127 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9128 * <p> 9129 * To disable change notifications for this view, use 9130 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9131 * mode for most views. 9132 * <p> 9133 * To indicate that the user should be notified of changes, use 9134 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9135 * <p> 9136 * If the view's changes should interrupt ongoing speech and notify the user 9137 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9138 * 9139 * @param mode The live region mode for this view, one of: 9140 * <ul> 9141 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9142 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9143 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9144 * </ul> 9145 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9146 */ 9147 public void setAccessibilityLiveRegion(int mode) { 9148 if (mode != getAccessibilityLiveRegion()) { 9149 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9150 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9151 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9152 notifyViewAccessibilityStateChangedIfNeeded( 9153 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9154 } 9155 } 9156 9157 /** 9158 * Gets the live region mode for this View. 9159 * 9160 * @return The live region mode for the view. 9161 * 9162 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9163 * 9164 * @see #setAccessibilityLiveRegion(int) 9165 */ 9166 public int getAccessibilityLiveRegion() { 9167 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9168 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9169 } 9170 9171 /** 9172 * Sets how to determine whether this view is important for accessibility 9173 * which is if it fires accessibility events and if it is reported to 9174 * accessibility services that query the screen. 9175 * 9176 * @param mode How to determine whether this view is important for accessibility. 9177 * 9178 * @attr ref android.R.styleable#View_importantForAccessibility 9179 * 9180 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9181 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9182 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9183 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9184 */ 9185 public void setImportantForAccessibility(int mode) { 9186 final int oldMode = getImportantForAccessibility(); 9187 if (mode != oldMode) { 9188 final boolean hideDescendants = 9189 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9190 9191 // If this node or its descendants are no longer important, try to 9192 // clear accessibility focus. 9193 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9194 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9195 if (focusHost != null) { 9196 focusHost.clearAccessibilityFocus(); 9197 } 9198 } 9199 9200 // If we're moving between AUTO and another state, we might not need 9201 // to send a subtree changed notification. We'll store the computed 9202 // importance, since we'll need to check it later to make sure. 9203 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9204 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9205 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9206 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9207 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9208 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9209 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9210 notifySubtreeAccessibilityStateChangedIfNeeded(); 9211 } else { 9212 notifyViewAccessibilityStateChangedIfNeeded( 9213 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9214 } 9215 } 9216 } 9217 9218 /** 9219 * Returns the view within this view's hierarchy that is hosting 9220 * accessibility focus. 9221 * 9222 * @param searchDescendants whether to search for focus in descendant views 9223 * @return the view hosting accessibility focus, or {@code null} 9224 */ 9225 private View findAccessibilityFocusHost(boolean searchDescendants) { 9226 if (isAccessibilityFocusedViewOrHost()) { 9227 return this; 9228 } 9229 9230 if (searchDescendants) { 9231 final ViewRootImpl viewRoot = getViewRootImpl(); 9232 if (viewRoot != null) { 9233 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9234 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9235 return focusHost; 9236 } 9237 } 9238 } 9239 9240 return null; 9241 } 9242 9243 /** 9244 * Computes whether this view should be exposed for accessibility. In 9245 * general, views that are interactive or provide information are exposed 9246 * while views that serve only as containers are hidden. 9247 * <p> 9248 * If an ancestor of this view has importance 9249 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9250 * returns <code>false</code>. 9251 * <p> 9252 * Otherwise, the value is computed according to the view's 9253 * {@link #getImportantForAccessibility()} value: 9254 * <ol> 9255 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9256 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9257 * </code> 9258 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9259 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9260 * view satisfies any of the following: 9261 * <ul> 9262 * <li>Is actionable, e.g. {@link #isClickable()}, 9263 * {@link #isLongClickable()}, or {@link #isFocusable()} 9264 * <li>Has an {@link AccessibilityDelegate} 9265 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9266 * {@link OnKeyListener}, etc. 9267 * <li>Is an accessibility live region, e.g. 9268 * {@link #getAccessibilityLiveRegion()} is not 9269 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9270 * </ul> 9271 * </ol> 9272 * 9273 * @return Whether the view is exposed for accessibility. 9274 * @see #setImportantForAccessibility(int) 9275 * @see #getImportantForAccessibility() 9276 */ 9277 public boolean isImportantForAccessibility() { 9278 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9279 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9280 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9281 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9282 return false; 9283 } 9284 9285 // Check parent mode to ensure we're not hidden. 9286 ViewParent parent = mParent; 9287 while (parent instanceof View) { 9288 if (((View) parent).getImportantForAccessibility() 9289 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9290 return false; 9291 } 9292 parent = parent.getParent(); 9293 } 9294 9295 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9296 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9297 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9298 } 9299 9300 /** 9301 * Gets the parent for accessibility purposes. Note that the parent for 9302 * accessibility is not necessary the immediate parent. It is the first 9303 * predecessor that is important for accessibility. 9304 * 9305 * @return The parent for accessibility purposes. 9306 */ 9307 public ViewParent getParentForAccessibility() { 9308 if (mParent instanceof View) { 9309 View parentView = (View) mParent; 9310 if (parentView.includeForAccessibility()) { 9311 return mParent; 9312 } else { 9313 return mParent.getParentForAccessibility(); 9314 } 9315 } 9316 return null; 9317 } 9318 9319 /** 9320 * Adds the children of this View relevant for accessibility to the given list 9321 * as output. Since some Views are not important for accessibility the added 9322 * child views are not necessarily direct children of this view, rather they are 9323 * the first level of descendants important for accessibility. 9324 * 9325 * @param outChildren The output list that will receive children for accessibility. 9326 */ 9327 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9328 9329 } 9330 9331 /** 9332 * Whether to regard this view for accessibility. A view is regarded for 9333 * accessibility if it is important for accessibility or the querying 9334 * accessibility service has explicitly requested that view not 9335 * important for accessibility are regarded. 9336 * 9337 * @return Whether to regard the view for accessibility. 9338 * 9339 * @hide 9340 */ 9341 public boolean includeForAccessibility() { 9342 if (mAttachInfo != null) { 9343 return (mAttachInfo.mAccessibilityFetchFlags 9344 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9345 || isImportantForAccessibility(); 9346 } 9347 return false; 9348 } 9349 9350 /** 9351 * Returns whether the View is considered actionable from 9352 * accessibility perspective. Such view are important for 9353 * accessibility. 9354 * 9355 * @return True if the view is actionable for accessibility. 9356 * 9357 * @hide 9358 */ 9359 public boolean isActionableForAccessibility() { 9360 return (isClickable() || isLongClickable() || isFocusable()); 9361 } 9362 9363 /** 9364 * Returns whether the View has registered callbacks which makes it 9365 * important for accessibility. 9366 * 9367 * @return True if the view is actionable for accessibility. 9368 */ 9369 private boolean hasListenersForAccessibility() { 9370 ListenerInfo info = getListenerInfo(); 9371 return mTouchDelegate != null || info.mOnKeyListener != null 9372 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9373 || info.mOnHoverListener != null || info.mOnDragListener != null; 9374 } 9375 9376 /** 9377 * Notifies that the accessibility state of this view changed. The change 9378 * is local to this view and does not represent structural changes such 9379 * as children and parent. For example, the view became focusable. The 9380 * notification is at at most once every 9381 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9382 * to avoid unnecessary load to the system. Also once a view has a pending 9383 * notification this method is a NOP until the notification has been sent. 9384 * 9385 * @hide 9386 */ 9387 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9388 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9389 return; 9390 } 9391 if (mSendViewStateChangedAccessibilityEvent == null) { 9392 mSendViewStateChangedAccessibilityEvent = 9393 new SendViewStateChangedAccessibilityEvent(); 9394 } 9395 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9396 } 9397 9398 /** 9399 * Notifies that the accessibility state of this view changed. The change 9400 * is *not* local to this view and does represent structural changes such 9401 * as children and parent. For example, the view size changed. The 9402 * notification is at at most once every 9403 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9404 * to avoid unnecessary load to the system. Also once a view has a pending 9405 * notification this method is a NOP until the notification has been sent. 9406 * 9407 * @hide 9408 */ 9409 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9410 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9411 return; 9412 } 9413 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9414 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9415 if (mParent != null) { 9416 try { 9417 mParent.notifySubtreeAccessibilityStateChanged( 9418 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9419 } catch (AbstractMethodError e) { 9420 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9421 " does not fully implement ViewParent", e); 9422 } 9423 } 9424 } 9425 } 9426 9427 /** 9428 * Change the visibility of the View without triggering any other changes. This is 9429 * important for transitions, where visibility changes should not adjust focus or 9430 * trigger a new layout. This is only used when the visibility has already been changed 9431 * and we need a transient value during an animation. When the animation completes, 9432 * the original visibility value is always restored. 9433 * 9434 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9435 * @hide 9436 */ 9437 public void setTransitionVisibility(@Visibility int visibility) { 9438 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9439 } 9440 9441 /** 9442 * Reset the flag indicating the accessibility state of the subtree rooted 9443 * at this view changed. 9444 */ 9445 void resetSubtreeAccessibilityStateChanged() { 9446 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9447 } 9448 9449 /** 9450 * Report an accessibility action to this view's parents for delegated processing. 9451 * 9452 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9453 * call this method to delegate an accessibility action to a supporting parent. If the parent 9454 * returns true from its 9455 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9456 * method this method will return true to signify that the action was consumed.</p> 9457 * 9458 * <p>This method is useful for implementing nested scrolling child views. If 9459 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9460 * a custom view implementation may invoke this method to allow a parent to consume the 9461 * scroll first. If this method returns true the custom view should skip its own scrolling 9462 * behavior.</p> 9463 * 9464 * @param action Accessibility action to delegate 9465 * @param arguments Optional action arguments 9466 * @return true if the action was consumed by a parent 9467 */ 9468 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9469 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9470 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9471 return true; 9472 } 9473 } 9474 return false; 9475 } 9476 9477 /** 9478 * Performs the specified accessibility action on the view. For 9479 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9480 * <p> 9481 * If an {@link AccessibilityDelegate} has been specified via calling 9482 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9483 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9484 * is responsible for handling this call. 9485 * </p> 9486 * 9487 * <p>The default implementation will delegate 9488 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9489 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9490 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9491 * 9492 * @param action The action to perform. 9493 * @param arguments Optional action arguments. 9494 * @return Whether the action was performed. 9495 */ 9496 public boolean performAccessibilityAction(int action, Bundle arguments) { 9497 if (mAccessibilityDelegate != null) { 9498 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9499 } else { 9500 return performAccessibilityActionInternal(action, arguments); 9501 } 9502 } 9503 9504 /** 9505 * @see #performAccessibilityAction(int, Bundle) 9506 * 9507 * Note: Called from the default {@link AccessibilityDelegate}. 9508 * 9509 * @hide 9510 */ 9511 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9512 if (isNestedScrollingEnabled() 9513 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9514 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9515 || action == R.id.accessibilityActionScrollUp 9516 || action == R.id.accessibilityActionScrollLeft 9517 || action == R.id.accessibilityActionScrollDown 9518 || action == R.id.accessibilityActionScrollRight)) { 9519 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9520 return true; 9521 } 9522 } 9523 9524 switch (action) { 9525 case AccessibilityNodeInfo.ACTION_CLICK: { 9526 if (isClickable()) { 9527 performClick(); 9528 return true; 9529 } 9530 } break; 9531 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9532 if (isLongClickable()) { 9533 performLongClick(); 9534 return true; 9535 } 9536 } break; 9537 case AccessibilityNodeInfo.ACTION_FOCUS: { 9538 if (!hasFocus()) { 9539 // Get out of touch mode since accessibility 9540 // wants to move focus around. 9541 getViewRootImpl().ensureTouchMode(false); 9542 return requestFocus(); 9543 } 9544 } break; 9545 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9546 if (hasFocus()) { 9547 clearFocus(); 9548 return !isFocused(); 9549 } 9550 } break; 9551 case AccessibilityNodeInfo.ACTION_SELECT: { 9552 if (!isSelected()) { 9553 setSelected(true); 9554 return isSelected(); 9555 } 9556 } break; 9557 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9558 if (isSelected()) { 9559 setSelected(false); 9560 return !isSelected(); 9561 } 9562 } break; 9563 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9564 if (!isAccessibilityFocused()) { 9565 return requestAccessibilityFocus(); 9566 } 9567 } break; 9568 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9569 if (isAccessibilityFocused()) { 9570 clearAccessibilityFocus(); 9571 return true; 9572 } 9573 } break; 9574 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9575 if (arguments != null) { 9576 final int granularity = arguments.getInt( 9577 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9578 final boolean extendSelection = arguments.getBoolean( 9579 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9580 return traverseAtGranularity(granularity, true, extendSelection); 9581 } 9582 } break; 9583 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9584 if (arguments != null) { 9585 final int granularity = arguments.getInt( 9586 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9587 final boolean extendSelection = arguments.getBoolean( 9588 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9589 return traverseAtGranularity(granularity, false, extendSelection); 9590 } 9591 } break; 9592 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9593 CharSequence text = getIterableTextForAccessibility(); 9594 if (text == null) { 9595 return false; 9596 } 9597 final int start = (arguments != null) ? arguments.getInt( 9598 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9599 final int end = (arguments != null) ? arguments.getInt( 9600 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9601 // Only cursor position can be specified (selection length == 0) 9602 if ((getAccessibilitySelectionStart() != start 9603 || getAccessibilitySelectionEnd() != end) 9604 && (start == end)) { 9605 setAccessibilitySelection(start, end); 9606 notifyViewAccessibilityStateChangedIfNeeded( 9607 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9608 return true; 9609 } 9610 } break; 9611 case R.id.accessibilityActionShowOnScreen: { 9612 if (mAttachInfo != null) { 9613 final Rect r = mAttachInfo.mTmpInvalRect; 9614 getDrawingRect(r); 9615 return requestRectangleOnScreen(r, true); 9616 } 9617 } break; 9618 case R.id.accessibilityActionContextClick: { 9619 if (isContextClickable()) { 9620 performContextClick(); 9621 return true; 9622 } 9623 } break; 9624 } 9625 return false; 9626 } 9627 9628 private boolean traverseAtGranularity(int granularity, boolean forward, 9629 boolean extendSelection) { 9630 CharSequence text = getIterableTextForAccessibility(); 9631 if (text == null || text.length() == 0) { 9632 return false; 9633 } 9634 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9635 if (iterator == null) { 9636 return false; 9637 } 9638 int current = getAccessibilitySelectionEnd(); 9639 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9640 current = forward ? 0 : text.length(); 9641 } 9642 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9643 if (range == null) { 9644 return false; 9645 } 9646 final int segmentStart = range[0]; 9647 final int segmentEnd = range[1]; 9648 int selectionStart; 9649 int selectionEnd; 9650 if (extendSelection && isAccessibilitySelectionExtendable()) { 9651 selectionStart = getAccessibilitySelectionStart(); 9652 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9653 selectionStart = forward ? segmentStart : segmentEnd; 9654 } 9655 selectionEnd = forward ? segmentEnd : segmentStart; 9656 } else { 9657 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9658 } 9659 setAccessibilitySelection(selectionStart, selectionEnd); 9660 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9661 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9662 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9663 return true; 9664 } 9665 9666 /** 9667 * Gets the text reported for accessibility purposes. 9668 * 9669 * @return The accessibility text. 9670 * 9671 * @hide 9672 */ 9673 public CharSequence getIterableTextForAccessibility() { 9674 return getContentDescription(); 9675 } 9676 9677 /** 9678 * Gets whether accessibility selection can be extended. 9679 * 9680 * @return If selection is extensible. 9681 * 9682 * @hide 9683 */ 9684 public boolean isAccessibilitySelectionExtendable() { 9685 return false; 9686 } 9687 9688 /** 9689 * @hide 9690 */ 9691 public int getAccessibilitySelectionStart() { 9692 return mAccessibilityCursorPosition; 9693 } 9694 9695 /** 9696 * @hide 9697 */ 9698 public int getAccessibilitySelectionEnd() { 9699 return getAccessibilitySelectionStart(); 9700 } 9701 9702 /** 9703 * @hide 9704 */ 9705 public void setAccessibilitySelection(int start, int end) { 9706 if (start == end && end == mAccessibilityCursorPosition) { 9707 return; 9708 } 9709 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9710 mAccessibilityCursorPosition = start; 9711 } else { 9712 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9713 } 9714 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9715 } 9716 9717 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9718 int fromIndex, int toIndex) { 9719 if (mParent == null) { 9720 return; 9721 } 9722 AccessibilityEvent event = AccessibilityEvent.obtain( 9723 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9724 onInitializeAccessibilityEvent(event); 9725 onPopulateAccessibilityEvent(event); 9726 event.setFromIndex(fromIndex); 9727 event.setToIndex(toIndex); 9728 event.setAction(action); 9729 event.setMovementGranularity(granularity); 9730 mParent.requestSendAccessibilityEvent(this, event); 9731 } 9732 9733 /** 9734 * @hide 9735 */ 9736 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9737 switch (granularity) { 9738 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9739 CharSequence text = getIterableTextForAccessibility(); 9740 if (text != null && text.length() > 0) { 9741 CharacterTextSegmentIterator iterator = 9742 CharacterTextSegmentIterator.getInstance( 9743 mContext.getResources().getConfiguration().locale); 9744 iterator.initialize(text.toString()); 9745 return iterator; 9746 } 9747 } break; 9748 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9749 CharSequence text = getIterableTextForAccessibility(); 9750 if (text != null && text.length() > 0) { 9751 WordTextSegmentIterator iterator = 9752 WordTextSegmentIterator.getInstance( 9753 mContext.getResources().getConfiguration().locale); 9754 iterator.initialize(text.toString()); 9755 return iterator; 9756 } 9757 } break; 9758 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9759 CharSequence text = getIterableTextForAccessibility(); 9760 if (text != null && text.length() > 0) { 9761 ParagraphTextSegmentIterator iterator = 9762 ParagraphTextSegmentIterator.getInstance(); 9763 iterator.initialize(text.toString()); 9764 return iterator; 9765 } 9766 } break; 9767 } 9768 return null; 9769 } 9770 9771 /** 9772 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9773 * and {@link #onFinishTemporaryDetach()}. 9774 */ 9775 public final boolean isTemporarilyDetached() { 9776 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9777 } 9778 9779 /** 9780 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9781 * a container View. 9782 */ 9783 @CallSuper 9784 public void dispatchStartTemporaryDetach() { 9785 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9786 onStartTemporaryDetach(); 9787 } 9788 9789 /** 9790 * This is called when a container is going to temporarily detach a child, with 9791 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9792 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9793 * {@link #onDetachedFromWindow()} when the container is done. 9794 */ 9795 public void onStartTemporaryDetach() { 9796 removeUnsetPressCallback(); 9797 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9798 } 9799 9800 /** 9801 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9802 * a container View. 9803 */ 9804 @CallSuper 9805 public void dispatchFinishTemporaryDetach() { 9806 onFinishTemporaryDetach(); 9807 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9808 } 9809 9810 /** 9811 * Called after {@link #onStartTemporaryDetach} when the container is done 9812 * changing the view. 9813 */ 9814 public void onFinishTemporaryDetach() { 9815 } 9816 9817 /** 9818 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9819 * for this view's window. Returns null if the view is not currently attached 9820 * to the window. Normally you will not need to use this directly, but 9821 * just use the standard high-level event callbacks like 9822 * {@link #onKeyDown(int, KeyEvent)}. 9823 */ 9824 public KeyEvent.DispatcherState getKeyDispatcherState() { 9825 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9826 } 9827 9828 /** 9829 * Dispatch a key event before it is processed by any input method 9830 * associated with the view hierarchy. This can be used to intercept 9831 * key events in special situations before the IME consumes them; a 9832 * typical example would be handling the BACK key to update the application's 9833 * UI instead of allowing the IME to see it and close itself. 9834 * 9835 * @param event The key event to be dispatched. 9836 * @return True if the event was handled, false otherwise. 9837 */ 9838 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9839 return onKeyPreIme(event.getKeyCode(), event); 9840 } 9841 9842 /** 9843 * Dispatch a key event to the next view on the focus path. This path runs 9844 * from the top of the view tree down to the currently focused view. If this 9845 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9846 * the next node down the focus path. This method also fires any key 9847 * listeners. 9848 * 9849 * @param event The key event to be dispatched. 9850 * @return True if the event was handled, false otherwise. 9851 */ 9852 public boolean dispatchKeyEvent(KeyEvent event) { 9853 if (mInputEventConsistencyVerifier != null) { 9854 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9855 } 9856 9857 // Give any attached key listener a first crack at the event. 9858 //noinspection SimplifiableIfStatement 9859 ListenerInfo li = mListenerInfo; 9860 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9861 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9862 return true; 9863 } 9864 9865 if (event.dispatch(this, mAttachInfo != null 9866 ? mAttachInfo.mKeyDispatchState : null, this)) { 9867 return true; 9868 } 9869 9870 if (mInputEventConsistencyVerifier != null) { 9871 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9872 } 9873 return false; 9874 } 9875 9876 /** 9877 * Dispatches a key shortcut event. 9878 * 9879 * @param event The key event to be dispatched. 9880 * @return True if the event was handled by the view, false otherwise. 9881 */ 9882 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9883 return onKeyShortcut(event.getKeyCode(), event); 9884 } 9885 9886 /** 9887 * Pass the touch screen motion event down to the target view, or this 9888 * view if it is the target. 9889 * 9890 * @param event The motion event to be dispatched. 9891 * @return True if the event was handled by the view, false otherwise. 9892 */ 9893 public boolean dispatchTouchEvent(MotionEvent event) { 9894 // If the event should be handled by accessibility focus first. 9895 if (event.isTargetAccessibilityFocus()) { 9896 // We don't have focus or no virtual descendant has it, do not handle the event. 9897 if (!isAccessibilityFocusedViewOrHost()) { 9898 return false; 9899 } 9900 // We have focus and got the event, then use normal event dispatch. 9901 event.setTargetAccessibilityFocus(false); 9902 } 9903 9904 boolean result = false; 9905 9906 if (mInputEventConsistencyVerifier != null) { 9907 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9908 } 9909 9910 final int actionMasked = event.getActionMasked(); 9911 if (actionMasked == MotionEvent.ACTION_DOWN) { 9912 // Defensive cleanup for new gesture 9913 stopNestedScroll(); 9914 } 9915 9916 if (onFilterTouchEventForSecurity(event)) { 9917 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9918 result = true; 9919 } 9920 //noinspection SimplifiableIfStatement 9921 ListenerInfo li = mListenerInfo; 9922 if (li != null && li.mOnTouchListener != null 9923 && (mViewFlags & ENABLED_MASK) == ENABLED 9924 && li.mOnTouchListener.onTouch(this, event)) { 9925 result = true; 9926 } 9927 9928 if (!result && onTouchEvent(event)) { 9929 result = true; 9930 } 9931 } 9932 9933 if (!result && mInputEventConsistencyVerifier != null) { 9934 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9935 } 9936 9937 // Clean up after nested scrolls if this is the end of a gesture; 9938 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9939 // of the gesture. 9940 if (actionMasked == MotionEvent.ACTION_UP || 9941 actionMasked == MotionEvent.ACTION_CANCEL || 9942 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9943 stopNestedScroll(); 9944 } 9945 9946 return result; 9947 } 9948 9949 boolean isAccessibilityFocusedViewOrHost() { 9950 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9951 .getAccessibilityFocusedHost() == this); 9952 } 9953 9954 /** 9955 * Filter the touch event to apply security policies. 9956 * 9957 * @param event The motion event to be filtered. 9958 * @return True if the event should be dispatched, false if the event should be dropped. 9959 * 9960 * @see #getFilterTouchesWhenObscured 9961 */ 9962 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9963 //noinspection RedundantIfStatement 9964 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9965 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9966 // Window is obscured, drop this touch. 9967 return false; 9968 } 9969 return true; 9970 } 9971 9972 /** 9973 * Pass a trackball motion event down to the focused view. 9974 * 9975 * @param event The motion event to be dispatched. 9976 * @return True if the event was handled by the view, false otherwise. 9977 */ 9978 public boolean dispatchTrackballEvent(MotionEvent event) { 9979 if (mInputEventConsistencyVerifier != null) { 9980 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9981 } 9982 9983 return onTrackballEvent(event); 9984 } 9985 9986 /** 9987 * Dispatch a generic motion event. 9988 * <p> 9989 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9990 * are delivered to the view under the pointer. All other generic motion events are 9991 * delivered to the focused view. Hover events are handled specially and are delivered 9992 * to {@link #onHoverEvent(MotionEvent)}. 9993 * </p> 9994 * 9995 * @param event The motion event to be dispatched. 9996 * @return True if the event was handled by the view, false otherwise. 9997 */ 9998 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9999 if (mInputEventConsistencyVerifier != null) { 10000 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 10001 } 10002 10003 final int source = event.getSource(); 10004 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 10005 final int action = event.getAction(); 10006 if (action == MotionEvent.ACTION_HOVER_ENTER 10007 || action == MotionEvent.ACTION_HOVER_MOVE 10008 || action == MotionEvent.ACTION_HOVER_EXIT) { 10009 if (dispatchHoverEvent(event)) { 10010 return true; 10011 } 10012 } else if (dispatchGenericPointerEvent(event)) { 10013 return true; 10014 } 10015 } else if (dispatchGenericFocusedEvent(event)) { 10016 return true; 10017 } 10018 10019 if (dispatchGenericMotionEventInternal(event)) { 10020 return true; 10021 } 10022 10023 if (mInputEventConsistencyVerifier != null) { 10024 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10025 } 10026 return false; 10027 } 10028 10029 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10030 //noinspection SimplifiableIfStatement 10031 ListenerInfo li = mListenerInfo; 10032 if (li != null && li.mOnGenericMotionListener != null 10033 && (mViewFlags & ENABLED_MASK) == ENABLED 10034 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10035 return true; 10036 } 10037 10038 if (onGenericMotionEvent(event)) { 10039 return true; 10040 } 10041 10042 final int actionButton = event.getActionButton(); 10043 switch (event.getActionMasked()) { 10044 case MotionEvent.ACTION_BUTTON_PRESS: 10045 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10046 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10047 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10048 if (performContextClick()) { 10049 mInContextButtonPress = true; 10050 setPressed(true, event.getX(), event.getY()); 10051 removeTapCallback(); 10052 removeLongPressCallback(); 10053 return true; 10054 } 10055 } 10056 break; 10057 10058 case MotionEvent.ACTION_BUTTON_RELEASE: 10059 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10060 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10061 mInContextButtonPress = false; 10062 mIgnoreNextUpEvent = true; 10063 } 10064 break; 10065 } 10066 10067 if (mInputEventConsistencyVerifier != null) { 10068 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10069 } 10070 return false; 10071 } 10072 10073 /** 10074 * Dispatch a hover event. 10075 * <p> 10076 * Do not call this method directly. 10077 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10078 * </p> 10079 * 10080 * @param event The motion event to be dispatched. 10081 * @return True if the event was handled by the view, false otherwise. 10082 */ 10083 protected boolean dispatchHoverEvent(MotionEvent event) { 10084 ListenerInfo li = mListenerInfo; 10085 //noinspection SimplifiableIfStatement 10086 if (li != null && li.mOnHoverListener != null 10087 && (mViewFlags & ENABLED_MASK) == ENABLED 10088 && li.mOnHoverListener.onHover(this, event)) { 10089 return true; 10090 } 10091 10092 return onHoverEvent(event); 10093 } 10094 10095 /** 10096 * Returns true if the view has a child to which it has recently sent 10097 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10098 * it does not have a hovered child, then it must be the innermost hovered view. 10099 * @hide 10100 */ 10101 protected boolean hasHoveredChild() { 10102 return false; 10103 } 10104 10105 /** 10106 * Dispatch a generic motion event to the view under the first pointer. 10107 * <p> 10108 * Do not call this method directly. 10109 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10110 * </p> 10111 * 10112 * @param event The motion event to be dispatched. 10113 * @return True if the event was handled by the view, false otherwise. 10114 */ 10115 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10116 return false; 10117 } 10118 10119 /** 10120 * Dispatch a generic motion event to the currently focused view. 10121 * <p> 10122 * Do not call this method directly. 10123 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10124 * </p> 10125 * 10126 * @param event The motion event to be dispatched. 10127 * @return True if the event was handled by the view, false otherwise. 10128 */ 10129 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10130 return false; 10131 } 10132 10133 /** 10134 * Dispatch a pointer event. 10135 * <p> 10136 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10137 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10138 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10139 * and should not be expected to handle other pointing device features. 10140 * </p> 10141 * 10142 * @param event The motion event to be dispatched. 10143 * @return True if the event was handled by the view, false otherwise. 10144 * @hide 10145 */ 10146 public final boolean dispatchPointerEvent(MotionEvent event) { 10147 if (event.isTouchEvent()) { 10148 return dispatchTouchEvent(event); 10149 } else { 10150 return dispatchGenericMotionEvent(event); 10151 } 10152 } 10153 10154 /** 10155 * Called when the window containing this view gains or loses window focus. 10156 * ViewGroups should override to route to their children. 10157 * 10158 * @param hasFocus True if the window containing this view now has focus, 10159 * false otherwise. 10160 */ 10161 public void dispatchWindowFocusChanged(boolean hasFocus) { 10162 onWindowFocusChanged(hasFocus); 10163 } 10164 10165 /** 10166 * Called when the window containing this view gains or loses focus. Note 10167 * that this is separate from view focus: to receive key events, both 10168 * your view and its window must have focus. If a window is displayed 10169 * on top of yours that takes input focus, then your own window will lose 10170 * focus but the view focus will remain unchanged. 10171 * 10172 * @param hasWindowFocus True if the window containing this view now has 10173 * focus, false otherwise. 10174 */ 10175 public void onWindowFocusChanged(boolean hasWindowFocus) { 10176 InputMethodManager imm = InputMethodManager.peekInstance(); 10177 if (!hasWindowFocus) { 10178 if (isPressed()) { 10179 setPressed(false); 10180 } 10181 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10182 imm.focusOut(this); 10183 } 10184 removeLongPressCallback(); 10185 removeTapCallback(); 10186 onFocusLost(); 10187 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10188 imm.focusIn(this); 10189 } 10190 refreshDrawableState(); 10191 } 10192 10193 /** 10194 * Returns true if this view is in a window that currently has window focus. 10195 * Note that this is not the same as the view itself having focus. 10196 * 10197 * @return True if this view is in a window that currently has window focus. 10198 */ 10199 public boolean hasWindowFocus() { 10200 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10201 } 10202 10203 /** 10204 * Dispatch a view visibility change down the view hierarchy. 10205 * ViewGroups should override to route to their children. 10206 * @param changedView The view whose visibility changed. Could be 'this' or 10207 * an ancestor view. 10208 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10209 * {@link #INVISIBLE} or {@link #GONE}. 10210 */ 10211 protected void dispatchVisibilityChanged(@NonNull View changedView, 10212 @Visibility int visibility) { 10213 onVisibilityChanged(changedView, visibility); 10214 } 10215 10216 /** 10217 * Called when the visibility of the view or an ancestor of the view has 10218 * changed. 10219 * 10220 * @param changedView The view whose visibility changed. May be 10221 * {@code this} or an ancestor view. 10222 * @param visibility The new visibility, one of {@link #VISIBLE}, 10223 * {@link #INVISIBLE} or {@link #GONE}. 10224 */ 10225 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10226 } 10227 10228 /** 10229 * Dispatch a hint about whether this view is displayed. For instance, when 10230 * a View moves out of the screen, it might receives a display hint indicating 10231 * the view is not displayed. Applications should not <em>rely</em> on this hint 10232 * as there is no guarantee that they will receive one. 10233 * 10234 * @param hint A hint about whether or not this view is displayed: 10235 * {@link #VISIBLE} or {@link #INVISIBLE}. 10236 */ 10237 public void dispatchDisplayHint(@Visibility int hint) { 10238 onDisplayHint(hint); 10239 } 10240 10241 /** 10242 * Gives this view a hint about whether is displayed or not. For instance, when 10243 * a View moves out of the screen, it might receives a display hint indicating 10244 * the view is not displayed. Applications should not <em>rely</em> on this hint 10245 * as there is no guarantee that they will receive one. 10246 * 10247 * @param hint A hint about whether or not this view is displayed: 10248 * {@link #VISIBLE} or {@link #INVISIBLE}. 10249 */ 10250 protected void onDisplayHint(@Visibility int hint) { 10251 } 10252 10253 /** 10254 * Dispatch a window visibility change down the view hierarchy. 10255 * ViewGroups should override to route to their children. 10256 * 10257 * @param visibility The new visibility of the window. 10258 * 10259 * @see #onWindowVisibilityChanged(int) 10260 */ 10261 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10262 onWindowVisibilityChanged(visibility); 10263 } 10264 10265 /** 10266 * Called when the window containing has change its visibility 10267 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10268 * that this tells you whether or not your window is being made visible 10269 * to the window manager; this does <em>not</em> tell you whether or not 10270 * your window is obscured by other windows on the screen, even if it 10271 * is itself visible. 10272 * 10273 * @param visibility The new visibility of the window. 10274 */ 10275 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10276 if (visibility == VISIBLE) { 10277 initialAwakenScrollBars(); 10278 } 10279 } 10280 10281 /** 10282 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10283 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10284 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10285 * 10286 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10287 * ancestors or by window visibility 10288 * @return true if this view is visible to the user, not counting clipping or overlapping 10289 */ 10290 @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) { 10291 final boolean thisVisible = getVisibility() == VISIBLE; 10292 // If we're not visible but something is telling us we are, ignore it. 10293 if (thisVisible || !isVisible) { 10294 onVisibilityAggregated(isVisible); 10295 } 10296 return thisVisible && isVisible; 10297 } 10298 10299 /** 10300 * Called when the user-visibility of this View is potentially affected by a change 10301 * to this view itself, an ancestor view or the window this view is attached to. 10302 * 10303 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10304 * and this view's window is also visible 10305 */ 10306 @CallSuper 10307 public void onVisibilityAggregated(boolean isVisible) { 10308 if (isVisible && mAttachInfo != null) { 10309 initialAwakenScrollBars(); 10310 } 10311 10312 final Drawable dr = mBackground; 10313 if (dr != null && isVisible != dr.isVisible()) { 10314 dr.setVisible(isVisible, false); 10315 } 10316 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10317 if (fg != null && isVisible != fg.isVisible()) { 10318 fg.setVisible(isVisible, false); 10319 } 10320 } 10321 10322 /** 10323 * Returns the current visibility of the window this view is attached to 10324 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10325 * 10326 * @return Returns the current visibility of the view's window. 10327 */ 10328 @Visibility 10329 public int getWindowVisibility() { 10330 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10331 } 10332 10333 /** 10334 * Retrieve the overall visible display size in which the window this view is 10335 * attached to has been positioned in. This takes into account screen 10336 * decorations above the window, for both cases where the window itself 10337 * is being position inside of them or the window is being placed under 10338 * then and covered insets are used for the window to position its content 10339 * inside. In effect, this tells you the available area where content can 10340 * be placed and remain visible to users. 10341 * 10342 * <p>This function requires an IPC back to the window manager to retrieve 10343 * the requested information, so should not be used in performance critical 10344 * code like drawing. 10345 * 10346 * @param outRect Filled in with the visible display frame. If the view 10347 * is not attached to a window, this is simply the raw display size. 10348 */ 10349 public void getWindowVisibleDisplayFrame(Rect outRect) { 10350 if (mAttachInfo != null) { 10351 try { 10352 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10353 } catch (RemoteException e) { 10354 return; 10355 } 10356 // XXX This is really broken, and probably all needs to be done 10357 // in the window manager, and we need to know more about whether 10358 // we want the area behind or in front of the IME. 10359 final Rect insets = mAttachInfo.mVisibleInsets; 10360 outRect.left += insets.left; 10361 outRect.top += insets.top; 10362 outRect.right -= insets.right; 10363 outRect.bottom -= insets.bottom; 10364 return; 10365 } 10366 // The view is not attached to a display so we don't have a context. 10367 // Make a best guess about the display size. 10368 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10369 d.getRectSize(outRect); 10370 } 10371 10372 /** 10373 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10374 * is currently in without any insets. 10375 * 10376 * @hide 10377 */ 10378 public void getWindowDisplayFrame(Rect outRect) { 10379 if (mAttachInfo != null) { 10380 try { 10381 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10382 } catch (RemoteException e) { 10383 return; 10384 } 10385 return; 10386 } 10387 // The view is not attached to a display so we don't have a context. 10388 // Make a best guess about the display size. 10389 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10390 d.getRectSize(outRect); 10391 } 10392 10393 /** 10394 * Dispatch a notification about a resource configuration change down 10395 * the view hierarchy. 10396 * ViewGroups should override to route to their children. 10397 * 10398 * @param newConfig The new resource configuration. 10399 * 10400 * @see #onConfigurationChanged(android.content.res.Configuration) 10401 */ 10402 public void dispatchConfigurationChanged(Configuration newConfig) { 10403 onConfigurationChanged(newConfig); 10404 } 10405 10406 /** 10407 * Called when the current configuration of the resources being used 10408 * by the application have changed. You can use this to decide when 10409 * to reload resources that can changed based on orientation and other 10410 * configuration characteristics. You only need to use this if you are 10411 * not relying on the normal {@link android.app.Activity} mechanism of 10412 * recreating the activity instance upon a configuration change. 10413 * 10414 * @param newConfig The new resource configuration. 10415 */ 10416 protected void onConfigurationChanged(Configuration newConfig) { 10417 } 10418 10419 /** 10420 * Private function to aggregate all per-view attributes in to the view 10421 * root. 10422 */ 10423 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10424 performCollectViewAttributes(attachInfo, visibility); 10425 } 10426 10427 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10428 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10429 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10430 attachInfo.mKeepScreenOn = true; 10431 } 10432 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10433 ListenerInfo li = mListenerInfo; 10434 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10435 attachInfo.mHasSystemUiListeners = true; 10436 } 10437 } 10438 } 10439 10440 void needGlobalAttributesUpdate(boolean force) { 10441 final AttachInfo ai = mAttachInfo; 10442 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10443 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10444 || ai.mHasSystemUiListeners) { 10445 ai.mRecomputeGlobalAttributes = true; 10446 } 10447 } 10448 } 10449 10450 /** 10451 * Returns whether the device is currently in touch mode. Touch mode is entered 10452 * once the user begins interacting with the device by touch, and affects various 10453 * things like whether focus is always visible to the user. 10454 * 10455 * @return Whether the device is in touch mode. 10456 */ 10457 @ViewDebug.ExportedProperty 10458 public boolean isInTouchMode() { 10459 if (mAttachInfo != null) { 10460 return mAttachInfo.mInTouchMode; 10461 } else { 10462 return ViewRootImpl.isInTouchMode(); 10463 } 10464 } 10465 10466 /** 10467 * Returns the context the view is running in, through which it can 10468 * access the current theme, resources, etc. 10469 * 10470 * @return The view's Context. 10471 */ 10472 @ViewDebug.CapturedViewProperty 10473 public final Context getContext() { 10474 return mContext; 10475 } 10476 10477 /** 10478 * Handle a key event before it is processed by any input method 10479 * associated with the view hierarchy. This can be used to intercept 10480 * key events in special situations before the IME consumes them; a 10481 * typical example would be handling the BACK key to update the application's 10482 * UI instead of allowing the IME to see it and close itself. 10483 * 10484 * @param keyCode The value in event.getKeyCode(). 10485 * @param event Description of the key event. 10486 * @return If you handled the event, return true. If you want to allow the 10487 * event to be handled by the next receiver, return false. 10488 */ 10489 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10490 return false; 10491 } 10492 10493 /** 10494 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10495 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10496 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10497 * is released, if the view is enabled and clickable. 10498 * <p> 10499 * Key presses in software keyboards will generally NOT trigger this 10500 * listener, although some may elect to do so in some situations. Do not 10501 * rely on this to catch software key presses. 10502 * 10503 * @param keyCode a key code that represents the button pressed, from 10504 * {@link android.view.KeyEvent} 10505 * @param event the KeyEvent object that defines the button action 10506 */ 10507 public boolean onKeyDown(int keyCode, KeyEvent event) { 10508 if (KeyEvent.isConfirmKey(keyCode)) { 10509 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10510 return true; 10511 } 10512 10513 // Long clickable items don't necessarily have to be clickable. 10514 if (((mViewFlags & CLICKABLE) == CLICKABLE 10515 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10516 && (event.getRepeatCount() == 0)) { 10517 // For the purposes of menu anchoring and drawable hotspots, 10518 // key events are considered to be at the center of the view. 10519 final float x = getWidth() / 2f; 10520 final float y = getHeight() / 2f; 10521 setPressed(true, x, y); 10522 checkForLongClick(0, x, y); 10523 return true; 10524 } 10525 } 10526 10527 return false; 10528 } 10529 10530 /** 10531 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10532 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10533 * the event). 10534 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10535 * although some may elect to do so in some situations. Do not rely on this to 10536 * catch software key presses. 10537 */ 10538 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10539 return false; 10540 } 10541 10542 /** 10543 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10544 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10545 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10546 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10547 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10548 * although some may elect to do so in some situations. Do not rely on this to 10549 * catch software key presses. 10550 * 10551 * @param keyCode A key code that represents the button pressed, from 10552 * {@link android.view.KeyEvent}. 10553 * @param event The KeyEvent object that defines the button action. 10554 */ 10555 public boolean onKeyUp(int keyCode, KeyEvent event) { 10556 if (KeyEvent.isConfirmKey(keyCode)) { 10557 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10558 return true; 10559 } 10560 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10561 setPressed(false); 10562 10563 if (!mHasPerformedLongPress) { 10564 // This is a tap, so remove the longpress check 10565 removeLongPressCallback(); 10566 return performClick(); 10567 } 10568 } 10569 } 10570 return false; 10571 } 10572 10573 /** 10574 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10575 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10576 * the event). 10577 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10578 * although some may elect to do so in some situations. Do not rely on this to 10579 * catch software key presses. 10580 * 10581 * @param keyCode A key code that represents the button pressed, from 10582 * {@link android.view.KeyEvent}. 10583 * @param repeatCount The number of times the action was made. 10584 * @param event The KeyEvent object that defines the button action. 10585 */ 10586 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10587 return false; 10588 } 10589 10590 /** 10591 * Called on the focused view when a key shortcut event is not handled. 10592 * Override this method to implement local key shortcuts for the View. 10593 * Key shortcuts can also be implemented by setting the 10594 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10595 * 10596 * @param keyCode The value in event.getKeyCode(). 10597 * @param event Description of the key event. 10598 * @return If you handled the event, return true. If you want to allow the 10599 * event to be handled by the next receiver, return false. 10600 */ 10601 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10602 return false; 10603 } 10604 10605 /** 10606 * Check whether the called view is a text editor, in which case it 10607 * would make sense to automatically display a soft input window for 10608 * it. Subclasses should override this if they implement 10609 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10610 * a call on that method would return a non-null InputConnection, and 10611 * they are really a first-class editor that the user would normally 10612 * start typing on when the go into a window containing your view. 10613 * 10614 * <p>The default implementation always returns false. This does 10615 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10616 * will not be called or the user can not otherwise perform edits on your 10617 * view; it is just a hint to the system that this is not the primary 10618 * purpose of this view. 10619 * 10620 * @return Returns true if this view is a text editor, else false. 10621 */ 10622 public boolean onCheckIsTextEditor() { 10623 return false; 10624 } 10625 10626 /** 10627 * Create a new InputConnection for an InputMethod to interact 10628 * with the view. The default implementation returns null, since it doesn't 10629 * support input methods. You can override this to implement such support. 10630 * This is only needed for views that take focus and text input. 10631 * 10632 * <p>When implementing this, you probably also want to implement 10633 * {@link #onCheckIsTextEditor()} to indicate you will return a 10634 * non-null InputConnection.</p> 10635 * 10636 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10637 * object correctly and in its entirety, so that the connected IME can rely 10638 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10639 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10640 * must be filled in with the correct cursor position for IMEs to work correctly 10641 * with your application.</p> 10642 * 10643 * @param outAttrs Fill in with attribute information about the connection. 10644 */ 10645 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10646 return null; 10647 } 10648 10649 /** 10650 * Called by the {@link android.view.inputmethod.InputMethodManager} 10651 * when a view who is not the current 10652 * input connection target is trying to make a call on the manager. The 10653 * default implementation returns false; you can override this to return 10654 * true for certain views if you are performing InputConnection proxying 10655 * to them. 10656 * @param view The View that is making the InputMethodManager call. 10657 * @return Return true to allow the call, false to reject. 10658 */ 10659 public boolean checkInputConnectionProxy(View view) { 10660 return false; 10661 } 10662 10663 /** 10664 * Show the context menu for this view. It is not safe to hold on to the 10665 * menu after returning from this method. 10666 * 10667 * You should normally not overload this method. Overload 10668 * {@link #onCreateContextMenu(ContextMenu)} or define an 10669 * {@link OnCreateContextMenuListener} to add items to the context menu. 10670 * 10671 * @param menu The context menu to populate 10672 */ 10673 public void createContextMenu(ContextMenu menu) { 10674 ContextMenuInfo menuInfo = getContextMenuInfo(); 10675 10676 // Sets the current menu info so all items added to menu will have 10677 // my extra info set. 10678 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10679 10680 onCreateContextMenu(menu); 10681 ListenerInfo li = mListenerInfo; 10682 if (li != null && li.mOnCreateContextMenuListener != null) { 10683 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10684 } 10685 10686 // Clear the extra information so subsequent items that aren't mine don't 10687 // have my extra info. 10688 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10689 10690 if (mParent != null) { 10691 mParent.createContextMenu(menu); 10692 } 10693 } 10694 10695 /** 10696 * Views should implement this if they have extra information to associate 10697 * with the context menu. The return result is supplied as a parameter to 10698 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10699 * callback. 10700 * 10701 * @return Extra information about the item for which the context menu 10702 * should be shown. This information will vary across different 10703 * subclasses of View. 10704 */ 10705 protected ContextMenuInfo getContextMenuInfo() { 10706 return null; 10707 } 10708 10709 /** 10710 * Views should implement this if the view itself is going to add items to 10711 * the context menu. 10712 * 10713 * @param menu the context menu to populate 10714 */ 10715 protected void onCreateContextMenu(ContextMenu menu) { 10716 } 10717 10718 /** 10719 * Implement this method to handle trackball motion events. The 10720 * <em>relative</em> movement of the trackball since the last event 10721 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10722 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10723 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10724 * they will often be fractional values, representing the more fine-grained 10725 * movement information available from a trackball). 10726 * 10727 * @param event The motion event. 10728 * @return True if the event was handled, false otherwise. 10729 */ 10730 public boolean onTrackballEvent(MotionEvent event) { 10731 return false; 10732 } 10733 10734 /** 10735 * Implement this method to handle generic motion events. 10736 * <p> 10737 * Generic motion events describe joystick movements, mouse hovers, track pad 10738 * touches, scroll wheel movements and other input events. The 10739 * {@link MotionEvent#getSource() source} of the motion event specifies 10740 * the class of input that was received. Implementations of this method 10741 * must examine the bits in the source before processing the event. 10742 * The following code example shows how this is done. 10743 * </p><p> 10744 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10745 * are delivered to the view under the pointer. All other generic motion events are 10746 * delivered to the focused view. 10747 * </p> 10748 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10749 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10750 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10751 * // process the joystick movement... 10752 * return true; 10753 * } 10754 * } 10755 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10756 * switch (event.getAction()) { 10757 * case MotionEvent.ACTION_HOVER_MOVE: 10758 * // process the mouse hover movement... 10759 * return true; 10760 * case MotionEvent.ACTION_SCROLL: 10761 * // process the scroll wheel movement... 10762 * return true; 10763 * } 10764 * } 10765 * return super.onGenericMotionEvent(event); 10766 * }</pre> 10767 * 10768 * @param event The generic motion event being processed. 10769 * @return True if the event was handled, false otherwise. 10770 */ 10771 public boolean onGenericMotionEvent(MotionEvent event) { 10772 return false; 10773 } 10774 10775 /** 10776 * Implement this method to handle hover events. 10777 * <p> 10778 * This method is called whenever a pointer is hovering into, over, or out of the 10779 * bounds of a view and the view is not currently being touched. 10780 * Hover events are represented as pointer events with action 10781 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10782 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10783 * </p> 10784 * <ul> 10785 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10786 * when the pointer enters the bounds of the view.</li> 10787 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10788 * when the pointer has already entered the bounds of the view and has moved.</li> 10789 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10790 * when the pointer has exited the bounds of the view or when the pointer is 10791 * about to go down due to a button click, tap, or similar user action that 10792 * causes the view to be touched.</li> 10793 * </ul> 10794 * <p> 10795 * The view should implement this method to return true to indicate that it is 10796 * handling the hover event, such as by changing its drawable state. 10797 * </p><p> 10798 * The default implementation calls {@link #setHovered} to update the hovered state 10799 * of the view when a hover enter or hover exit event is received, if the view 10800 * is enabled and is clickable. The default implementation also sends hover 10801 * accessibility events. 10802 * </p> 10803 * 10804 * @param event The motion event that describes the hover. 10805 * @return True if the view handled the hover event. 10806 * 10807 * @see #isHovered 10808 * @see #setHovered 10809 * @see #onHoverChanged 10810 */ 10811 public boolean onHoverEvent(MotionEvent event) { 10812 // The root view may receive hover (or touch) events that are outside the bounds of 10813 // the window. This code ensures that we only send accessibility events for 10814 // hovers that are actually within the bounds of the root view. 10815 final int action = event.getActionMasked(); 10816 if (!mSendingHoverAccessibilityEvents) { 10817 if ((action == MotionEvent.ACTION_HOVER_ENTER 10818 || action == MotionEvent.ACTION_HOVER_MOVE) 10819 && !hasHoveredChild() 10820 && pointInView(event.getX(), event.getY())) { 10821 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10822 mSendingHoverAccessibilityEvents = true; 10823 } 10824 } else { 10825 if (action == MotionEvent.ACTION_HOVER_EXIT 10826 || (action == MotionEvent.ACTION_MOVE 10827 && !pointInView(event.getX(), event.getY()))) { 10828 mSendingHoverAccessibilityEvents = false; 10829 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10830 } 10831 } 10832 10833 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10834 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10835 && isOnScrollbar(event.getX(), event.getY())) { 10836 awakenScrollBars(); 10837 } 10838 if (isHoverable()) { 10839 switch (action) { 10840 case MotionEvent.ACTION_HOVER_ENTER: 10841 setHovered(true); 10842 break; 10843 case MotionEvent.ACTION_HOVER_EXIT: 10844 setHovered(false); 10845 break; 10846 } 10847 10848 // Dispatch the event to onGenericMotionEvent before returning true. 10849 // This is to provide compatibility with existing applications that 10850 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10851 // break because of the new default handling for hoverable views 10852 // in onHoverEvent. 10853 // Note that onGenericMotionEvent will be called by default when 10854 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10855 dispatchGenericMotionEventInternal(event); 10856 // The event was already handled by calling setHovered(), so always 10857 // return true. 10858 return true; 10859 } 10860 10861 return false; 10862 } 10863 10864 /** 10865 * Returns true if the view should handle {@link #onHoverEvent} 10866 * by calling {@link #setHovered} to change its hovered state. 10867 * 10868 * @return True if the view is hoverable. 10869 */ 10870 private boolean isHoverable() { 10871 final int viewFlags = mViewFlags; 10872 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10873 return false; 10874 } 10875 10876 return (viewFlags & CLICKABLE) == CLICKABLE 10877 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10878 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10879 } 10880 10881 /** 10882 * Returns true if the view is currently hovered. 10883 * 10884 * @return True if the view is currently hovered. 10885 * 10886 * @see #setHovered 10887 * @see #onHoverChanged 10888 */ 10889 @ViewDebug.ExportedProperty 10890 public boolean isHovered() { 10891 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10892 } 10893 10894 /** 10895 * Sets whether the view is currently hovered. 10896 * <p> 10897 * Calling this method also changes the drawable state of the view. This 10898 * enables the view to react to hover by using different drawable resources 10899 * to change its appearance. 10900 * </p><p> 10901 * The {@link #onHoverChanged} method is called when the hovered state changes. 10902 * </p> 10903 * 10904 * @param hovered True if the view is hovered. 10905 * 10906 * @see #isHovered 10907 * @see #onHoverChanged 10908 */ 10909 public void setHovered(boolean hovered) { 10910 if (hovered) { 10911 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10912 mPrivateFlags |= PFLAG_HOVERED; 10913 refreshDrawableState(); 10914 onHoverChanged(true); 10915 } 10916 } else { 10917 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10918 mPrivateFlags &= ~PFLAG_HOVERED; 10919 refreshDrawableState(); 10920 onHoverChanged(false); 10921 } 10922 } 10923 } 10924 10925 /** 10926 * Implement this method to handle hover state changes. 10927 * <p> 10928 * This method is called whenever the hover state changes as a result of a 10929 * call to {@link #setHovered}. 10930 * </p> 10931 * 10932 * @param hovered The current hover state, as returned by {@link #isHovered}. 10933 * 10934 * @see #isHovered 10935 * @see #setHovered 10936 */ 10937 public void onHoverChanged(boolean hovered) { 10938 } 10939 10940 /** 10941 * Handles scroll bar dragging by mouse input. 10942 * 10943 * @hide 10944 * @param event The motion event. 10945 * 10946 * @return true if the event was handled as a scroll bar dragging, false otherwise. 10947 */ 10948 protected boolean handleScrollBarDragging(MotionEvent event) { 10949 if (mScrollCache == null) { 10950 return false; 10951 } 10952 final float x = event.getX(); 10953 final float y = event.getY(); 10954 final int action = event.getAction(); 10955 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 10956 && action != MotionEvent.ACTION_DOWN) 10957 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 10958 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 10959 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10960 return false; 10961 } 10962 10963 switch (action) { 10964 case MotionEvent.ACTION_MOVE: 10965 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 10966 return false; 10967 } 10968 if (mScrollCache.mScrollBarDraggingState 10969 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 10970 final Rect bounds = mScrollCache.mScrollBarBounds; 10971 getVerticalScrollBarBounds(bounds); 10972 final int range = computeVerticalScrollRange(); 10973 final int offset = computeVerticalScrollOffset(); 10974 final int extent = computeVerticalScrollExtent(); 10975 10976 final int thumbLength = ScrollBarUtils.getThumbLength( 10977 bounds.height(), bounds.width(), extent, range); 10978 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10979 bounds.height(), thumbLength, extent, range, offset); 10980 10981 final float diff = y - mScrollCache.mScrollBarDraggingPos; 10982 final float maxThumbOffset = bounds.height() - thumbLength; 10983 final float newThumbOffset = 10984 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10985 final int height = getHeight(); 10986 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10987 && height > 0 && extent > 0) { 10988 final int newY = Math.round((range - extent) 10989 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 10990 if (newY != getScrollY()) { 10991 mScrollCache.mScrollBarDraggingPos = y; 10992 setScrollY(newY); 10993 } 10994 } 10995 return true; 10996 } 10997 if (mScrollCache.mScrollBarDraggingState 10998 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 10999 final Rect bounds = mScrollCache.mScrollBarBounds; 11000 getHorizontalScrollBarBounds(bounds); 11001 final int range = computeHorizontalScrollRange(); 11002 final int offset = computeHorizontalScrollOffset(); 11003 final int extent = computeHorizontalScrollExtent(); 11004 11005 final int thumbLength = ScrollBarUtils.getThumbLength( 11006 bounds.width(), bounds.height(), extent, range); 11007 final int thumbOffset = ScrollBarUtils.getThumbOffset( 11008 bounds.width(), thumbLength, extent, range, offset); 11009 11010 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11011 final float maxThumbOffset = bounds.width() - thumbLength; 11012 final float newThumbOffset = 11013 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11014 final int width = getWidth(); 11015 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11016 && width > 0 && extent > 0) { 11017 final int newX = Math.round((range - extent) 11018 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11019 if (newX != getScrollX()) { 11020 mScrollCache.mScrollBarDraggingPos = x; 11021 setScrollX(newX); 11022 } 11023 } 11024 return true; 11025 } 11026 case MotionEvent.ACTION_DOWN: 11027 if (mScrollCache.state == ScrollabilityCache.OFF) { 11028 return false; 11029 } 11030 if (isOnVerticalScrollbarThumb(x, y)) { 11031 mScrollCache.mScrollBarDraggingState = 11032 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11033 mScrollCache.mScrollBarDraggingPos = y; 11034 return true; 11035 } 11036 if (isOnHorizontalScrollbarThumb(x, y)) { 11037 mScrollCache.mScrollBarDraggingState = 11038 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11039 mScrollCache.mScrollBarDraggingPos = x; 11040 return true; 11041 } 11042 } 11043 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11044 return false; 11045 } 11046 11047 /** 11048 * Implement this method to handle touch screen motion events. 11049 * <p> 11050 * If this method is used to detect click actions, it is recommended that 11051 * the actions be performed by implementing and calling 11052 * {@link #performClick()}. This will ensure consistent system behavior, 11053 * including: 11054 * <ul> 11055 * <li>obeying click sound preferences 11056 * <li>dispatching OnClickListener calls 11057 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11058 * accessibility features are enabled 11059 * </ul> 11060 * 11061 * @param event The motion event. 11062 * @return True if the event was handled, false otherwise. 11063 */ 11064 public boolean onTouchEvent(MotionEvent event) { 11065 final float x = event.getX(); 11066 final float y = event.getY(); 11067 final int viewFlags = mViewFlags; 11068 final int action = event.getAction(); 11069 11070 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11071 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11072 setPressed(false); 11073 } 11074 // A disabled view that is clickable still consumes the touch 11075 // events, it just doesn't respond to them. 11076 return (((viewFlags & CLICKABLE) == CLICKABLE 11077 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11078 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11079 } 11080 if (mTouchDelegate != null) { 11081 if (mTouchDelegate.onTouchEvent(event)) { 11082 return true; 11083 } 11084 } 11085 11086 if (((viewFlags & CLICKABLE) == CLICKABLE || 11087 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11088 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11089 switch (action) { 11090 case MotionEvent.ACTION_UP: 11091 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11092 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11093 // take focus if we don't have it already and we should in 11094 // touch mode. 11095 boolean focusTaken = false; 11096 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11097 focusTaken = requestFocus(); 11098 } 11099 11100 if (prepressed) { 11101 // The button is being released before we actually 11102 // showed it as pressed. Make it show the pressed 11103 // state now (before scheduling the click) to ensure 11104 // the user sees it. 11105 setPressed(true, x, y); 11106 } 11107 11108 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11109 // This is a tap, so remove the longpress check 11110 removeLongPressCallback(); 11111 11112 // Only perform take click actions if we were in the pressed state 11113 if (!focusTaken) { 11114 // Use a Runnable and post this rather than calling 11115 // performClick directly. This lets other visual state 11116 // of the view update before click actions start. 11117 if (mPerformClick == null) { 11118 mPerformClick = new PerformClick(); 11119 } 11120 if (!post(mPerformClick)) { 11121 performClick(); 11122 } 11123 } 11124 } 11125 11126 if (mUnsetPressedState == null) { 11127 mUnsetPressedState = new UnsetPressedState(); 11128 } 11129 11130 if (prepressed) { 11131 postDelayed(mUnsetPressedState, 11132 ViewConfiguration.getPressedStateDuration()); 11133 } else if (!post(mUnsetPressedState)) { 11134 // If the post failed, unpress right now 11135 mUnsetPressedState.run(); 11136 } 11137 11138 removeTapCallback(); 11139 } 11140 mIgnoreNextUpEvent = false; 11141 break; 11142 11143 case MotionEvent.ACTION_DOWN: 11144 mHasPerformedLongPress = false; 11145 11146 if (performButtonActionOnTouchDown(event)) { 11147 break; 11148 } 11149 11150 // Walk up the hierarchy to determine if we're inside a scrolling container. 11151 boolean isInScrollingContainer = isInScrollingContainer(); 11152 11153 // For views inside a scrolling container, delay the pressed feedback for 11154 // a short period in case this is a scroll. 11155 if (isInScrollingContainer) { 11156 mPrivateFlags |= PFLAG_PREPRESSED; 11157 if (mPendingCheckForTap == null) { 11158 mPendingCheckForTap = new CheckForTap(); 11159 } 11160 mPendingCheckForTap.x = event.getX(); 11161 mPendingCheckForTap.y = event.getY(); 11162 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11163 } else { 11164 // Not inside a scrolling container, so show the feedback right away 11165 setPressed(true, x, y); 11166 checkForLongClick(0, x, y); 11167 } 11168 break; 11169 11170 case MotionEvent.ACTION_CANCEL: 11171 setPressed(false); 11172 removeTapCallback(); 11173 removeLongPressCallback(); 11174 mInContextButtonPress = false; 11175 mHasPerformedLongPress = false; 11176 mIgnoreNextUpEvent = false; 11177 break; 11178 11179 case MotionEvent.ACTION_MOVE: 11180 drawableHotspotChanged(x, y); 11181 11182 // Be lenient about moving outside of buttons 11183 if (!pointInView(x, y, mTouchSlop)) { 11184 // Outside button 11185 removeTapCallback(); 11186 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11187 // Remove any future long press/tap checks 11188 removeLongPressCallback(); 11189 11190 setPressed(false); 11191 } 11192 } 11193 break; 11194 } 11195 11196 return true; 11197 } 11198 11199 return false; 11200 } 11201 11202 /** 11203 * @hide 11204 */ 11205 public boolean isInScrollingContainer() { 11206 ViewParent p = getParent(); 11207 while (p != null && p instanceof ViewGroup) { 11208 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11209 return true; 11210 } 11211 p = p.getParent(); 11212 } 11213 return false; 11214 } 11215 11216 /** 11217 * Remove the longpress detection timer. 11218 */ 11219 private void removeLongPressCallback() { 11220 if (mPendingCheckForLongPress != null) { 11221 removeCallbacks(mPendingCheckForLongPress); 11222 } 11223 } 11224 11225 /** 11226 * Remove the pending click action 11227 */ 11228 private void removePerformClickCallback() { 11229 if (mPerformClick != null) { 11230 removeCallbacks(mPerformClick); 11231 } 11232 } 11233 11234 /** 11235 * Remove the prepress detection timer. 11236 */ 11237 private void removeUnsetPressCallback() { 11238 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11239 setPressed(false); 11240 removeCallbacks(mUnsetPressedState); 11241 } 11242 } 11243 11244 /** 11245 * Remove the tap detection timer. 11246 */ 11247 private void removeTapCallback() { 11248 if (mPendingCheckForTap != null) { 11249 mPrivateFlags &= ~PFLAG_PREPRESSED; 11250 removeCallbacks(mPendingCheckForTap); 11251 } 11252 } 11253 11254 /** 11255 * Cancels a pending long press. Your subclass can use this if you 11256 * want the context menu to come up if the user presses and holds 11257 * at the same place, but you don't want it to come up if they press 11258 * and then move around enough to cause scrolling. 11259 */ 11260 public void cancelLongPress() { 11261 removeLongPressCallback(); 11262 11263 /* 11264 * The prepressed state handled by the tap callback is a display 11265 * construct, but the tap callback will post a long press callback 11266 * less its own timeout. Remove it here. 11267 */ 11268 removeTapCallback(); 11269 } 11270 11271 /** 11272 * Remove the pending callback for sending a 11273 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11274 */ 11275 private void removeSendViewScrolledAccessibilityEventCallback() { 11276 if (mSendViewScrolledAccessibilityEvent != null) { 11277 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11278 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11279 } 11280 } 11281 11282 /** 11283 * Sets the TouchDelegate for this View. 11284 */ 11285 public void setTouchDelegate(TouchDelegate delegate) { 11286 mTouchDelegate = delegate; 11287 } 11288 11289 /** 11290 * Gets the TouchDelegate for this View. 11291 */ 11292 public TouchDelegate getTouchDelegate() { 11293 return mTouchDelegate; 11294 } 11295 11296 /** 11297 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11298 * 11299 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11300 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11301 * available. This method should only be called for touch events. 11302 * 11303 * <p class="note">This api is not intended for most applications. Buffered dispatch 11304 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11305 * streams will not improve your input latency. Side effects include: increased latency, 11306 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11307 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11308 * you.</p> 11309 */ 11310 public final void requestUnbufferedDispatch(MotionEvent event) { 11311 final int action = event.getAction(); 11312 if (mAttachInfo == null 11313 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11314 || !event.isTouchEvent()) { 11315 return; 11316 } 11317 mAttachInfo.mUnbufferedDispatchRequested = true; 11318 } 11319 11320 /** 11321 * Set flags controlling behavior of this view. 11322 * 11323 * @param flags Constant indicating the value which should be set 11324 * @param mask Constant indicating the bit range that should be changed 11325 */ 11326 void setFlags(int flags, int mask) { 11327 final boolean accessibilityEnabled = 11328 AccessibilityManager.getInstance(mContext).isEnabled(); 11329 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11330 11331 int old = mViewFlags; 11332 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11333 11334 int changed = mViewFlags ^ old; 11335 if (changed == 0) { 11336 return; 11337 } 11338 int privateFlags = mPrivateFlags; 11339 11340 /* Check if the FOCUSABLE bit has changed */ 11341 if (((changed & FOCUSABLE_MASK) != 0) && 11342 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11343 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11344 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11345 /* Give up focus if we are no longer focusable */ 11346 clearFocus(); 11347 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11348 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11349 /* 11350 * Tell the view system that we are now available to take focus 11351 * if no one else already has it. 11352 */ 11353 if (mParent != null) mParent.focusableViewAvailable(this); 11354 } 11355 } 11356 11357 final int newVisibility = flags & VISIBILITY_MASK; 11358 if (newVisibility == VISIBLE) { 11359 if ((changed & VISIBILITY_MASK) != 0) { 11360 /* 11361 * If this view is becoming visible, invalidate it in case it changed while 11362 * it was not visible. Marking it drawn ensures that the invalidation will 11363 * go through. 11364 */ 11365 mPrivateFlags |= PFLAG_DRAWN; 11366 invalidate(true); 11367 11368 needGlobalAttributesUpdate(true); 11369 11370 // a view becoming visible is worth notifying the parent 11371 // about in case nothing has focus. even if this specific view 11372 // isn't focusable, it may contain something that is, so let 11373 // the root view try to give this focus if nothing else does. 11374 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11375 mParent.focusableViewAvailable(this); 11376 } 11377 } 11378 } 11379 11380 /* Check if the GONE bit has changed */ 11381 if ((changed & GONE) != 0) { 11382 needGlobalAttributesUpdate(false); 11383 requestLayout(); 11384 11385 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11386 if (hasFocus()) clearFocus(); 11387 clearAccessibilityFocus(); 11388 destroyDrawingCache(); 11389 if (mParent instanceof View) { 11390 // GONE views noop invalidation, so invalidate the parent 11391 ((View) mParent).invalidate(true); 11392 } 11393 // Mark the view drawn to ensure that it gets invalidated properly the next 11394 // time it is visible and gets invalidated 11395 mPrivateFlags |= PFLAG_DRAWN; 11396 } 11397 if (mAttachInfo != null) { 11398 mAttachInfo.mViewVisibilityChanged = true; 11399 } 11400 } 11401 11402 /* Check if the VISIBLE bit has changed */ 11403 if ((changed & INVISIBLE) != 0) { 11404 needGlobalAttributesUpdate(false); 11405 /* 11406 * If this view is becoming invisible, set the DRAWN flag so that 11407 * the next invalidate() will not be skipped. 11408 */ 11409 mPrivateFlags |= PFLAG_DRAWN; 11410 11411 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11412 // root view becoming invisible shouldn't clear focus and accessibility focus 11413 if (getRootView() != this) { 11414 if (hasFocus()) clearFocus(); 11415 clearAccessibilityFocus(); 11416 } 11417 } 11418 if (mAttachInfo != null) { 11419 mAttachInfo.mViewVisibilityChanged = true; 11420 } 11421 } 11422 11423 if ((changed & VISIBILITY_MASK) != 0) { 11424 // If the view is invisible, cleanup its display list to free up resources 11425 if (newVisibility != VISIBLE && mAttachInfo != null) { 11426 cleanupDraw(); 11427 } 11428 11429 if (mParent instanceof ViewGroup) { 11430 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11431 (changed & VISIBILITY_MASK), newVisibility); 11432 ((View) mParent).invalidate(true); 11433 } else if (mParent != null) { 11434 mParent.invalidateChild(this, null); 11435 } 11436 11437 if (mAttachInfo != null) { 11438 dispatchVisibilityChanged(this, newVisibility); 11439 11440 // Aggregated visibility changes are dispatched to attached views 11441 // in visible windows where the parent is currently shown/drawn 11442 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11443 // discounting clipping or overlapping. This makes it a good place 11444 // to change animation states. 11445 if (mParent != null && getWindowVisibility() == VISIBLE && 11446 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11447 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11448 } 11449 notifySubtreeAccessibilityStateChangedIfNeeded(); 11450 } 11451 } 11452 11453 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11454 destroyDrawingCache(); 11455 } 11456 11457 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11458 destroyDrawingCache(); 11459 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11460 invalidateParentCaches(); 11461 } 11462 11463 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11464 destroyDrawingCache(); 11465 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11466 } 11467 11468 if ((changed & DRAW_MASK) != 0) { 11469 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11470 if (mBackground != null 11471 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11472 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11473 } else { 11474 mPrivateFlags |= PFLAG_SKIP_DRAW; 11475 } 11476 } else { 11477 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11478 } 11479 requestLayout(); 11480 invalidate(true); 11481 } 11482 11483 if ((changed & KEEP_SCREEN_ON) != 0) { 11484 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11485 mParent.recomputeViewAttributes(this); 11486 } 11487 } 11488 11489 if (accessibilityEnabled) { 11490 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11491 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11492 || (changed & CONTEXT_CLICKABLE) != 0) { 11493 if (oldIncludeForAccessibility != includeForAccessibility()) { 11494 notifySubtreeAccessibilityStateChangedIfNeeded(); 11495 } else { 11496 notifyViewAccessibilityStateChangedIfNeeded( 11497 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11498 } 11499 } else if ((changed & ENABLED_MASK) != 0) { 11500 notifyViewAccessibilityStateChangedIfNeeded( 11501 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11502 } 11503 } 11504 } 11505 11506 /** 11507 * Change the view's z order in the tree, so it's on top of other sibling 11508 * views. This ordering change may affect layout, if the parent container 11509 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11510 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11511 * method should be followed by calls to {@link #requestLayout()} and 11512 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11513 * with the new child ordering. 11514 * 11515 * @see ViewGroup#bringChildToFront(View) 11516 */ 11517 public void bringToFront() { 11518 if (mParent != null) { 11519 mParent.bringChildToFront(this); 11520 } 11521 } 11522 11523 /** 11524 * This is called in response to an internal scroll in this view (i.e., the 11525 * view scrolled its own contents). This is typically as a result of 11526 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11527 * called. 11528 * 11529 * @param l Current horizontal scroll origin. 11530 * @param t Current vertical scroll origin. 11531 * @param oldl Previous horizontal scroll origin. 11532 * @param oldt Previous vertical scroll origin. 11533 */ 11534 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11535 notifySubtreeAccessibilityStateChangedIfNeeded(); 11536 11537 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11538 postSendViewScrolledAccessibilityEventCallback(); 11539 } 11540 11541 mBackgroundSizeChanged = true; 11542 if (mForegroundInfo != null) { 11543 mForegroundInfo.mBoundsChanged = true; 11544 } 11545 11546 final AttachInfo ai = mAttachInfo; 11547 if (ai != null) { 11548 ai.mViewScrollChanged = true; 11549 } 11550 11551 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11552 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11553 } 11554 } 11555 11556 /** 11557 * Interface definition for a callback to be invoked when the scroll 11558 * X or Y positions of a view change. 11559 * <p> 11560 * <b>Note:</b> Some views handle scrolling independently from View and may 11561 * have their own separate listeners for scroll-type events. For example, 11562 * {@link android.widget.ListView ListView} allows clients to register an 11563 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11564 * to listen for changes in list scroll position. 11565 * 11566 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11567 */ 11568 public interface OnScrollChangeListener { 11569 /** 11570 * Called when the scroll position of a view changes. 11571 * 11572 * @param v The view whose scroll position has changed. 11573 * @param scrollX Current horizontal scroll origin. 11574 * @param scrollY Current vertical scroll origin. 11575 * @param oldScrollX Previous horizontal scroll origin. 11576 * @param oldScrollY Previous vertical scroll origin. 11577 */ 11578 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11579 } 11580 11581 /** 11582 * Interface definition for a callback to be invoked when the layout bounds of a view 11583 * changes due to layout processing. 11584 */ 11585 public interface OnLayoutChangeListener { 11586 /** 11587 * Called when the layout bounds of a view changes due to layout processing. 11588 * 11589 * @param v The view whose bounds have changed. 11590 * @param left The new value of the view's left property. 11591 * @param top The new value of the view's top property. 11592 * @param right The new value of the view's right property. 11593 * @param bottom The new value of the view's bottom property. 11594 * @param oldLeft The previous value of the view's left property. 11595 * @param oldTop The previous value of the view's top property. 11596 * @param oldRight The previous value of the view's right property. 11597 * @param oldBottom The previous value of the view's bottom property. 11598 */ 11599 void onLayoutChange(View v, int left, int top, int right, int bottom, 11600 int oldLeft, int oldTop, int oldRight, int oldBottom); 11601 } 11602 11603 /** 11604 * This is called during layout when the size of this view has changed. If 11605 * you were just added to the view hierarchy, you're called with the old 11606 * values of 0. 11607 * 11608 * @param w Current width of this view. 11609 * @param h Current height of this view. 11610 * @param oldw Old width of this view. 11611 * @param oldh Old height of this view. 11612 */ 11613 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11614 } 11615 11616 /** 11617 * Called by draw to draw the child views. This may be overridden 11618 * by derived classes to gain control just before its children are drawn 11619 * (but after its own view has been drawn). 11620 * @param canvas the canvas on which to draw the view 11621 */ 11622 protected void dispatchDraw(Canvas canvas) { 11623 11624 } 11625 11626 /** 11627 * Gets the parent of this view. Note that the parent is a 11628 * ViewParent and not necessarily a View. 11629 * 11630 * @return Parent of this view. 11631 */ 11632 public final ViewParent getParent() { 11633 return mParent; 11634 } 11635 11636 /** 11637 * Set the horizontal scrolled position of your view. This will cause a call to 11638 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11639 * invalidated. 11640 * @param value the x position to scroll to 11641 */ 11642 public void setScrollX(int value) { 11643 scrollTo(value, mScrollY); 11644 } 11645 11646 /** 11647 * Set the vertical scrolled position of your view. This will cause a call to 11648 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11649 * invalidated. 11650 * @param value the y position to scroll to 11651 */ 11652 public void setScrollY(int value) { 11653 scrollTo(mScrollX, value); 11654 } 11655 11656 /** 11657 * Return the scrolled left position of this view. This is the left edge of 11658 * the displayed part of your view. You do not need to draw any pixels 11659 * farther left, since those are outside of the frame of your view on 11660 * screen. 11661 * 11662 * @return The left edge of the displayed part of your view, in pixels. 11663 */ 11664 public final int getScrollX() { 11665 return mScrollX; 11666 } 11667 11668 /** 11669 * Return the scrolled top position of this view. This is the top edge of 11670 * the displayed part of your view. You do not need to draw any pixels above 11671 * it, since those are outside of the frame of your view on screen. 11672 * 11673 * @return The top edge of the displayed part of your view, in pixels. 11674 */ 11675 public final int getScrollY() { 11676 return mScrollY; 11677 } 11678 11679 /** 11680 * Return the width of the your view. 11681 * 11682 * @return The width of your view, in pixels. 11683 */ 11684 @ViewDebug.ExportedProperty(category = "layout") 11685 public final int getWidth() { 11686 return mRight - mLeft; 11687 } 11688 11689 /** 11690 * Return the height of your view. 11691 * 11692 * @return The height of your view, in pixels. 11693 */ 11694 @ViewDebug.ExportedProperty(category = "layout") 11695 public final int getHeight() { 11696 return mBottom - mTop; 11697 } 11698 11699 /** 11700 * Return the visible drawing bounds of your view. Fills in the output 11701 * rectangle with the values from getScrollX(), getScrollY(), 11702 * getWidth(), and getHeight(). These bounds do not account for any 11703 * transformation properties currently set on the view, such as 11704 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11705 * 11706 * @param outRect The (scrolled) drawing bounds of the view. 11707 */ 11708 public void getDrawingRect(Rect outRect) { 11709 outRect.left = mScrollX; 11710 outRect.top = mScrollY; 11711 outRect.right = mScrollX + (mRight - mLeft); 11712 outRect.bottom = mScrollY + (mBottom - mTop); 11713 } 11714 11715 /** 11716 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11717 * raw width component (that is the result is masked by 11718 * {@link #MEASURED_SIZE_MASK}). 11719 * 11720 * @return The raw measured width of this view. 11721 */ 11722 public final int getMeasuredWidth() { 11723 return mMeasuredWidth & MEASURED_SIZE_MASK; 11724 } 11725 11726 /** 11727 * Return the full width measurement information for this view as computed 11728 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11729 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11730 * This should be used during measurement and layout calculations only. Use 11731 * {@link #getWidth()} to see how wide a view is after layout. 11732 * 11733 * @return The measured width of this view as a bit mask. 11734 */ 11735 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11736 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11737 name = "MEASURED_STATE_TOO_SMALL"), 11738 }) 11739 public final int getMeasuredWidthAndState() { 11740 return mMeasuredWidth; 11741 } 11742 11743 /** 11744 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11745 * raw width component (that is the result is masked by 11746 * {@link #MEASURED_SIZE_MASK}). 11747 * 11748 * @return The raw measured height of this view. 11749 */ 11750 public final int getMeasuredHeight() { 11751 return mMeasuredHeight & MEASURED_SIZE_MASK; 11752 } 11753 11754 /** 11755 * Return the full height measurement information for this view as computed 11756 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11757 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11758 * This should be used during measurement and layout calculations only. Use 11759 * {@link #getHeight()} to see how wide a view is after layout. 11760 * 11761 * @return The measured width of this view as a bit mask. 11762 */ 11763 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11764 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11765 name = "MEASURED_STATE_TOO_SMALL"), 11766 }) 11767 public final int getMeasuredHeightAndState() { 11768 return mMeasuredHeight; 11769 } 11770 11771 /** 11772 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11773 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11774 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11775 * and the height component is at the shifted bits 11776 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11777 */ 11778 public final int getMeasuredState() { 11779 return (mMeasuredWidth&MEASURED_STATE_MASK) 11780 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11781 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11782 } 11783 11784 /** 11785 * The transform matrix of this view, which is calculated based on the current 11786 * rotation, scale, and pivot properties. 11787 * 11788 * @see #getRotation() 11789 * @see #getScaleX() 11790 * @see #getScaleY() 11791 * @see #getPivotX() 11792 * @see #getPivotY() 11793 * @return The current transform matrix for the view 11794 */ 11795 public Matrix getMatrix() { 11796 ensureTransformationInfo(); 11797 final Matrix matrix = mTransformationInfo.mMatrix; 11798 mRenderNode.getMatrix(matrix); 11799 return matrix; 11800 } 11801 11802 /** 11803 * Returns true if the transform matrix is the identity matrix. 11804 * Recomputes the matrix if necessary. 11805 * 11806 * @return True if the transform matrix is the identity matrix, false otherwise. 11807 */ 11808 final boolean hasIdentityMatrix() { 11809 return mRenderNode.hasIdentityMatrix(); 11810 } 11811 11812 void ensureTransformationInfo() { 11813 if (mTransformationInfo == null) { 11814 mTransformationInfo = new TransformationInfo(); 11815 } 11816 } 11817 11818 /** 11819 * Utility method to retrieve the inverse of the current mMatrix property. 11820 * We cache the matrix to avoid recalculating it when transform properties 11821 * have not changed. 11822 * 11823 * @return The inverse of the current matrix of this view. 11824 * @hide 11825 */ 11826 public final Matrix getInverseMatrix() { 11827 ensureTransformationInfo(); 11828 if (mTransformationInfo.mInverseMatrix == null) { 11829 mTransformationInfo.mInverseMatrix = new Matrix(); 11830 } 11831 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11832 mRenderNode.getInverseMatrix(matrix); 11833 return matrix; 11834 } 11835 11836 /** 11837 * Gets the distance along the Z axis from the camera to this view. 11838 * 11839 * @see #setCameraDistance(float) 11840 * 11841 * @return The distance along the Z axis. 11842 */ 11843 public float getCameraDistance() { 11844 final float dpi = mResources.getDisplayMetrics().densityDpi; 11845 return -(mRenderNode.getCameraDistance() * dpi); 11846 } 11847 11848 /** 11849 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11850 * views are drawn) from the camera to this view. The camera's distance 11851 * affects 3D transformations, for instance rotations around the X and Y 11852 * axis. If the rotationX or rotationY properties are changed and this view is 11853 * large (more than half the size of the screen), it is recommended to always 11854 * use a camera distance that's greater than the height (X axis rotation) or 11855 * the width (Y axis rotation) of this view.</p> 11856 * 11857 * <p>The distance of the camera from the view plane can have an affect on the 11858 * perspective distortion of the view when it is rotated around the x or y axis. 11859 * For example, a large distance will result in a large viewing angle, and there 11860 * will not be much perspective distortion of the view as it rotates. A short 11861 * distance may cause much more perspective distortion upon rotation, and can 11862 * also result in some drawing artifacts if the rotated view ends up partially 11863 * behind the camera (which is why the recommendation is to use a distance at 11864 * least as far as the size of the view, if the view is to be rotated.)</p> 11865 * 11866 * <p>The distance is expressed in "depth pixels." The default distance depends 11867 * on the screen density. For instance, on a medium density display, the 11868 * default distance is 1280. On a high density display, the default distance 11869 * is 1920.</p> 11870 * 11871 * <p>If you want to specify a distance that leads to visually consistent 11872 * results across various densities, use the following formula:</p> 11873 * <pre> 11874 * float scale = context.getResources().getDisplayMetrics().density; 11875 * view.setCameraDistance(distance * scale); 11876 * </pre> 11877 * 11878 * <p>The density scale factor of a high density display is 1.5, 11879 * and 1920 = 1280 * 1.5.</p> 11880 * 11881 * @param distance The distance in "depth pixels", if negative the opposite 11882 * value is used 11883 * 11884 * @see #setRotationX(float) 11885 * @see #setRotationY(float) 11886 */ 11887 public void setCameraDistance(float distance) { 11888 final float dpi = mResources.getDisplayMetrics().densityDpi; 11889 11890 invalidateViewProperty(true, false); 11891 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11892 invalidateViewProperty(false, false); 11893 11894 invalidateParentIfNeededAndWasQuickRejected(); 11895 } 11896 11897 /** 11898 * The degrees that the view is rotated around the pivot point. 11899 * 11900 * @see #setRotation(float) 11901 * @see #getPivotX() 11902 * @see #getPivotY() 11903 * 11904 * @return The degrees of rotation. 11905 */ 11906 @ViewDebug.ExportedProperty(category = "drawing") 11907 public float getRotation() { 11908 return mRenderNode.getRotation(); 11909 } 11910 11911 /** 11912 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11913 * result in clockwise rotation. 11914 * 11915 * @param rotation The degrees of rotation. 11916 * 11917 * @see #getRotation() 11918 * @see #getPivotX() 11919 * @see #getPivotY() 11920 * @see #setRotationX(float) 11921 * @see #setRotationY(float) 11922 * 11923 * @attr ref android.R.styleable#View_rotation 11924 */ 11925 public void setRotation(float rotation) { 11926 if (rotation != getRotation()) { 11927 // Double-invalidation is necessary to capture view's old and new areas 11928 invalidateViewProperty(true, false); 11929 mRenderNode.setRotation(rotation); 11930 invalidateViewProperty(false, true); 11931 11932 invalidateParentIfNeededAndWasQuickRejected(); 11933 notifySubtreeAccessibilityStateChangedIfNeeded(); 11934 } 11935 } 11936 11937 /** 11938 * The degrees that the view is rotated around the vertical axis through the pivot point. 11939 * 11940 * @see #getPivotX() 11941 * @see #getPivotY() 11942 * @see #setRotationY(float) 11943 * 11944 * @return The degrees of Y rotation. 11945 */ 11946 @ViewDebug.ExportedProperty(category = "drawing") 11947 public float getRotationY() { 11948 return mRenderNode.getRotationY(); 11949 } 11950 11951 /** 11952 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11953 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11954 * down the y axis. 11955 * 11956 * When rotating large views, it is recommended to adjust the camera distance 11957 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11958 * 11959 * @param rotationY The degrees of Y rotation. 11960 * 11961 * @see #getRotationY() 11962 * @see #getPivotX() 11963 * @see #getPivotY() 11964 * @see #setRotation(float) 11965 * @see #setRotationX(float) 11966 * @see #setCameraDistance(float) 11967 * 11968 * @attr ref android.R.styleable#View_rotationY 11969 */ 11970 public void setRotationY(float rotationY) { 11971 if (rotationY != getRotationY()) { 11972 invalidateViewProperty(true, false); 11973 mRenderNode.setRotationY(rotationY); 11974 invalidateViewProperty(false, true); 11975 11976 invalidateParentIfNeededAndWasQuickRejected(); 11977 notifySubtreeAccessibilityStateChangedIfNeeded(); 11978 } 11979 } 11980 11981 /** 11982 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11983 * 11984 * @see #getPivotX() 11985 * @see #getPivotY() 11986 * @see #setRotationX(float) 11987 * 11988 * @return The degrees of X rotation. 11989 */ 11990 @ViewDebug.ExportedProperty(category = "drawing") 11991 public float getRotationX() { 11992 return mRenderNode.getRotationX(); 11993 } 11994 11995 /** 11996 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11997 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11998 * x axis. 11999 * 12000 * When rotating large views, it is recommended to adjust the camera distance 12001 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 12002 * 12003 * @param rotationX The degrees of X rotation. 12004 * 12005 * @see #getRotationX() 12006 * @see #getPivotX() 12007 * @see #getPivotY() 12008 * @see #setRotation(float) 12009 * @see #setRotationY(float) 12010 * @see #setCameraDistance(float) 12011 * 12012 * @attr ref android.R.styleable#View_rotationX 12013 */ 12014 public void setRotationX(float rotationX) { 12015 if (rotationX != getRotationX()) { 12016 invalidateViewProperty(true, false); 12017 mRenderNode.setRotationX(rotationX); 12018 invalidateViewProperty(false, true); 12019 12020 invalidateParentIfNeededAndWasQuickRejected(); 12021 notifySubtreeAccessibilityStateChangedIfNeeded(); 12022 } 12023 } 12024 12025 /** 12026 * The amount that the view is scaled in x around the pivot point, as a proportion of 12027 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12028 * 12029 * <p>By default, this is 1.0f. 12030 * 12031 * @see #getPivotX() 12032 * @see #getPivotY() 12033 * @return The scaling factor. 12034 */ 12035 @ViewDebug.ExportedProperty(category = "drawing") 12036 public float getScaleX() { 12037 return mRenderNode.getScaleX(); 12038 } 12039 12040 /** 12041 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12042 * the view's unscaled width. A value of 1 means that no scaling is applied. 12043 * 12044 * @param scaleX The scaling factor. 12045 * @see #getPivotX() 12046 * @see #getPivotY() 12047 * 12048 * @attr ref android.R.styleable#View_scaleX 12049 */ 12050 public void setScaleX(float scaleX) { 12051 if (scaleX != getScaleX()) { 12052 invalidateViewProperty(true, false); 12053 mRenderNode.setScaleX(scaleX); 12054 invalidateViewProperty(false, true); 12055 12056 invalidateParentIfNeededAndWasQuickRejected(); 12057 notifySubtreeAccessibilityStateChangedIfNeeded(); 12058 } 12059 } 12060 12061 /** 12062 * The amount that the view is scaled in y around the pivot point, as a proportion of 12063 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12064 * 12065 * <p>By default, this is 1.0f. 12066 * 12067 * @see #getPivotX() 12068 * @see #getPivotY() 12069 * @return The scaling factor. 12070 */ 12071 @ViewDebug.ExportedProperty(category = "drawing") 12072 public float getScaleY() { 12073 return mRenderNode.getScaleY(); 12074 } 12075 12076 /** 12077 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12078 * the view's unscaled width. A value of 1 means that no scaling is applied. 12079 * 12080 * @param scaleY The scaling factor. 12081 * @see #getPivotX() 12082 * @see #getPivotY() 12083 * 12084 * @attr ref android.R.styleable#View_scaleY 12085 */ 12086 public void setScaleY(float scaleY) { 12087 if (scaleY != getScaleY()) { 12088 invalidateViewProperty(true, false); 12089 mRenderNode.setScaleY(scaleY); 12090 invalidateViewProperty(false, true); 12091 12092 invalidateParentIfNeededAndWasQuickRejected(); 12093 notifySubtreeAccessibilityStateChangedIfNeeded(); 12094 } 12095 } 12096 12097 /** 12098 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12099 * and {@link #setScaleX(float) scaled}. 12100 * 12101 * @see #getRotation() 12102 * @see #getScaleX() 12103 * @see #getScaleY() 12104 * @see #getPivotY() 12105 * @return The x location of the pivot point. 12106 * 12107 * @attr ref android.R.styleable#View_transformPivotX 12108 */ 12109 @ViewDebug.ExportedProperty(category = "drawing") 12110 public float getPivotX() { 12111 return mRenderNode.getPivotX(); 12112 } 12113 12114 /** 12115 * Sets the x location of the point around which the view is 12116 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12117 * By default, the pivot point is centered on the object. 12118 * Setting this property disables this behavior and causes the view to use only the 12119 * explicitly set pivotX and pivotY values. 12120 * 12121 * @param pivotX The x location of the pivot point. 12122 * @see #getRotation() 12123 * @see #getScaleX() 12124 * @see #getScaleY() 12125 * @see #getPivotY() 12126 * 12127 * @attr ref android.R.styleable#View_transformPivotX 12128 */ 12129 public void setPivotX(float pivotX) { 12130 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12131 invalidateViewProperty(true, false); 12132 mRenderNode.setPivotX(pivotX); 12133 invalidateViewProperty(false, true); 12134 12135 invalidateParentIfNeededAndWasQuickRejected(); 12136 } 12137 } 12138 12139 /** 12140 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12141 * and {@link #setScaleY(float) scaled}. 12142 * 12143 * @see #getRotation() 12144 * @see #getScaleX() 12145 * @see #getScaleY() 12146 * @see #getPivotY() 12147 * @return The y location of the pivot point. 12148 * 12149 * @attr ref android.R.styleable#View_transformPivotY 12150 */ 12151 @ViewDebug.ExportedProperty(category = "drawing") 12152 public float getPivotY() { 12153 return mRenderNode.getPivotY(); 12154 } 12155 12156 /** 12157 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12158 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12159 * Setting this property disables this behavior and causes the view to use only the 12160 * explicitly set pivotX and pivotY values. 12161 * 12162 * @param pivotY The y location of the pivot point. 12163 * @see #getRotation() 12164 * @see #getScaleX() 12165 * @see #getScaleY() 12166 * @see #getPivotY() 12167 * 12168 * @attr ref android.R.styleable#View_transformPivotY 12169 */ 12170 public void setPivotY(float pivotY) { 12171 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12172 invalidateViewProperty(true, false); 12173 mRenderNode.setPivotY(pivotY); 12174 invalidateViewProperty(false, true); 12175 12176 invalidateParentIfNeededAndWasQuickRejected(); 12177 } 12178 } 12179 12180 /** 12181 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12182 * completely transparent and 1 means the view is completely opaque. 12183 * 12184 * <p>By default this is 1.0f. 12185 * @return The opacity of the view. 12186 */ 12187 @ViewDebug.ExportedProperty(category = "drawing") 12188 public float getAlpha() { 12189 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12190 } 12191 12192 /** 12193 * Sets the behavior for overlapping rendering for this view (see {@link 12194 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12195 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12196 * providing the value which is then used internally. That is, when {@link 12197 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12198 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12199 * instead. 12200 * 12201 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12202 * instead of that returned by {@link #hasOverlappingRendering()}. 12203 * 12204 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12205 */ 12206 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12207 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12208 if (hasOverlappingRendering) { 12209 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12210 } else { 12211 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12212 } 12213 } 12214 12215 /** 12216 * Returns the value for overlapping rendering that is used internally. This is either 12217 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12218 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12219 * 12220 * @return The value for overlapping rendering being used internally. 12221 */ 12222 public final boolean getHasOverlappingRendering() { 12223 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12224 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12225 hasOverlappingRendering(); 12226 } 12227 12228 /** 12229 * Returns whether this View has content which overlaps. 12230 * 12231 * <p>This function, intended to be overridden by specific View types, is an optimization when 12232 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12233 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12234 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12235 * directly. An example of overlapping rendering is a TextView with a background image, such as 12236 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12237 * ImageView with only the foreground image. The default implementation returns true; subclasses 12238 * should override if they have cases which can be optimized.</p> 12239 * 12240 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12241 * necessitates that a View return true if it uses the methods internally without passing the 12242 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12243 * 12244 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12245 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12246 * 12247 * @return true if the content in this view might overlap, false otherwise. 12248 */ 12249 @ViewDebug.ExportedProperty(category = "drawing") 12250 public boolean hasOverlappingRendering() { 12251 return true; 12252 } 12253 12254 /** 12255 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12256 * completely transparent and 1 means the view is completely opaque. 12257 * 12258 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12259 * can have significant performance implications, especially for large views. It is best to use 12260 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12261 * 12262 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12263 * strongly recommended for performance reasons to either override 12264 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12265 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12266 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12267 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12268 * of rendering cost, even for simple or small views. Starting with 12269 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12270 * applied to the view at the rendering level.</p> 12271 * 12272 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12273 * responsible for applying the opacity itself.</p> 12274 * 12275 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12276 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12277 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12278 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12279 * 12280 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12281 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12282 * {@link #hasOverlappingRendering}.</p> 12283 * 12284 * @param alpha The opacity of the view. 12285 * 12286 * @see #hasOverlappingRendering() 12287 * @see #setLayerType(int, android.graphics.Paint) 12288 * 12289 * @attr ref android.R.styleable#View_alpha 12290 */ 12291 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12292 ensureTransformationInfo(); 12293 if (mTransformationInfo.mAlpha != alpha) { 12294 mTransformationInfo.mAlpha = alpha; 12295 if (onSetAlpha((int) (alpha * 255))) { 12296 mPrivateFlags |= PFLAG_ALPHA_SET; 12297 // subclass is handling alpha - don't optimize rendering cache invalidation 12298 invalidateParentCaches(); 12299 invalidate(true); 12300 } else { 12301 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12302 invalidateViewProperty(true, false); 12303 mRenderNode.setAlpha(getFinalAlpha()); 12304 notifyViewAccessibilityStateChangedIfNeeded( 12305 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12306 } 12307 } 12308 } 12309 12310 /** 12311 * Faster version of setAlpha() which performs the same steps except there are 12312 * no calls to invalidate(). The caller of this function should perform proper invalidation 12313 * on the parent and this object. The return value indicates whether the subclass handles 12314 * alpha (the return value for onSetAlpha()). 12315 * 12316 * @param alpha The new value for the alpha property 12317 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12318 * the new value for the alpha property is different from the old value 12319 */ 12320 boolean setAlphaNoInvalidation(float alpha) { 12321 ensureTransformationInfo(); 12322 if (mTransformationInfo.mAlpha != alpha) { 12323 mTransformationInfo.mAlpha = alpha; 12324 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12325 if (subclassHandlesAlpha) { 12326 mPrivateFlags |= PFLAG_ALPHA_SET; 12327 return true; 12328 } else { 12329 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12330 mRenderNode.setAlpha(getFinalAlpha()); 12331 } 12332 } 12333 return false; 12334 } 12335 12336 /** 12337 * This property is hidden and intended only for use by the Fade transition, which 12338 * animates it to produce a visual translucency that does not side-effect (or get 12339 * affected by) the real alpha property. This value is composited with the other 12340 * alpha value (and the AlphaAnimation value, when that is present) to produce 12341 * a final visual translucency result, which is what is passed into the DisplayList. 12342 * 12343 * @hide 12344 */ 12345 public void setTransitionAlpha(float alpha) { 12346 ensureTransformationInfo(); 12347 if (mTransformationInfo.mTransitionAlpha != alpha) { 12348 mTransformationInfo.mTransitionAlpha = alpha; 12349 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12350 invalidateViewProperty(true, false); 12351 mRenderNode.setAlpha(getFinalAlpha()); 12352 } 12353 } 12354 12355 /** 12356 * Calculates the visual alpha of this view, which is a combination of the actual 12357 * alpha value and the transitionAlpha value (if set). 12358 */ 12359 private float getFinalAlpha() { 12360 if (mTransformationInfo != null) { 12361 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12362 } 12363 return 1; 12364 } 12365 12366 /** 12367 * This property is hidden and intended only for use by the Fade transition, which 12368 * animates it to produce a visual translucency that does not side-effect (or get 12369 * affected by) the real alpha property. This value is composited with the other 12370 * alpha value (and the AlphaAnimation value, when that is present) to produce 12371 * a final visual translucency result, which is what is passed into the DisplayList. 12372 * 12373 * @hide 12374 */ 12375 @ViewDebug.ExportedProperty(category = "drawing") 12376 public float getTransitionAlpha() { 12377 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12378 } 12379 12380 /** 12381 * Top position of this view relative to its parent. 12382 * 12383 * @return The top of this view, in pixels. 12384 */ 12385 @ViewDebug.CapturedViewProperty 12386 public final int getTop() { 12387 return mTop; 12388 } 12389 12390 /** 12391 * Sets the top position of this view relative to its parent. This method is meant to be called 12392 * by the layout system and should not generally be called otherwise, because the property 12393 * may be changed at any time by the layout. 12394 * 12395 * @param top The top of this view, in pixels. 12396 */ 12397 public final void setTop(int top) { 12398 if (top != mTop) { 12399 final boolean matrixIsIdentity = hasIdentityMatrix(); 12400 if (matrixIsIdentity) { 12401 if (mAttachInfo != null) { 12402 int minTop; 12403 int yLoc; 12404 if (top < mTop) { 12405 minTop = top; 12406 yLoc = top - mTop; 12407 } else { 12408 minTop = mTop; 12409 yLoc = 0; 12410 } 12411 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12412 } 12413 } else { 12414 // Double-invalidation is necessary to capture view's old and new areas 12415 invalidate(true); 12416 } 12417 12418 int width = mRight - mLeft; 12419 int oldHeight = mBottom - mTop; 12420 12421 mTop = top; 12422 mRenderNode.setTop(mTop); 12423 12424 sizeChange(width, mBottom - mTop, width, oldHeight); 12425 12426 if (!matrixIsIdentity) { 12427 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12428 invalidate(true); 12429 } 12430 mBackgroundSizeChanged = true; 12431 if (mForegroundInfo != null) { 12432 mForegroundInfo.mBoundsChanged = true; 12433 } 12434 invalidateParentIfNeeded(); 12435 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12436 // View was rejected last time it was drawn by its parent; this may have changed 12437 invalidateParentIfNeeded(); 12438 } 12439 } 12440 } 12441 12442 /** 12443 * Bottom position of this view relative to its parent. 12444 * 12445 * @return The bottom of this view, in pixels. 12446 */ 12447 @ViewDebug.CapturedViewProperty 12448 public final int getBottom() { 12449 return mBottom; 12450 } 12451 12452 /** 12453 * True if this view has changed since the last time being drawn. 12454 * 12455 * @return The dirty state of this view. 12456 */ 12457 public boolean isDirty() { 12458 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12459 } 12460 12461 /** 12462 * Sets the bottom position of this view relative to its parent. This method is meant to be 12463 * called by the layout system and should not generally be called otherwise, because the 12464 * property may be changed at any time by the layout. 12465 * 12466 * @param bottom The bottom of this view, in pixels. 12467 */ 12468 public final void setBottom(int bottom) { 12469 if (bottom != mBottom) { 12470 final boolean matrixIsIdentity = hasIdentityMatrix(); 12471 if (matrixIsIdentity) { 12472 if (mAttachInfo != null) { 12473 int maxBottom; 12474 if (bottom < mBottom) { 12475 maxBottom = mBottom; 12476 } else { 12477 maxBottom = bottom; 12478 } 12479 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12480 } 12481 } else { 12482 // Double-invalidation is necessary to capture view's old and new areas 12483 invalidate(true); 12484 } 12485 12486 int width = mRight - mLeft; 12487 int oldHeight = mBottom - mTop; 12488 12489 mBottom = bottom; 12490 mRenderNode.setBottom(mBottom); 12491 12492 sizeChange(width, mBottom - mTop, width, oldHeight); 12493 12494 if (!matrixIsIdentity) { 12495 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12496 invalidate(true); 12497 } 12498 mBackgroundSizeChanged = true; 12499 if (mForegroundInfo != null) { 12500 mForegroundInfo.mBoundsChanged = true; 12501 } 12502 invalidateParentIfNeeded(); 12503 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12504 // View was rejected last time it was drawn by its parent; this may have changed 12505 invalidateParentIfNeeded(); 12506 } 12507 } 12508 } 12509 12510 /** 12511 * Left position of this view relative to its parent. 12512 * 12513 * @return The left edge of this view, in pixels. 12514 */ 12515 @ViewDebug.CapturedViewProperty 12516 public final int getLeft() { 12517 return mLeft; 12518 } 12519 12520 /** 12521 * Sets the left position of this view relative to its parent. This method is meant to be called 12522 * by the layout system and should not generally be called otherwise, because the property 12523 * may be changed at any time by the layout. 12524 * 12525 * @param left The left of this view, in pixels. 12526 */ 12527 public final void setLeft(int left) { 12528 if (left != mLeft) { 12529 final boolean matrixIsIdentity = hasIdentityMatrix(); 12530 if (matrixIsIdentity) { 12531 if (mAttachInfo != null) { 12532 int minLeft; 12533 int xLoc; 12534 if (left < mLeft) { 12535 minLeft = left; 12536 xLoc = left - mLeft; 12537 } else { 12538 minLeft = mLeft; 12539 xLoc = 0; 12540 } 12541 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12542 } 12543 } else { 12544 // Double-invalidation is necessary to capture view's old and new areas 12545 invalidate(true); 12546 } 12547 12548 int oldWidth = mRight - mLeft; 12549 int height = mBottom - mTop; 12550 12551 mLeft = left; 12552 mRenderNode.setLeft(left); 12553 12554 sizeChange(mRight - mLeft, height, oldWidth, height); 12555 12556 if (!matrixIsIdentity) { 12557 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12558 invalidate(true); 12559 } 12560 mBackgroundSizeChanged = true; 12561 if (mForegroundInfo != null) { 12562 mForegroundInfo.mBoundsChanged = true; 12563 } 12564 invalidateParentIfNeeded(); 12565 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12566 // View was rejected last time it was drawn by its parent; this may have changed 12567 invalidateParentIfNeeded(); 12568 } 12569 } 12570 } 12571 12572 /** 12573 * Right position of this view relative to its parent. 12574 * 12575 * @return The right edge of this view, in pixels. 12576 */ 12577 @ViewDebug.CapturedViewProperty 12578 public final int getRight() { 12579 return mRight; 12580 } 12581 12582 /** 12583 * Sets the right position of this view relative to its parent. This method is meant to be called 12584 * by the layout system and should not generally be called otherwise, because the property 12585 * may be changed at any time by the layout. 12586 * 12587 * @param right The right of this view, in pixels. 12588 */ 12589 public final void setRight(int right) { 12590 if (right != mRight) { 12591 final boolean matrixIsIdentity = hasIdentityMatrix(); 12592 if (matrixIsIdentity) { 12593 if (mAttachInfo != null) { 12594 int maxRight; 12595 if (right < mRight) { 12596 maxRight = mRight; 12597 } else { 12598 maxRight = right; 12599 } 12600 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12601 } 12602 } else { 12603 // Double-invalidation is necessary to capture view's old and new areas 12604 invalidate(true); 12605 } 12606 12607 int oldWidth = mRight - mLeft; 12608 int height = mBottom - mTop; 12609 12610 mRight = right; 12611 mRenderNode.setRight(mRight); 12612 12613 sizeChange(mRight - mLeft, height, oldWidth, height); 12614 12615 if (!matrixIsIdentity) { 12616 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12617 invalidate(true); 12618 } 12619 mBackgroundSizeChanged = true; 12620 if (mForegroundInfo != null) { 12621 mForegroundInfo.mBoundsChanged = true; 12622 } 12623 invalidateParentIfNeeded(); 12624 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12625 // View was rejected last time it was drawn by its parent; this may have changed 12626 invalidateParentIfNeeded(); 12627 } 12628 } 12629 } 12630 12631 /** 12632 * The visual x position of this view, in pixels. This is equivalent to the 12633 * {@link #setTranslationX(float) translationX} property plus the current 12634 * {@link #getLeft() left} property. 12635 * 12636 * @return The visual x position of this view, in pixels. 12637 */ 12638 @ViewDebug.ExportedProperty(category = "drawing") 12639 public float getX() { 12640 return mLeft + getTranslationX(); 12641 } 12642 12643 /** 12644 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12645 * {@link #setTranslationX(float) translationX} property to be the difference between 12646 * the x value passed in and the current {@link #getLeft() left} property. 12647 * 12648 * @param x The visual x position of this view, in pixels. 12649 */ 12650 public void setX(float x) { 12651 setTranslationX(x - mLeft); 12652 } 12653 12654 /** 12655 * The visual y position of this view, in pixels. This is equivalent to the 12656 * {@link #setTranslationY(float) translationY} property plus the current 12657 * {@link #getTop() top} property. 12658 * 12659 * @return The visual y position of this view, in pixels. 12660 */ 12661 @ViewDebug.ExportedProperty(category = "drawing") 12662 public float getY() { 12663 return mTop + getTranslationY(); 12664 } 12665 12666 /** 12667 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12668 * {@link #setTranslationY(float) translationY} property to be the difference between 12669 * the y value passed in and the current {@link #getTop() top} property. 12670 * 12671 * @param y The visual y position of this view, in pixels. 12672 */ 12673 public void setY(float y) { 12674 setTranslationY(y - mTop); 12675 } 12676 12677 /** 12678 * The visual z position of this view, in pixels. This is equivalent to the 12679 * {@link #setTranslationZ(float) translationZ} property plus the current 12680 * {@link #getElevation() elevation} property. 12681 * 12682 * @return The visual z position of this view, in pixels. 12683 */ 12684 @ViewDebug.ExportedProperty(category = "drawing") 12685 public float getZ() { 12686 return getElevation() + getTranslationZ(); 12687 } 12688 12689 /** 12690 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12691 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12692 * the x value passed in and the current {@link #getElevation() elevation} property. 12693 * 12694 * @param z The visual z position of this view, in pixels. 12695 */ 12696 public void setZ(float z) { 12697 setTranslationZ(z - getElevation()); 12698 } 12699 12700 /** 12701 * The base elevation of this view relative to its parent, in pixels. 12702 * 12703 * @return The base depth position of the view, in pixels. 12704 */ 12705 @ViewDebug.ExportedProperty(category = "drawing") 12706 public float getElevation() { 12707 return mRenderNode.getElevation(); 12708 } 12709 12710 /** 12711 * Sets the base elevation of this view, in pixels. 12712 * 12713 * @attr ref android.R.styleable#View_elevation 12714 */ 12715 public void setElevation(float elevation) { 12716 if (elevation != getElevation()) { 12717 invalidateViewProperty(true, false); 12718 mRenderNode.setElevation(elevation); 12719 invalidateViewProperty(false, true); 12720 12721 invalidateParentIfNeededAndWasQuickRejected(); 12722 } 12723 } 12724 12725 /** 12726 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12727 * This position is post-layout, in addition to wherever the object's 12728 * layout placed it. 12729 * 12730 * @return The horizontal position of this view relative to its left position, in pixels. 12731 */ 12732 @ViewDebug.ExportedProperty(category = "drawing") 12733 public float getTranslationX() { 12734 return mRenderNode.getTranslationX(); 12735 } 12736 12737 /** 12738 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12739 * This effectively positions the object post-layout, in addition to wherever the object's 12740 * layout placed it. 12741 * 12742 * @param translationX The horizontal position of this view relative to its left position, 12743 * in pixels. 12744 * 12745 * @attr ref android.R.styleable#View_translationX 12746 */ 12747 public void setTranslationX(float translationX) { 12748 if (translationX != getTranslationX()) { 12749 invalidateViewProperty(true, false); 12750 mRenderNode.setTranslationX(translationX); 12751 invalidateViewProperty(false, true); 12752 12753 invalidateParentIfNeededAndWasQuickRejected(); 12754 notifySubtreeAccessibilityStateChangedIfNeeded(); 12755 } 12756 } 12757 12758 /** 12759 * The vertical location of this view relative to its {@link #getTop() top} position. 12760 * This position is post-layout, in addition to wherever the object's 12761 * layout placed it. 12762 * 12763 * @return The vertical position of this view relative to its top position, 12764 * in pixels. 12765 */ 12766 @ViewDebug.ExportedProperty(category = "drawing") 12767 public float getTranslationY() { 12768 return mRenderNode.getTranslationY(); 12769 } 12770 12771 /** 12772 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12773 * This effectively positions the object post-layout, in addition to wherever the object's 12774 * layout placed it. 12775 * 12776 * @param translationY The vertical position of this view relative to its top position, 12777 * in pixels. 12778 * 12779 * @attr ref android.R.styleable#View_translationY 12780 */ 12781 public void setTranslationY(float translationY) { 12782 if (translationY != getTranslationY()) { 12783 invalidateViewProperty(true, false); 12784 mRenderNode.setTranslationY(translationY); 12785 invalidateViewProperty(false, true); 12786 12787 invalidateParentIfNeededAndWasQuickRejected(); 12788 notifySubtreeAccessibilityStateChangedIfNeeded(); 12789 } 12790 } 12791 12792 /** 12793 * The depth location of this view relative to its {@link #getElevation() elevation}. 12794 * 12795 * @return The depth of this view relative to its elevation. 12796 */ 12797 @ViewDebug.ExportedProperty(category = "drawing") 12798 public float getTranslationZ() { 12799 return mRenderNode.getTranslationZ(); 12800 } 12801 12802 /** 12803 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12804 * 12805 * @attr ref android.R.styleable#View_translationZ 12806 */ 12807 public void setTranslationZ(float translationZ) { 12808 if (translationZ != getTranslationZ()) { 12809 invalidateViewProperty(true, false); 12810 mRenderNode.setTranslationZ(translationZ); 12811 invalidateViewProperty(false, true); 12812 12813 invalidateParentIfNeededAndWasQuickRejected(); 12814 } 12815 } 12816 12817 /** @hide */ 12818 public void setAnimationMatrix(Matrix matrix) { 12819 invalidateViewProperty(true, false); 12820 mRenderNode.setAnimationMatrix(matrix); 12821 invalidateViewProperty(false, true); 12822 12823 invalidateParentIfNeededAndWasQuickRejected(); 12824 } 12825 12826 /** 12827 * Returns the current StateListAnimator if exists. 12828 * 12829 * @return StateListAnimator or null if it does not exists 12830 * @see #setStateListAnimator(android.animation.StateListAnimator) 12831 */ 12832 public StateListAnimator getStateListAnimator() { 12833 return mStateListAnimator; 12834 } 12835 12836 /** 12837 * Attaches the provided StateListAnimator to this View. 12838 * <p> 12839 * Any previously attached StateListAnimator will be detached. 12840 * 12841 * @param stateListAnimator The StateListAnimator to update the view 12842 * @see {@link android.animation.StateListAnimator} 12843 */ 12844 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12845 if (mStateListAnimator == stateListAnimator) { 12846 return; 12847 } 12848 if (mStateListAnimator != null) { 12849 mStateListAnimator.setTarget(null); 12850 } 12851 mStateListAnimator = stateListAnimator; 12852 if (stateListAnimator != null) { 12853 stateListAnimator.setTarget(this); 12854 if (isAttachedToWindow()) { 12855 stateListAnimator.setState(getDrawableState()); 12856 } 12857 } 12858 } 12859 12860 /** 12861 * Returns whether the Outline should be used to clip the contents of the View. 12862 * <p> 12863 * Note that this flag will only be respected if the View's Outline returns true from 12864 * {@link Outline#canClip()}. 12865 * 12866 * @see #setOutlineProvider(ViewOutlineProvider) 12867 * @see #setClipToOutline(boolean) 12868 */ 12869 public final boolean getClipToOutline() { 12870 return mRenderNode.getClipToOutline(); 12871 } 12872 12873 /** 12874 * Sets whether the View's Outline should be used to clip the contents of the View. 12875 * <p> 12876 * Only a single non-rectangular clip can be applied on a View at any time. 12877 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12878 * circular reveal} animation take priority over Outline clipping, and 12879 * child Outline clipping takes priority over Outline clipping done by a 12880 * parent. 12881 * <p> 12882 * Note that this flag will only be respected if the View's Outline returns true from 12883 * {@link Outline#canClip()}. 12884 * 12885 * @see #setOutlineProvider(ViewOutlineProvider) 12886 * @see #getClipToOutline() 12887 */ 12888 public void setClipToOutline(boolean clipToOutline) { 12889 damageInParent(); 12890 if (getClipToOutline() != clipToOutline) { 12891 mRenderNode.setClipToOutline(clipToOutline); 12892 } 12893 } 12894 12895 // correspond to the enum values of View_outlineProvider 12896 private static final int PROVIDER_BACKGROUND = 0; 12897 private static final int PROVIDER_NONE = 1; 12898 private static final int PROVIDER_BOUNDS = 2; 12899 private static final int PROVIDER_PADDED_BOUNDS = 3; 12900 private void setOutlineProviderFromAttribute(int providerInt) { 12901 switch (providerInt) { 12902 case PROVIDER_BACKGROUND: 12903 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12904 break; 12905 case PROVIDER_NONE: 12906 setOutlineProvider(null); 12907 break; 12908 case PROVIDER_BOUNDS: 12909 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12910 break; 12911 case PROVIDER_PADDED_BOUNDS: 12912 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12913 break; 12914 } 12915 } 12916 12917 /** 12918 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12919 * the shape of the shadow it casts, and enables outline clipping. 12920 * <p> 12921 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12922 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12923 * outline provider with this method allows this behavior to be overridden. 12924 * <p> 12925 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12926 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12927 * <p> 12928 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12929 * 12930 * @see #setClipToOutline(boolean) 12931 * @see #getClipToOutline() 12932 * @see #getOutlineProvider() 12933 */ 12934 public void setOutlineProvider(ViewOutlineProvider provider) { 12935 mOutlineProvider = provider; 12936 invalidateOutline(); 12937 } 12938 12939 /** 12940 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12941 * that defines the shape of the shadow it casts, and enables outline clipping. 12942 * 12943 * @see #setOutlineProvider(ViewOutlineProvider) 12944 */ 12945 public ViewOutlineProvider getOutlineProvider() { 12946 return mOutlineProvider; 12947 } 12948 12949 /** 12950 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12951 * 12952 * @see #setOutlineProvider(ViewOutlineProvider) 12953 */ 12954 public void invalidateOutline() { 12955 rebuildOutline(); 12956 12957 notifySubtreeAccessibilityStateChangedIfNeeded(); 12958 invalidateViewProperty(false, false); 12959 } 12960 12961 /** 12962 * Internal version of {@link #invalidateOutline()} which invalidates the 12963 * outline without invalidating the view itself. This is intended to be called from 12964 * within methods in the View class itself which are the result of the view being 12965 * invalidated already. For example, when we are drawing the background of a View, 12966 * we invalidate the outline in case it changed in the meantime, but we do not 12967 * need to invalidate the view because we're already drawing the background as part 12968 * of drawing the view in response to an earlier invalidation of the view. 12969 */ 12970 private void rebuildOutline() { 12971 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12972 if (mAttachInfo == null) return; 12973 12974 if (mOutlineProvider == null) { 12975 // no provider, remove outline 12976 mRenderNode.setOutline(null); 12977 } else { 12978 final Outline outline = mAttachInfo.mTmpOutline; 12979 outline.setEmpty(); 12980 outline.setAlpha(1.0f); 12981 12982 mOutlineProvider.getOutline(this, outline); 12983 mRenderNode.setOutline(outline); 12984 } 12985 } 12986 12987 /** 12988 * HierarchyViewer only 12989 * 12990 * @hide 12991 */ 12992 @ViewDebug.ExportedProperty(category = "drawing") 12993 public boolean hasShadow() { 12994 return mRenderNode.hasShadow(); 12995 } 12996 12997 12998 /** @hide */ 12999 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 13000 mRenderNode.setRevealClip(shouldClip, x, y, radius); 13001 invalidateViewProperty(false, false); 13002 } 13003 13004 /** 13005 * Hit rectangle in parent's coordinates 13006 * 13007 * @param outRect The hit rectangle of the view. 13008 */ 13009 public void getHitRect(Rect outRect) { 13010 if (hasIdentityMatrix() || mAttachInfo == null) { 13011 outRect.set(mLeft, mTop, mRight, mBottom); 13012 } else { 13013 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13014 tmpRect.set(0, 0, getWidth(), getHeight()); 13015 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13016 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13017 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13018 } 13019 } 13020 13021 /** 13022 * Determines whether the given point, in local coordinates is inside the view. 13023 */ 13024 /*package*/ final boolean pointInView(float localX, float localY) { 13025 return pointInView(localX, localY, 0); 13026 } 13027 13028 /** 13029 * Utility method to determine whether the given point, in local coordinates, 13030 * is inside the view, where the area of the view is expanded by the slop factor. 13031 * This method is called while processing touch-move events to determine if the event 13032 * is still within the view. 13033 * 13034 * @hide 13035 */ 13036 public boolean pointInView(float localX, float localY, float slop) { 13037 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13038 localY < ((mBottom - mTop) + slop); 13039 } 13040 13041 /** 13042 * When a view has focus and the user navigates away from it, the next view is searched for 13043 * starting from the rectangle filled in by this method. 13044 * 13045 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13046 * of the view. However, if your view maintains some idea of internal selection, 13047 * such as a cursor, or a selected row or column, you should override this method and 13048 * fill in a more specific rectangle. 13049 * 13050 * @param r The rectangle to fill in, in this view's coordinates. 13051 */ 13052 public void getFocusedRect(Rect r) { 13053 getDrawingRect(r); 13054 } 13055 13056 /** 13057 * If some part of this view is not clipped by any of its parents, then 13058 * return that area in r in global (root) coordinates. To convert r to local 13059 * coordinates (without taking possible View rotations into account), offset 13060 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13061 * If the view is completely clipped or translated out, return false. 13062 * 13063 * @param r If true is returned, r holds the global coordinates of the 13064 * visible portion of this view. 13065 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13066 * between this view and its root. globalOffet may be null. 13067 * @return true if r is non-empty (i.e. part of the view is visible at the 13068 * root level. 13069 */ 13070 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13071 int width = mRight - mLeft; 13072 int height = mBottom - mTop; 13073 if (width > 0 && height > 0) { 13074 r.set(0, 0, width, height); 13075 if (globalOffset != null) { 13076 globalOffset.set(-mScrollX, -mScrollY); 13077 } 13078 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13079 } 13080 return false; 13081 } 13082 13083 public final boolean getGlobalVisibleRect(Rect r) { 13084 return getGlobalVisibleRect(r, null); 13085 } 13086 13087 public final boolean getLocalVisibleRect(Rect r) { 13088 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13089 if (getGlobalVisibleRect(r, offset)) { 13090 r.offset(-offset.x, -offset.y); // make r local 13091 return true; 13092 } 13093 return false; 13094 } 13095 13096 /** 13097 * Offset this view's vertical location by the specified number of pixels. 13098 * 13099 * @param offset the number of pixels to offset the view by 13100 */ 13101 public void offsetTopAndBottom(int offset) { 13102 if (offset != 0) { 13103 final boolean matrixIsIdentity = hasIdentityMatrix(); 13104 if (matrixIsIdentity) { 13105 if (isHardwareAccelerated()) { 13106 invalidateViewProperty(false, false); 13107 } else { 13108 final ViewParent p = mParent; 13109 if (p != null && mAttachInfo != null) { 13110 final Rect r = mAttachInfo.mTmpInvalRect; 13111 int minTop; 13112 int maxBottom; 13113 int yLoc; 13114 if (offset < 0) { 13115 minTop = mTop + offset; 13116 maxBottom = mBottom; 13117 yLoc = offset; 13118 } else { 13119 minTop = mTop; 13120 maxBottom = mBottom + offset; 13121 yLoc = 0; 13122 } 13123 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13124 p.invalidateChild(this, r); 13125 } 13126 } 13127 } else { 13128 invalidateViewProperty(false, false); 13129 } 13130 13131 mTop += offset; 13132 mBottom += offset; 13133 mRenderNode.offsetTopAndBottom(offset); 13134 if (isHardwareAccelerated()) { 13135 invalidateViewProperty(false, false); 13136 invalidateParentIfNeededAndWasQuickRejected(); 13137 } else { 13138 if (!matrixIsIdentity) { 13139 invalidateViewProperty(false, true); 13140 } 13141 invalidateParentIfNeeded(); 13142 } 13143 notifySubtreeAccessibilityStateChangedIfNeeded(); 13144 } 13145 } 13146 13147 /** 13148 * Offset this view's horizontal location by the specified amount of pixels. 13149 * 13150 * @param offset the number of pixels to offset the view by 13151 */ 13152 public void offsetLeftAndRight(int offset) { 13153 if (offset != 0) { 13154 final boolean matrixIsIdentity = hasIdentityMatrix(); 13155 if (matrixIsIdentity) { 13156 if (isHardwareAccelerated()) { 13157 invalidateViewProperty(false, false); 13158 } else { 13159 final ViewParent p = mParent; 13160 if (p != null && mAttachInfo != null) { 13161 final Rect r = mAttachInfo.mTmpInvalRect; 13162 int minLeft; 13163 int maxRight; 13164 if (offset < 0) { 13165 minLeft = mLeft + offset; 13166 maxRight = mRight; 13167 } else { 13168 minLeft = mLeft; 13169 maxRight = mRight + offset; 13170 } 13171 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13172 p.invalidateChild(this, r); 13173 } 13174 } 13175 } else { 13176 invalidateViewProperty(false, false); 13177 } 13178 13179 mLeft += offset; 13180 mRight += offset; 13181 mRenderNode.offsetLeftAndRight(offset); 13182 if (isHardwareAccelerated()) { 13183 invalidateViewProperty(false, false); 13184 invalidateParentIfNeededAndWasQuickRejected(); 13185 } else { 13186 if (!matrixIsIdentity) { 13187 invalidateViewProperty(false, true); 13188 } 13189 invalidateParentIfNeeded(); 13190 } 13191 notifySubtreeAccessibilityStateChangedIfNeeded(); 13192 } 13193 } 13194 13195 /** 13196 * Get the LayoutParams associated with this view. All views should have 13197 * layout parameters. These supply parameters to the <i>parent</i> of this 13198 * view specifying how it should be arranged. There are many subclasses of 13199 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13200 * of ViewGroup that are responsible for arranging their children. 13201 * 13202 * This method may return null if this View is not attached to a parent 13203 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13204 * was not invoked successfully. When a View is attached to a parent 13205 * ViewGroup, this method must not return null. 13206 * 13207 * @return The LayoutParams associated with this view, or null if no 13208 * parameters have been set yet 13209 */ 13210 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13211 public ViewGroup.LayoutParams getLayoutParams() { 13212 return mLayoutParams; 13213 } 13214 13215 /** 13216 * Set the layout parameters associated with this view. These supply 13217 * parameters to the <i>parent</i> of this view specifying how it should be 13218 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13219 * correspond to the different subclasses of ViewGroup that are responsible 13220 * for arranging their children. 13221 * 13222 * @param params The layout parameters for this view, cannot be null 13223 */ 13224 public void setLayoutParams(ViewGroup.LayoutParams params) { 13225 if (params == null) { 13226 throw new NullPointerException("Layout parameters cannot be null"); 13227 } 13228 mLayoutParams = params; 13229 resolveLayoutParams(); 13230 if (mParent instanceof ViewGroup) { 13231 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13232 } 13233 requestLayout(); 13234 } 13235 13236 /** 13237 * Resolve the layout parameters depending on the resolved layout direction 13238 * 13239 * @hide 13240 */ 13241 public void resolveLayoutParams() { 13242 if (mLayoutParams != null) { 13243 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13244 } 13245 } 13246 13247 /** 13248 * Set the scrolled position of your view. This will cause a call to 13249 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13250 * invalidated. 13251 * @param x the x position to scroll to 13252 * @param y the y position to scroll to 13253 */ 13254 public void scrollTo(int x, int y) { 13255 if (mScrollX != x || mScrollY != y) { 13256 int oldX = mScrollX; 13257 int oldY = mScrollY; 13258 mScrollX = x; 13259 mScrollY = y; 13260 invalidateParentCaches(); 13261 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13262 if (!awakenScrollBars()) { 13263 postInvalidateOnAnimation(); 13264 } 13265 } 13266 } 13267 13268 /** 13269 * Move the scrolled position of your view. This will cause a call to 13270 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13271 * invalidated. 13272 * @param x the amount of pixels to scroll by horizontally 13273 * @param y the amount of pixels to scroll by vertically 13274 */ 13275 public void scrollBy(int x, int y) { 13276 scrollTo(mScrollX + x, mScrollY + y); 13277 } 13278 13279 /** 13280 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13281 * animation to fade the scrollbars out after a default delay. If a subclass 13282 * provides animated scrolling, the start delay should equal the duration 13283 * of the scrolling animation.</p> 13284 * 13285 * <p>The animation starts only if at least one of the scrollbars is 13286 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13287 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13288 * this method returns true, and false otherwise. If the animation is 13289 * started, this method calls {@link #invalidate()}; in that case the 13290 * caller should not call {@link #invalidate()}.</p> 13291 * 13292 * <p>This method should be invoked every time a subclass directly updates 13293 * the scroll parameters.</p> 13294 * 13295 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13296 * and {@link #scrollTo(int, int)}.</p> 13297 * 13298 * @return true if the animation is played, false otherwise 13299 * 13300 * @see #awakenScrollBars(int) 13301 * @see #scrollBy(int, int) 13302 * @see #scrollTo(int, int) 13303 * @see #isHorizontalScrollBarEnabled() 13304 * @see #isVerticalScrollBarEnabled() 13305 * @see #setHorizontalScrollBarEnabled(boolean) 13306 * @see #setVerticalScrollBarEnabled(boolean) 13307 */ 13308 protected boolean awakenScrollBars() { 13309 return mScrollCache != null && 13310 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13311 } 13312 13313 /** 13314 * Trigger the scrollbars to draw. 13315 * This method differs from awakenScrollBars() only in its default duration. 13316 * initialAwakenScrollBars() will show the scroll bars for longer than 13317 * usual to give the user more of a chance to notice them. 13318 * 13319 * @return true if the animation is played, false otherwise. 13320 */ 13321 private boolean initialAwakenScrollBars() { 13322 return mScrollCache != null && 13323 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13324 } 13325 13326 /** 13327 * <p> 13328 * Trigger the scrollbars to draw. When invoked this method starts an 13329 * animation to fade the scrollbars out after a fixed delay. If a subclass 13330 * provides animated scrolling, the start delay should equal the duration of 13331 * the scrolling animation. 13332 * </p> 13333 * 13334 * <p> 13335 * The animation starts only if at least one of the scrollbars is enabled, 13336 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13337 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13338 * this method returns true, and false otherwise. If the animation is 13339 * started, this method calls {@link #invalidate()}; in that case the caller 13340 * should not call {@link #invalidate()}. 13341 * </p> 13342 * 13343 * <p> 13344 * This method should be invoked every time a subclass directly updates the 13345 * scroll parameters. 13346 * </p> 13347 * 13348 * @param startDelay the delay, in milliseconds, after which the animation 13349 * should start; when the delay is 0, the animation starts 13350 * immediately 13351 * @return true if the animation is played, false otherwise 13352 * 13353 * @see #scrollBy(int, int) 13354 * @see #scrollTo(int, int) 13355 * @see #isHorizontalScrollBarEnabled() 13356 * @see #isVerticalScrollBarEnabled() 13357 * @see #setHorizontalScrollBarEnabled(boolean) 13358 * @see #setVerticalScrollBarEnabled(boolean) 13359 */ 13360 protected boolean awakenScrollBars(int startDelay) { 13361 return awakenScrollBars(startDelay, true); 13362 } 13363 13364 /** 13365 * <p> 13366 * Trigger the scrollbars to draw. When invoked this method starts an 13367 * animation to fade the scrollbars out after a fixed delay. If a subclass 13368 * provides animated scrolling, the start delay should equal the duration of 13369 * the scrolling animation. 13370 * </p> 13371 * 13372 * <p> 13373 * The animation starts only if at least one of the scrollbars is enabled, 13374 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13375 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13376 * this method returns true, and false otherwise. If the animation is 13377 * started, this method calls {@link #invalidate()} if the invalidate parameter 13378 * is set to true; in that case the caller 13379 * should not call {@link #invalidate()}. 13380 * </p> 13381 * 13382 * <p> 13383 * This method should be invoked every time a subclass directly updates the 13384 * scroll parameters. 13385 * </p> 13386 * 13387 * @param startDelay the delay, in milliseconds, after which the animation 13388 * should start; when the delay is 0, the animation starts 13389 * immediately 13390 * 13391 * @param invalidate Whether this method should call invalidate 13392 * 13393 * @return true if the animation is played, false otherwise 13394 * 13395 * @see #scrollBy(int, int) 13396 * @see #scrollTo(int, int) 13397 * @see #isHorizontalScrollBarEnabled() 13398 * @see #isVerticalScrollBarEnabled() 13399 * @see #setHorizontalScrollBarEnabled(boolean) 13400 * @see #setVerticalScrollBarEnabled(boolean) 13401 */ 13402 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13403 final ScrollabilityCache scrollCache = mScrollCache; 13404 13405 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13406 return false; 13407 } 13408 13409 if (scrollCache.scrollBar == null) { 13410 scrollCache.scrollBar = new ScrollBarDrawable(); 13411 scrollCache.scrollBar.setState(getDrawableState()); 13412 scrollCache.scrollBar.setCallback(this); 13413 } 13414 13415 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13416 13417 if (invalidate) { 13418 // Invalidate to show the scrollbars 13419 postInvalidateOnAnimation(); 13420 } 13421 13422 if (scrollCache.state == ScrollabilityCache.OFF) { 13423 // FIXME: this is copied from WindowManagerService. 13424 // We should get this value from the system when it 13425 // is possible to do so. 13426 final int KEY_REPEAT_FIRST_DELAY = 750; 13427 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13428 } 13429 13430 // Tell mScrollCache when we should start fading. This may 13431 // extend the fade start time if one was already scheduled 13432 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13433 scrollCache.fadeStartTime = fadeStartTime; 13434 scrollCache.state = ScrollabilityCache.ON; 13435 13436 // Schedule our fader to run, unscheduling any old ones first 13437 if (mAttachInfo != null) { 13438 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13439 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13440 } 13441 13442 return true; 13443 } 13444 13445 return false; 13446 } 13447 13448 /** 13449 * Do not invalidate views which are not visible and which are not running an animation. They 13450 * will not get drawn and they should not set dirty flags as if they will be drawn 13451 */ 13452 private boolean skipInvalidate() { 13453 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13454 (!(mParent instanceof ViewGroup) || 13455 !((ViewGroup) mParent).isViewTransitioning(this)); 13456 } 13457 13458 /** 13459 * Mark the area defined by dirty as needing to be drawn. If the view is 13460 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13461 * point in the future. 13462 * <p> 13463 * This must be called from a UI thread. To call from a non-UI thread, call 13464 * {@link #postInvalidate()}. 13465 * <p> 13466 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13467 * {@code dirty}. 13468 * 13469 * @param dirty the rectangle representing the bounds of the dirty region 13470 */ 13471 public void invalidate(Rect dirty) { 13472 final int scrollX = mScrollX; 13473 final int scrollY = mScrollY; 13474 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13475 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13476 } 13477 13478 /** 13479 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13480 * coordinates of the dirty rect are relative to the view. If the view is 13481 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13482 * point in the future. 13483 * <p> 13484 * This must be called from a UI thread. To call from a non-UI thread, call 13485 * {@link #postInvalidate()}. 13486 * 13487 * @param l the left position of the dirty region 13488 * @param t the top position of the dirty region 13489 * @param r the right position of the dirty region 13490 * @param b the bottom position of the dirty region 13491 */ 13492 public void invalidate(int l, int t, int r, int b) { 13493 final int scrollX = mScrollX; 13494 final int scrollY = mScrollY; 13495 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13496 } 13497 13498 /** 13499 * Invalidate the whole view. If the view is visible, 13500 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13501 * the future. 13502 * <p> 13503 * This must be called from a UI thread. To call from a non-UI thread, call 13504 * {@link #postInvalidate()}. 13505 */ 13506 public void invalidate() { 13507 invalidate(true); 13508 } 13509 13510 /** 13511 * This is where the invalidate() work actually happens. A full invalidate() 13512 * causes the drawing cache to be invalidated, but this function can be 13513 * called with invalidateCache set to false to skip that invalidation step 13514 * for cases that do not need it (for example, a component that remains at 13515 * the same dimensions with the same content). 13516 * 13517 * @param invalidateCache Whether the drawing cache for this view should be 13518 * invalidated as well. This is usually true for a full 13519 * invalidate, but may be set to false if the View's contents or 13520 * dimensions have not changed. 13521 */ 13522 void invalidate(boolean invalidateCache) { 13523 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13524 } 13525 13526 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13527 boolean fullInvalidate) { 13528 if (mGhostView != null) { 13529 mGhostView.invalidate(true); 13530 return; 13531 } 13532 13533 if (skipInvalidate()) { 13534 return; 13535 } 13536 13537 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13538 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13539 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13540 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13541 if (fullInvalidate) { 13542 mLastIsOpaque = isOpaque(); 13543 mPrivateFlags &= ~PFLAG_DRAWN; 13544 } 13545 13546 mPrivateFlags |= PFLAG_DIRTY; 13547 13548 if (invalidateCache) { 13549 mPrivateFlags |= PFLAG_INVALIDATED; 13550 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13551 } 13552 13553 // Propagate the damage rectangle to the parent view. 13554 final AttachInfo ai = mAttachInfo; 13555 final ViewParent p = mParent; 13556 if (p != null && ai != null && l < r && t < b) { 13557 final Rect damage = ai.mTmpInvalRect; 13558 damage.set(l, t, r, b); 13559 p.invalidateChild(this, damage); 13560 } 13561 13562 // Damage the entire projection receiver, if necessary. 13563 if (mBackground != null && mBackground.isProjected()) { 13564 final View receiver = getProjectionReceiver(); 13565 if (receiver != null) { 13566 receiver.damageInParent(); 13567 } 13568 } 13569 13570 // Damage the entire IsolatedZVolume receiving this view's shadow. 13571 if (isHardwareAccelerated() && getZ() != 0) { 13572 damageShadowReceiver(); 13573 } 13574 } 13575 } 13576 13577 /** 13578 * @return this view's projection receiver, or {@code null} if none exists 13579 */ 13580 private View getProjectionReceiver() { 13581 ViewParent p = getParent(); 13582 while (p != null && p instanceof View) { 13583 final View v = (View) p; 13584 if (v.isProjectionReceiver()) { 13585 return v; 13586 } 13587 p = p.getParent(); 13588 } 13589 13590 return null; 13591 } 13592 13593 /** 13594 * @return whether the view is a projection receiver 13595 */ 13596 private boolean isProjectionReceiver() { 13597 return mBackground != null; 13598 } 13599 13600 /** 13601 * Damage area of the screen that can be covered by this View's shadow. 13602 * 13603 * This method will guarantee that any changes to shadows cast by a View 13604 * are damaged on the screen for future redraw. 13605 */ 13606 private void damageShadowReceiver() { 13607 final AttachInfo ai = mAttachInfo; 13608 if (ai != null) { 13609 ViewParent p = getParent(); 13610 if (p != null && p instanceof ViewGroup) { 13611 final ViewGroup vg = (ViewGroup) p; 13612 vg.damageInParent(); 13613 } 13614 } 13615 } 13616 13617 /** 13618 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13619 * set any flags or handle all of the cases handled by the default invalidation methods. 13620 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13621 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13622 * walk up the hierarchy, transforming the dirty rect as necessary. 13623 * 13624 * The method also handles normal invalidation logic if display list properties are not 13625 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13626 * backup approach, to handle these cases used in the various property-setting methods. 13627 * 13628 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13629 * are not being used in this view 13630 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13631 * list properties are not being used in this view 13632 */ 13633 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13634 if (!isHardwareAccelerated() 13635 || !mRenderNode.isValid() 13636 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13637 if (invalidateParent) { 13638 invalidateParentCaches(); 13639 } 13640 if (forceRedraw) { 13641 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13642 } 13643 invalidate(false); 13644 } else { 13645 damageInParent(); 13646 } 13647 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13648 damageShadowReceiver(); 13649 } 13650 } 13651 13652 /** 13653 * Tells the parent view to damage this view's bounds. 13654 * 13655 * @hide 13656 */ 13657 protected void damageInParent() { 13658 final AttachInfo ai = mAttachInfo; 13659 final ViewParent p = mParent; 13660 if (p != null && ai != null) { 13661 final Rect r = ai.mTmpInvalRect; 13662 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13663 if (mParent instanceof ViewGroup) { 13664 ((ViewGroup) mParent).damageChild(this, r); 13665 } else { 13666 mParent.invalidateChild(this, r); 13667 } 13668 } 13669 } 13670 13671 /** 13672 * Utility method to transform a given Rect by the current matrix of this view. 13673 */ 13674 void transformRect(final Rect rect) { 13675 if (!getMatrix().isIdentity()) { 13676 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13677 boundingRect.set(rect); 13678 getMatrix().mapRect(boundingRect); 13679 rect.set((int) Math.floor(boundingRect.left), 13680 (int) Math.floor(boundingRect.top), 13681 (int) Math.ceil(boundingRect.right), 13682 (int) Math.ceil(boundingRect.bottom)); 13683 } 13684 } 13685 13686 /** 13687 * Used to indicate that the parent of this view should clear its caches. This functionality 13688 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13689 * which is necessary when various parent-managed properties of the view change, such as 13690 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13691 * clears the parent caches and does not causes an invalidate event. 13692 * 13693 * @hide 13694 */ 13695 protected void invalidateParentCaches() { 13696 if (mParent instanceof View) { 13697 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13698 } 13699 } 13700 13701 /** 13702 * Used to indicate that the parent of this view should be invalidated. This functionality 13703 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13704 * which is necessary when various parent-managed properties of the view change, such as 13705 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13706 * an invalidation event to the parent. 13707 * 13708 * @hide 13709 */ 13710 protected void invalidateParentIfNeeded() { 13711 if (isHardwareAccelerated() && mParent instanceof View) { 13712 ((View) mParent).invalidate(true); 13713 } 13714 } 13715 13716 /** 13717 * @hide 13718 */ 13719 protected void invalidateParentIfNeededAndWasQuickRejected() { 13720 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13721 // View was rejected last time it was drawn by its parent; this may have changed 13722 invalidateParentIfNeeded(); 13723 } 13724 } 13725 13726 /** 13727 * Indicates whether this View is opaque. An opaque View guarantees that it will 13728 * draw all the pixels overlapping its bounds using a fully opaque color. 13729 * 13730 * Subclasses of View should override this method whenever possible to indicate 13731 * whether an instance is opaque. Opaque Views are treated in a special way by 13732 * the View hierarchy, possibly allowing it to perform optimizations during 13733 * invalidate/draw passes. 13734 * 13735 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13736 */ 13737 @ViewDebug.ExportedProperty(category = "drawing") 13738 public boolean isOpaque() { 13739 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13740 getFinalAlpha() >= 1.0f; 13741 } 13742 13743 /** 13744 * @hide 13745 */ 13746 protected void computeOpaqueFlags() { 13747 // Opaque if: 13748 // - Has a background 13749 // - Background is opaque 13750 // - Doesn't have scrollbars or scrollbars overlay 13751 13752 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13753 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13754 } else { 13755 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13756 } 13757 13758 final int flags = mViewFlags; 13759 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13760 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13761 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13762 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13763 } else { 13764 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13765 } 13766 } 13767 13768 /** 13769 * @hide 13770 */ 13771 protected boolean hasOpaqueScrollbars() { 13772 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13773 } 13774 13775 /** 13776 * @return A handler associated with the thread running the View. This 13777 * handler can be used to pump events in the UI events queue. 13778 */ 13779 public Handler getHandler() { 13780 final AttachInfo attachInfo = mAttachInfo; 13781 if (attachInfo != null) { 13782 return attachInfo.mHandler; 13783 } 13784 return null; 13785 } 13786 13787 /** 13788 * Returns the queue of runnable for this view. 13789 * 13790 * @return the queue of runnables for this view 13791 */ 13792 private HandlerActionQueue getRunQueue() { 13793 if (mRunQueue == null) { 13794 mRunQueue = new HandlerActionQueue(); 13795 } 13796 return mRunQueue; 13797 } 13798 13799 /** 13800 * Gets the view root associated with the View. 13801 * @return The view root, or null if none. 13802 * @hide 13803 */ 13804 public ViewRootImpl getViewRootImpl() { 13805 if (mAttachInfo != null) { 13806 return mAttachInfo.mViewRootImpl; 13807 } 13808 return null; 13809 } 13810 13811 /** 13812 * @hide 13813 */ 13814 public ThreadedRenderer getHardwareRenderer() { 13815 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 13816 } 13817 13818 /** 13819 * <p>Causes the Runnable to be added to the message queue. 13820 * The runnable will be run on the user interface thread.</p> 13821 * 13822 * @param action The Runnable that will be executed. 13823 * 13824 * @return Returns true if the Runnable was successfully placed in to the 13825 * message queue. Returns false on failure, usually because the 13826 * looper processing the message queue is exiting. 13827 * 13828 * @see #postDelayed 13829 * @see #removeCallbacks 13830 */ 13831 public boolean post(Runnable action) { 13832 final AttachInfo attachInfo = mAttachInfo; 13833 if (attachInfo != null) { 13834 return attachInfo.mHandler.post(action); 13835 } 13836 13837 // Postpone the runnable until we know on which thread it needs to run. 13838 // Assume that the runnable will be successfully placed after attach. 13839 getRunQueue().post(action); 13840 return true; 13841 } 13842 13843 /** 13844 * <p>Causes the Runnable to be added to the message queue, to be run 13845 * after the specified amount of time elapses. 13846 * The runnable will be run on the user interface thread.</p> 13847 * 13848 * @param action The Runnable that will be executed. 13849 * @param delayMillis The delay (in milliseconds) until the Runnable 13850 * will be executed. 13851 * 13852 * @return true if the Runnable was successfully placed in to the 13853 * message queue. Returns false on failure, usually because the 13854 * looper processing the message queue is exiting. Note that a 13855 * result of true does not mean the Runnable will be processed -- 13856 * if the looper is quit before the delivery time of the message 13857 * occurs then the message will be dropped. 13858 * 13859 * @see #post 13860 * @see #removeCallbacks 13861 */ 13862 public boolean postDelayed(Runnable action, long delayMillis) { 13863 final AttachInfo attachInfo = mAttachInfo; 13864 if (attachInfo != null) { 13865 return attachInfo.mHandler.postDelayed(action, delayMillis); 13866 } 13867 13868 // Postpone the runnable until we know on which thread it needs to run. 13869 // Assume that the runnable will be successfully placed after attach. 13870 getRunQueue().postDelayed(action, delayMillis); 13871 return true; 13872 } 13873 13874 /** 13875 * <p>Causes the Runnable to execute on the next animation time step. 13876 * The runnable will be run on the user interface thread.</p> 13877 * 13878 * @param action The Runnable that will be executed. 13879 * 13880 * @see #postOnAnimationDelayed 13881 * @see #removeCallbacks 13882 */ 13883 public void postOnAnimation(Runnable action) { 13884 final AttachInfo attachInfo = mAttachInfo; 13885 if (attachInfo != null) { 13886 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13887 Choreographer.CALLBACK_ANIMATION, action, null); 13888 } else { 13889 // Postpone the runnable until we know 13890 // on which thread it needs to run. 13891 getRunQueue().post(action); 13892 } 13893 } 13894 13895 /** 13896 * <p>Causes the Runnable to execute on the next animation time step, 13897 * after the specified amount of time elapses. 13898 * The runnable will be run on the user interface thread.</p> 13899 * 13900 * @param action The Runnable that will be executed. 13901 * @param delayMillis The delay (in milliseconds) until the Runnable 13902 * will be executed. 13903 * 13904 * @see #postOnAnimation 13905 * @see #removeCallbacks 13906 */ 13907 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13908 final AttachInfo attachInfo = mAttachInfo; 13909 if (attachInfo != null) { 13910 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13911 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13912 } else { 13913 // Postpone the runnable until we know 13914 // on which thread it needs to run. 13915 getRunQueue().postDelayed(action, delayMillis); 13916 } 13917 } 13918 13919 /** 13920 * <p>Removes the specified Runnable from the message queue.</p> 13921 * 13922 * @param action The Runnable to remove from the message handling queue 13923 * 13924 * @return true if this view could ask the Handler to remove the Runnable, 13925 * false otherwise. When the returned value is true, the Runnable 13926 * may or may not have been actually removed from the message queue 13927 * (for instance, if the Runnable was not in the queue already.) 13928 * 13929 * @see #post 13930 * @see #postDelayed 13931 * @see #postOnAnimation 13932 * @see #postOnAnimationDelayed 13933 */ 13934 public boolean removeCallbacks(Runnable action) { 13935 if (action != null) { 13936 final AttachInfo attachInfo = mAttachInfo; 13937 if (attachInfo != null) { 13938 attachInfo.mHandler.removeCallbacks(action); 13939 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13940 Choreographer.CALLBACK_ANIMATION, action, null); 13941 } 13942 getRunQueue().removeCallbacks(action); 13943 } 13944 return true; 13945 } 13946 13947 /** 13948 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13949 * Use this to invalidate the View from a non-UI thread.</p> 13950 * 13951 * <p>This method can be invoked from outside of the UI thread 13952 * only when this View is attached to a window.</p> 13953 * 13954 * @see #invalidate() 13955 * @see #postInvalidateDelayed(long) 13956 */ 13957 public void postInvalidate() { 13958 postInvalidateDelayed(0); 13959 } 13960 13961 /** 13962 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13963 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13964 * 13965 * <p>This method can be invoked from outside of the UI thread 13966 * only when this View is attached to a window.</p> 13967 * 13968 * @param left The left coordinate of the rectangle to invalidate. 13969 * @param top The top coordinate of the rectangle to invalidate. 13970 * @param right The right coordinate of the rectangle to invalidate. 13971 * @param bottom The bottom coordinate of the rectangle to invalidate. 13972 * 13973 * @see #invalidate(int, int, int, int) 13974 * @see #invalidate(Rect) 13975 * @see #postInvalidateDelayed(long, int, int, int, int) 13976 */ 13977 public void postInvalidate(int left, int top, int right, int bottom) { 13978 postInvalidateDelayed(0, left, top, right, bottom); 13979 } 13980 13981 /** 13982 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13983 * loop. Waits for the specified amount of time.</p> 13984 * 13985 * <p>This method can be invoked from outside of the UI thread 13986 * only when this View is attached to a window.</p> 13987 * 13988 * @param delayMilliseconds the duration in milliseconds to delay the 13989 * invalidation by 13990 * 13991 * @see #invalidate() 13992 * @see #postInvalidate() 13993 */ 13994 public void postInvalidateDelayed(long delayMilliseconds) { 13995 // We try only with the AttachInfo because there's no point in invalidating 13996 // if we are not attached to our window 13997 final AttachInfo attachInfo = mAttachInfo; 13998 if (attachInfo != null) { 13999 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 14000 } 14001 } 14002 14003 /** 14004 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 14005 * through the event loop. Waits for the specified amount of time.</p> 14006 * 14007 * <p>This method can be invoked from outside of the UI thread 14008 * only when this View is attached to a window.</p> 14009 * 14010 * @param delayMilliseconds the duration in milliseconds to delay the 14011 * invalidation by 14012 * @param left The left coordinate of the rectangle to invalidate. 14013 * @param top The top coordinate of the rectangle to invalidate. 14014 * @param right The right coordinate of the rectangle to invalidate. 14015 * @param bottom The bottom coordinate of the rectangle to invalidate. 14016 * 14017 * @see #invalidate(int, int, int, int) 14018 * @see #invalidate(Rect) 14019 * @see #postInvalidate(int, int, int, int) 14020 */ 14021 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14022 int right, int bottom) { 14023 14024 // We try only with the AttachInfo because there's no point in invalidating 14025 // if we are not attached to our window 14026 final AttachInfo attachInfo = mAttachInfo; 14027 if (attachInfo != null) { 14028 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14029 info.target = this; 14030 info.left = left; 14031 info.top = top; 14032 info.right = right; 14033 info.bottom = bottom; 14034 14035 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14036 } 14037 } 14038 14039 /** 14040 * <p>Cause an invalidate to happen on the next animation time step, typically the 14041 * next display frame.</p> 14042 * 14043 * <p>This method can be invoked from outside of the UI thread 14044 * only when this View is attached to a window.</p> 14045 * 14046 * @see #invalidate() 14047 */ 14048 public void postInvalidateOnAnimation() { 14049 // We try only with the AttachInfo because there's no point in invalidating 14050 // if we are not attached to our window 14051 final AttachInfo attachInfo = mAttachInfo; 14052 if (attachInfo != null) { 14053 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14054 } 14055 } 14056 14057 /** 14058 * <p>Cause an invalidate of the specified area to happen on the next animation 14059 * time step, typically the next display frame.</p> 14060 * 14061 * <p>This method can be invoked from outside of the UI thread 14062 * only when this View is attached to a window.</p> 14063 * 14064 * @param left The left coordinate of the rectangle to invalidate. 14065 * @param top The top coordinate of the rectangle to invalidate. 14066 * @param right The right coordinate of the rectangle to invalidate. 14067 * @param bottom The bottom coordinate of the rectangle to invalidate. 14068 * 14069 * @see #invalidate(int, int, int, int) 14070 * @see #invalidate(Rect) 14071 */ 14072 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14073 // We try only with the AttachInfo because there's no point in invalidating 14074 // if we are not attached to our window 14075 final AttachInfo attachInfo = mAttachInfo; 14076 if (attachInfo != null) { 14077 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14078 info.target = this; 14079 info.left = left; 14080 info.top = top; 14081 info.right = right; 14082 info.bottom = bottom; 14083 14084 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14085 } 14086 } 14087 14088 /** 14089 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14090 * This event is sent at most once every 14091 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14092 */ 14093 private void postSendViewScrolledAccessibilityEventCallback() { 14094 if (mSendViewScrolledAccessibilityEvent == null) { 14095 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14096 } 14097 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14098 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14099 postDelayed(mSendViewScrolledAccessibilityEvent, 14100 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14101 } 14102 } 14103 14104 /** 14105 * Called by a parent to request that a child update its values for mScrollX 14106 * and mScrollY if necessary. This will typically be done if the child is 14107 * animating a scroll using a {@link android.widget.Scroller Scroller} 14108 * object. 14109 */ 14110 public void computeScroll() { 14111 } 14112 14113 /** 14114 * <p>Indicate whether the horizontal edges are faded when the view is 14115 * scrolled horizontally.</p> 14116 * 14117 * @return true if the horizontal edges should are faded on scroll, false 14118 * otherwise 14119 * 14120 * @see #setHorizontalFadingEdgeEnabled(boolean) 14121 * 14122 * @attr ref android.R.styleable#View_requiresFadingEdge 14123 */ 14124 public boolean isHorizontalFadingEdgeEnabled() { 14125 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14126 } 14127 14128 /** 14129 * <p>Define whether the horizontal edges should be faded when this view 14130 * is scrolled horizontally.</p> 14131 * 14132 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14133 * be faded when the view is scrolled 14134 * horizontally 14135 * 14136 * @see #isHorizontalFadingEdgeEnabled() 14137 * 14138 * @attr ref android.R.styleable#View_requiresFadingEdge 14139 */ 14140 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14141 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14142 if (horizontalFadingEdgeEnabled) { 14143 initScrollCache(); 14144 } 14145 14146 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14147 } 14148 } 14149 14150 /** 14151 * <p>Indicate whether the vertical edges are faded when the view is 14152 * scrolled horizontally.</p> 14153 * 14154 * @return true if the vertical edges should are faded on scroll, false 14155 * otherwise 14156 * 14157 * @see #setVerticalFadingEdgeEnabled(boolean) 14158 * 14159 * @attr ref android.R.styleable#View_requiresFadingEdge 14160 */ 14161 public boolean isVerticalFadingEdgeEnabled() { 14162 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14163 } 14164 14165 /** 14166 * <p>Define whether the vertical edges should be faded when this view 14167 * is scrolled vertically.</p> 14168 * 14169 * @param verticalFadingEdgeEnabled true if the vertical edges should 14170 * be faded when the view is scrolled 14171 * vertically 14172 * 14173 * @see #isVerticalFadingEdgeEnabled() 14174 * 14175 * @attr ref android.R.styleable#View_requiresFadingEdge 14176 */ 14177 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14178 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14179 if (verticalFadingEdgeEnabled) { 14180 initScrollCache(); 14181 } 14182 14183 mViewFlags ^= FADING_EDGE_VERTICAL; 14184 } 14185 } 14186 14187 /** 14188 * Returns the strength, or intensity, of the top faded edge. The strength is 14189 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14190 * returns 0.0 or 1.0 but no value in between. 14191 * 14192 * Subclasses should override this method to provide a smoother fade transition 14193 * when scrolling occurs. 14194 * 14195 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14196 */ 14197 protected float getTopFadingEdgeStrength() { 14198 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14199 } 14200 14201 /** 14202 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14203 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14204 * returns 0.0 or 1.0 but no value in between. 14205 * 14206 * Subclasses should override this method to provide a smoother fade transition 14207 * when scrolling occurs. 14208 * 14209 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14210 */ 14211 protected float getBottomFadingEdgeStrength() { 14212 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14213 computeVerticalScrollRange() ? 1.0f : 0.0f; 14214 } 14215 14216 /** 14217 * Returns the strength, or intensity, of the left faded edge. The strength is 14218 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14219 * returns 0.0 or 1.0 but no value in between. 14220 * 14221 * Subclasses should override this method to provide a smoother fade transition 14222 * when scrolling occurs. 14223 * 14224 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14225 */ 14226 protected float getLeftFadingEdgeStrength() { 14227 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14228 } 14229 14230 /** 14231 * Returns the strength, or intensity, of the right faded edge. The strength is 14232 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14233 * returns 0.0 or 1.0 but no value in between. 14234 * 14235 * Subclasses should override this method to provide a smoother fade transition 14236 * when scrolling occurs. 14237 * 14238 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14239 */ 14240 protected float getRightFadingEdgeStrength() { 14241 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14242 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14243 } 14244 14245 /** 14246 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14247 * scrollbar is not drawn by default.</p> 14248 * 14249 * @return true if the horizontal scrollbar should be painted, false 14250 * otherwise 14251 * 14252 * @see #setHorizontalScrollBarEnabled(boolean) 14253 */ 14254 public boolean isHorizontalScrollBarEnabled() { 14255 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14256 } 14257 14258 /** 14259 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14260 * scrollbar is not drawn by default.</p> 14261 * 14262 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14263 * be painted 14264 * 14265 * @see #isHorizontalScrollBarEnabled() 14266 */ 14267 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14268 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14269 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14270 computeOpaqueFlags(); 14271 resolvePadding(); 14272 } 14273 } 14274 14275 /** 14276 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14277 * scrollbar is not drawn by default.</p> 14278 * 14279 * @return true if the vertical scrollbar should be painted, false 14280 * otherwise 14281 * 14282 * @see #setVerticalScrollBarEnabled(boolean) 14283 */ 14284 public boolean isVerticalScrollBarEnabled() { 14285 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14286 } 14287 14288 /** 14289 * <p>Define whether the vertical scrollbar should be drawn or not. The 14290 * scrollbar is not drawn by default.</p> 14291 * 14292 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14293 * be painted 14294 * 14295 * @see #isVerticalScrollBarEnabled() 14296 */ 14297 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14298 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14299 mViewFlags ^= SCROLLBARS_VERTICAL; 14300 computeOpaqueFlags(); 14301 resolvePadding(); 14302 } 14303 } 14304 14305 /** 14306 * @hide 14307 */ 14308 protected void recomputePadding() { 14309 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14310 } 14311 14312 /** 14313 * Define whether scrollbars will fade when the view is not scrolling. 14314 * 14315 * @param fadeScrollbars whether to enable fading 14316 * 14317 * @attr ref android.R.styleable#View_fadeScrollbars 14318 */ 14319 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14320 initScrollCache(); 14321 final ScrollabilityCache scrollabilityCache = mScrollCache; 14322 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14323 if (fadeScrollbars) { 14324 scrollabilityCache.state = ScrollabilityCache.OFF; 14325 } else { 14326 scrollabilityCache.state = ScrollabilityCache.ON; 14327 } 14328 } 14329 14330 /** 14331 * 14332 * Returns true if scrollbars will fade when this view is not scrolling 14333 * 14334 * @return true if scrollbar fading is enabled 14335 * 14336 * @attr ref android.R.styleable#View_fadeScrollbars 14337 */ 14338 public boolean isScrollbarFadingEnabled() { 14339 return mScrollCache != null && mScrollCache.fadeScrollBars; 14340 } 14341 14342 /** 14343 * 14344 * Returns the delay before scrollbars fade. 14345 * 14346 * @return the delay before scrollbars fade 14347 * 14348 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14349 */ 14350 public int getScrollBarDefaultDelayBeforeFade() { 14351 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14352 mScrollCache.scrollBarDefaultDelayBeforeFade; 14353 } 14354 14355 /** 14356 * Define the delay before scrollbars fade. 14357 * 14358 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14359 * 14360 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14361 */ 14362 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14363 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14364 } 14365 14366 /** 14367 * 14368 * Returns the scrollbar fade duration. 14369 * 14370 * @return the scrollbar fade duration 14371 * 14372 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14373 */ 14374 public int getScrollBarFadeDuration() { 14375 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14376 mScrollCache.scrollBarFadeDuration; 14377 } 14378 14379 /** 14380 * Define the scrollbar fade duration. 14381 * 14382 * @param scrollBarFadeDuration - the scrollbar fade duration 14383 * 14384 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14385 */ 14386 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14387 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14388 } 14389 14390 /** 14391 * 14392 * Returns the scrollbar size. 14393 * 14394 * @return the scrollbar size 14395 * 14396 * @attr ref android.R.styleable#View_scrollbarSize 14397 */ 14398 public int getScrollBarSize() { 14399 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14400 mScrollCache.scrollBarSize; 14401 } 14402 14403 /** 14404 * Define the scrollbar size. 14405 * 14406 * @param scrollBarSize - the scrollbar size 14407 * 14408 * @attr ref android.R.styleable#View_scrollbarSize 14409 */ 14410 public void setScrollBarSize(int scrollBarSize) { 14411 getScrollCache().scrollBarSize = scrollBarSize; 14412 } 14413 14414 /** 14415 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14416 * inset. When inset, they add to the padding of the view. And the scrollbars 14417 * can be drawn inside the padding area or on the edge of the view. For example, 14418 * if a view has a background drawable and you want to draw the scrollbars 14419 * inside the padding specified by the drawable, you can use 14420 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14421 * appear at the edge of the view, ignoring the padding, then you can use 14422 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14423 * @param style the style of the scrollbars. Should be one of 14424 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14425 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14426 * @see #SCROLLBARS_INSIDE_OVERLAY 14427 * @see #SCROLLBARS_INSIDE_INSET 14428 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14429 * @see #SCROLLBARS_OUTSIDE_INSET 14430 * 14431 * @attr ref android.R.styleable#View_scrollbarStyle 14432 */ 14433 public void setScrollBarStyle(@ScrollBarStyle int style) { 14434 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14435 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14436 computeOpaqueFlags(); 14437 resolvePadding(); 14438 } 14439 } 14440 14441 /** 14442 * <p>Returns the current scrollbar style.</p> 14443 * @return the current scrollbar style 14444 * @see #SCROLLBARS_INSIDE_OVERLAY 14445 * @see #SCROLLBARS_INSIDE_INSET 14446 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14447 * @see #SCROLLBARS_OUTSIDE_INSET 14448 * 14449 * @attr ref android.R.styleable#View_scrollbarStyle 14450 */ 14451 @ViewDebug.ExportedProperty(mapping = { 14452 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14453 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14454 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14455 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14456 }) 14457 @ScrollBarStyle 14458 public int getScrollBarStyle() { 14459 return mViewFlags & SCROLLBARS_STYLE_MASK; 14460 } 14461 14462 /** 14463 * <p>Compute the horizontal range that the horizontal scrollbar 14464 * represents.</p> 14465 * 14466 * <p>The range is expressed in arbitrary units that must be the same as the 14467 * units used by {@link #computeHorizontalScrollExtent()} and 14468 * {@link #computeHorizontalScrollOffset()}.</p> 14469 * 14470 * <p>The default range is the drawing width of this view.</p> 14471 * 14472 * @return the total horizontal range represented by the horizontal 14473 * scrollbar 14474 * 14475 * @see #computeHorizontalScrollExtent() 14476 * @see #computeHorizontalScrollOffset() 14477 * @see android.widget.ScrollBarDrawable 14478 */ 14479 protected int computeHorizontalScrollRange() { 14480 return getWidth(); 14481 } 14482 14483 /** 14484 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14485 * within the horizontal range. This value is used to compute the position 14486 * of the thumb within the scrollbar's track.</p> 14487 * 14488 * <p>The range is expressed in arbitrary units that must be the same as the 14489 * units used by {@link #computeHorizontalScrollRange()} and 14490 * {@link #computeHorizontalScrollExtent()}.</p> 14491 * 14492 * <p>The default offset is the scroll offset of this view.</p> 14493 * 14494 * @return the horizontal offset of the scrollbar's thumb 14495 * 14496 * @see #computeHorizontalScrollRange() 14497 * @see #computeHorizontalScrollExtent() 14498 * @see android.widget.ScrollBarDrawable 14499 */ 14500 protected int computeHorizontalScrollOffset() { 14501 return mScrollX; 14502 } 14503 14504 /** 14505 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14506 * within the horizontal range. This value is used to compute the length 14507 * of the thumb within the scrollbar's track.</p> 14508 * 14509 * <p>The range is expressed in arbitrary units that must be the same as the 14510 * units used by {@link #computeHorizontalScrollRange()} and 14511 * {@link #computeHorizontalScrollOffset()}.</p> 14512 * 14513 * <p>The default extent is the drawing width of this view.</p> 14514 * 14515 * @return the horizontal extent of the scrollbar's thumb 14516 * 14517 * @see #computeHorizontalScrollRange() 14518 * @see #computeHorizontalScrollOffset() 14519 * @see android.widget.ScrollBarDrawable 14520 */ 14521 protected int computeHorizontalScrollExtent() { 14522 return getWidth(); 14523 } 14524 14525 /** 14526 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14527 * 14528 * <p>The range is expressed in arbitrary units that must be the same as the 14529 * units used by {@link #computeVerticalScrollExtent()} and 14530 * {@link #computeVerticalScrollOffset()}.</p> 14531 * 14532 * @return the total vertical range represented by the vertical scrollbar 14533 * 14534 * <p>The default range is the drawing height of this view.</p> 14535 * 14536 * @see #computeVerticalScrollExtent() 14537 * @see #computeVerticalScrollOffset() 14538 * @see android.widget.ScrollBarDrawable 14539 */ 14540 protected int computeVerticalScrollRange() { 14541 return getHeight(); 14542 } 14543 14544 /** 14545 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14546 * within the horizontal range. This value is used to compute the position 14547 * of the thumb within the scrollbar's track.</p> 14548 * 14549 * <p>The range is expressed in arbitrary units that must be the same as the 14550 * units used by {@link #computeVerticalScrollRange()} and 14551 * {@link #computeVerticalScrollExtent()}.</p> 14552 * 14553 * <p>The default offset is the scroll offset of this view.</p> 14554 * 14555 * @return the vertical offset of the scrollbar's thumb 14556 * 14557 * @see #computeVerticalScrollRange() 14558 * @see #computeVerticalScrollExtent() 14559 * @see android.widget.ScrollBarDrawable 14560 */ 14561 protected int computeVerticalScrollOffset() { 14562 return mScrollY; 14563 } 14564 14565 /** 14566 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14567 * within the vertical range. This value is used to compute the length 14568 * of the thumb within the scrollbar's track.</p> 14569 * 14570 * <p>The range is expressed in arbitrary units that must be the same as the 14571 * units used by {@link #computeVerticalScrollRange()} and 14572 * {@link #computeVerticalScrollOffset()}.</p> 14573 * 14574 * <p>The default extent is the drawing height of this view.</p> 14575 * 14576 * @return the vertical extent of the scrollbar's thumb 14577 * 14578 * @see #computeVerticalScrollRange() 14579 * @see #computeVerticalScrollOffset() 14580 * @see android.widget.ScrollBarDrawable 14581 */ 14582 protected int computeVerticalScrollExtent() { 14583 return getHeight(); 14584 } 14585 14586 /** 14587 * Check if this view can be scrolled horizontally in a certain direction. 14588 * 14589 * @param direction Negative to check scrolling left, positive to check scrolling right. 14590 * @return true if this view can be scrolled in the specified direction, false otherwise. 14591 */ 14592 public boolean canScrollHorizontally(int direction) { 14593 final int offset = computeHorizontalScrollOffset(); 14594 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14595 if (range == 0) return false; 14596 if (direction < 0) { 14597 return offset > 0; 14598 } else { 14599 return offset < range - 1; 14600 } 14601 } 14602 14603 /** 14604 * Check if this view can be scrolled vertically in a certain direction. 14605 * 14606 * @param direction Negative to check scrolling up, positive to check scrolling down. 14607 * @return true if this view can be scrolled in the specified direction, false otherwise. 14608 */ 14609 public boolean canScrollVertically(int direction) { 14610 final int offset = computeVerticalScrollOffset(); 14611 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14612 if (range == 0) return false; 14613 if (direction < 0) { 14614 return offset > 0; 14615 } else { 14616 return offset < range - 1; 14617 } 14618 } 14619 14620 void getScrollIndicatorBounds(@NonNull Rect out) { 14621 out.left = mScrollX; 14622 out.right = mScrollX + mRight - mLeft; 14623 out.top = mScrollY; 14624 out.bottom = mScrollY + mBottom - mTop; 14625 } 14626 14627 private void onDrawScrollIndicators(Canvas c) { 14628 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14629 // No scroll indicators enabled. 14630 return; 14631 } 14632 14633 final Drawable dr = mScrollIndicatorDrawable; 14634 if (dr == null) { 14635 // Scroll indicators aren't supported here. 14636 return; 14637 } 14638 14639 final int h = dr.getIntrinsicHeight(); 14640 final int w = dr.getIntrinsicWidth(); 14641 final Rect rect = mAttachInfo.mTmpInvalRect; 14642 getScrollIndicatorBounds(rect); 14643 14644 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14645 final boolean canScrollUp = canScrollVertically(-1); 14646 if (canScrollUp) { 14647 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14648 dr.draw(c); 14649 } 14650 } 14651 14652 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14653 final boolean canScrollDown = canScrollVertically(1); 14654 if (canScrollDown) { 14655 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14656 dr.draw(c); 14657 } 14658 } 14659 14660 final int leftRtl; 14661 final int rightRtl; 14662 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14663 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14664 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14665 } else { 14666 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14667 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14668 } 14669 14670 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14671 if ((mPrivateFlags3 & leftMask) != 0) { 14672 final boolean canScrollLeft = canScrollHorizontally(-1); 14673 if (canScrollLeft) { 14674 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14675 dr.draw(c); 14676 } 14677 } 14678 14679 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14680 if ((mPrivateFlags3 & rightMask) != 0) { 14681 final boolean canScrollRight = canScrollHorizontally(1); 14682 if (canScrollRight) { 14683 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14684 dr.draw(c); 14685 } 14686 } 14687 } 14688 14689 private void getHorizontalScrollBarBounds(Rect bounds) { 14690 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14691 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14692 && !isVerticalScrollBarHidden(); 14693 final int size = getHorizontalScrollbarHeight(); 14694 final int verticalScrollBarGap = drawVerticalScrollBar ? 14695 getVerticalScrollbarWidth() : 0; 14696 final int width = mRight - mLeft; 14697 final int height = mBottom - mTop; 14698 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14699 bounds.left = mScrollX + (mPaddingLeft & inside); 14700 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14701 bounds.bottom = bounds.top + size; 14702 } 14703 14704 private void getVerticalScrollBarBounds(Rect bounds) { 14705 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14706 final int size = getVerticalScrollbarWidth(); 14707 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14708 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14709 verticalScrollbarPosition = isLayoutRtl() ? 14710 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14711 } 14712 final int width = mRight - mLeft; 14713 final int height = mBottom - mTop; 14714 switch (verticalScrollbarPosition) { 14715 default: 14716 case SCROLLBAR_POSITION_RIGHT: 14717 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14718 break; 14719 case SCROLLBAR_POSITION_LEFT: 14720 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14721 break; 14722 } 14723 bounds.top = mScrollY + (mPaddingTop & inside); 14724 bounds.right = bounds.left + size; 14725 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14726 } 14727 14728 /** 14729 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14730 * scrollbars are painted only if they have been awakened first.</p> 14731 * 14732 * @param canvas the canvas on which to draw the scrollbars 14733 * 14734 * @see #awakenScrollBars(int) 14735 */ 14736 protected final void onDrawScrollBars(Canvas canvas) { 14737 // scrollbars are drawn only when the animation is running 14738 final ScrollabilityCache cache = mScrollCache; 14739 if (cache != null) { 14740 14741 int state = cache.state; 14742 14743 if (state == ScrollabilityCache.OFF) { 14744 return; 14745 } 14746 14747 boolean invalidate = false; 14748 14749 if (state == ScrollabilityCache.FADING) { 14750 // We're fading -- get our fade interpolation 14751 if (cache.interpolatorValues == null) { 14752 cache.interpolatorValues = new float[1]; 14753 } 14754 14755 float[] values = cache.interpolatorValues; 14756 14757 // Stops the animation if we're done 14758 if (cache.scrollBarInterpolator.timeToValues(values) == 14759 Interpolator.Result.FREEZE_END) { 14760 cache.state = ScrollabilityCache.OFF; 14761 } else { 14762 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14763 } 14764 14765 // This will make the scroll bars inval themselves after 14766 // drawing. We only want this when we're fading so that 14767 // we prevent excessive redraws 14768 invalidate = true; 14769 } else { 14770 // We're just on -- but we may have been fading before so 14771 // reset alpha 14772 cache.scrollBar.mutate().setAlpha(255); 14773 } 14774 14775 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14776 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14777 && !isVerticalScrollBarHidden(); 14778 14779 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14780 final ScrollBarDrawable scrollBar = cache.scrollBar; 14781 14782 if (drawHorizontalScrollBar) { 14783 scrollBar.setParameters(computeHorizontalScrollRange(), 14784 computeHorizontalScrollOffset(), 14785 computeHorizontalScrollExtent(), false); 14786 final Rect bounds = cache.mScrollBarBounds; 14787 getHorizontalScrollBarBounds(bounds); 14788 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14789 bounds.right, bounds.bottom); 14790 if (invalidate) { 14791 invalidate(bounds); 14792 } 14793 } 14794 14795 if (drawVerticalScrollBar) { 14796 scrollBar.setParameters(computeVerticalScrollRange(), 14797 computeVerticalScrollOffset(), 14798 computeVerticalScrollExtent(), true); 14799 final Rect bounds = cache.mScrollBarBounds; 14800 getVerticalScrollBarBounds(bounds); 14801 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14802 bounds.right, bounds.bottom); 14803 if (invalidate) { 14804 invalidate(bounds); 14805 } 14806 } 14807 } 14808 } 14809 } 14810 14811 /** 14812 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14813 * FastScroller is visible. 14814 * @return whether to temporarily hide the vertical scrollbar 14815 * @hide 14816 */ 14817 protected boolean isVerticalScrollBarHidden() { 14818 return false; 14819 } 14820 14821 /** 14822 * <p>Draw the horizontal scrollbar if 14823 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14824 * 14825 * @param canvas the canvas on which to draw the scrollbar 14826 * @param scrollBar the scrollbar's drawable 14827 * 14828 * @see #isHorizontalScrollBarEnabled() 14829 * @see #computeHorizontalScrollRange() 14830 * @see #computeHorizontalScrollExtent() 14831 * @see #computeHorizontalScrollOffset() 14832 * @see android.widget.ScrollBarDrawable 14833 * @hide 14834 */ 14835 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14836 int l, int t, int r, int b) { 14837 scrollBar.setBounds(l, t, r, b); 14838 scrollBar.draw(canvas); 14839 } 14840 14841 /** 14842 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14843 * returns true.</p> 14844 * 14845 * @param canvas the canvas on which to draw the scrollbar 14846 * @param scrollBar the scrollbar's drawable 14847 * 14848 * @see #isVerticalScrollBarEnabled() 14849 * @see #computeVerticalScrollRange() 14850 * @see #computeVerticalScrollExtent() 14851 * @see #computeVerticalScrollOffset() 14852 * @see android.widget.ScrollBarDrawable 14853 * @hide 14854 */ 14855 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14856 int l, int t, int r, int b) { 14857 scrollBar.setBounds(l, t, r, b); 14858 scrollBar.draw(canvas); 14859 } 14860 14861 /** 14862 * Implement this to do your drawing. 14863 * 14864 * @param canvas the canvas on which the background will be drawn 14865 */ 14866 protected void onDraw(Canvas canvas) { 14867 } 14868 14869 /* 14870 * Caller is responsible for calling requestLayout if necessary. 14871 * (This allows addViewInLayout to not request a new layout.) 14872 */ 14873 void assignParent(ViewParent parent) { 14874 if (mParent == null) { 14875 mParent = parent; 14876 } else if (parent == null) { 14877 mParent = null; 14878 } else { 14879 throw new RuntimeException("view " + this + " being added, but" 14880 + " it already has a parent"); 14881 } 14882 } 14883 14884 /** 14885 * This is called when the view is attached to a window. At this point it 14886 * has a Surface and will start drawing. Note that this function is 14887 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14888 * however it may be called any time before the first onDraw -- including 14889 * before or after {@link #onMeasure(int, int)}. 14890 * 14891 * @see #onDetachedFromWindow() 14892 */ 14893 @CallSuper 14894 protected void onAttachedToWindow() { 14895 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14896 mParent.requestTransparentRegion(this); 14897 } 14898 14899 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14900 14901 jumpDrawablesToCurrentState(); 14902 14903 resetSubtreeAccessibilityStateChanged(); 14904 14905 // rebuild, since Outline not maintained while View is detached 14906 rebuildOutline(); 14907 14908 if (isFocused()) { 14909 InputMethodManager imm = InputMethodManager.peekInstance(); 14910 if (imm != null) { 14911 imm.focusIn(this); 14912 } 14913 } 14914 } 14915 14916 /** 14917 * Resolve all RTL related properties. 14918 * 14919 * @return true if resolution of RTL properties has been done 14920 * 14921 * @hide 14922 */ 14923 public boolean resolveRtlPropertiesIfNeeded() { 14924 if (!needRtlPropertiesResolution()) return false; 14925 14926 // Order is important here: LayoutDirection MUST be resolved first 14927 if (!isLayoutDirectionResolved()) { 14928 resolveLayoutDirection(); 14929 resolveLayoutParams(); 14930 } 14931 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14932 if (!isTextDirectionResolved()) { 14933 resolveTextDirection(); 14934 } 14935 if (!isTextAlignmentResolved()) { 14936 resolveTextAlignment(); 14937 } 14938 // Should resolve Drawables before Padding because we need the layout direction of the 14939 // Drawable to correctly resolve Padding. 14940 if (!areDrawablesResolved()) { 14941 resolveDrawables(); 14942 } 14943 if (!isPaddingResolved()) { 14944 resolvePadding(); 14945 } 14946 onRtlPropertiesChanged(getLayoutDirection()); 14947 return true; 14948 } 14949 14950 /** 14951 * Reset resolution of all RTL related properties. 14952 * 14953 * @hide 14954 */ 14955 public void resetRtlProperties() { 14956 resetResolvedLayoutDirection(); 14957 resetResolvedTextDirection(); 14958 resetResolvedTextAlignment(); 14959 resetResolvedPadding(); 14960 resetResolvedDrawables(); 14961 } 14962 14963 /** 14964 * @see #onScreenStateChanged(int) 14965 */ 14966 void dispatchScreenStateChanged(int screenState) { 14967 onScreenStateChanged(screenState); 14968 } 14969 14970 /** 14971 * This method is called whenever the state of the screen this view is 14972 * attached to changes. A state change will usually occurs when the screen 14973 * turns on or off (whether it happens automatically or the user does it 14974 * manually.) 14975 * 14976 * @param screenState The new state of the screen. Can be either 14977 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14978 */ 14979 public void onScreenStateChanged(int screenState) { 14980 } 14981 14982 /** 14983 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14984 */ 14985 private boolean hasRtlSupport() { 14986 return mContext.getApplicationInfo().hasRtlSupport(); 14987 } 14988 14989 /** 14990 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14991 * RTL not supported) 14992 */ 14993 private boolean isRtlCompatibilityMode() { 14994 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14995 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14996 } 14997 14998 /** 14999 * @return true if RTL properties need resolution. 15000 * 15001 */ 15002 private boolean needRtlPropertiesResolution() { 15003 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 15004 } 15005 15006 /** 15007 * Called when any RTL property (layout direction or text direction or text alignment) has 15008 * been changed. 15009 * 15010 * Subclasses need to override this method to take care of cached information that depends on the 15011 * resolved layout direction, or to inform child views that inherit their layout direction. 15012 * 15013 * The default implementation does nothing. 15014 * 15015 * @param layoutDirection the direction of the layout 15016 * 15017 * @see #LAYOUT_DIRECTION_LTR 15018 * @see #LAYOUT_DIRECTION_RTL 15019 */ 15020 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15021 } 15022 15023 /** 15024 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15025 * that the parent directionality can and will be resolved before its children. 15026 * 15027 * @return true if resolution has been done, false otherwise. 15028 * 15029 * @hide 15030 */ 15031 public boolean resolveLayoutDirection() { 15032 // Clear any previous layout direction resolution 15033 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15034 15035 if (hasRtlSupport()) { 15036 // Set resolved depending on layout direction 15037 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15038 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15039 case LAYOUT_DIRECTION_INHERIT: 15040 // We cannot resolve yet. LTR is by default and let the resolution happen again 15041 // later to get the correct resolved value 15042 if (!canResolveLayoutDirection()) return false; 15043 15044 // Parent has not yet resolved, LTR is still the default 15045 try { 15046 if (!mParent.isLayoutDirectionResolved()) return false; 15047 15048 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15049 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15050 } 15051 } catch (AbstractMethodError e) { 15052 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15053 " does not fully implement ViewParent", e); 15054 } 15055 break; 15056 case LAYOUT_DIRECTION_RTL: 15057 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15058 break; 15059 case LAYOUT_DIRECTION_LOCALE: 15060 if((LAYOUT_DIRECTION_RTL == 15061 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15062 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15063 } 15064 break; 15065 default: 15066 // Nothing to do, LTR by default 15067 } 15068 } 15069 15070 // Set to resolved 15071 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15072 return true; 15073 } 15074 15075 /** 15076 * Check if layout direction resolution can be done. 15077 * 15078 * @return true if layout direction resolution can be done otherwise return false. 15079 */ 15080 public boolean canResolveLayoutDirection() { 15081 switch (getRawLayoutDirection()) { 15082 case LAYOUT_DIRECTION_INHERIT: 15083 if (mParent != null) { 15084 try { 15085 return mParent.canResolveLayoutDirection(); 15086 } catch (AbstractMethodError e) { 15087 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15088 " does not fully implement ViewParent", e); 15089 } 15090 } 15091 return false; 15092 15093 default: 15094 return true; 15095 } 15096 } 15097 15098 /** 15099 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15100 * {@link #onMeasure(int, int)}. 15101 * 15102 * @hide 15103 */ 15104 public void resetResolvedLayoutDirection() { 15105 // Reset the current resolved bits 15106 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15107 } 15108 15109 /** 15110 * @return true if the layout direction is inherited. 15111 * 15112 * @hide 15113 */ 15114 public boolean isLayoutDirectionInherited() { 15115 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15116 } 15117 15118 /** 15119 * @return true if layout direction has been resolved. 15120 */ 15121 public boolean isLayoutDirectionResolved() { 15122 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15123 } 15124 15125 /** 15126 * Return if padding has been resolved 15127 * 15128 * @hide 15129 */ 15130 boolean isPaddingResolved() { 15131 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15132 } 15133 15134 /** 15135 * Resolves padding depending on layout direction, if applicable, and 15136 * recomputes internal padding values to adjust for scroll bars. 15137 * 15138 * @hide 15139 */ 15140 public void resolvePadding() { 15141 final int resolvedLayoutDirection = getLayoutDirection(); 15142 15143 if (!isRtlCompatibilityMode()) { 15144 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15145 // If start / end padding are defined, they will be resolved (hence overriding) to 15146 // left / right or right / left depending on the resolved layout direction. 15147 // If start / end padding are not defined, use the left / right ones. 15148 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15149 Rect padding = sThreadLocal.get(); 15150 if (padding == null) { 15151 padding = new Rect(); 15152 sThreadLocal.set(padding); 15153 } 15154 mBackground.getPadding(padding); 15155 if (!mLeftPaddingDefined) { 15156 mUserPaddingLeftInitial = padding.left; 15157 } 15158 if (!mRightPaddingDefined) { 15159 mUserPaddingRightInitial = padding.right; 15160 } 15161 } 15162 switch (resolvedLayoutDirection) { 15163 case LAYOUT_DIRECTION_RTL: 15164 if (mUserPaddingStart != UNDEFINED_PADDING) { 15165 mUserPaddingRight = mUserPaddingStart; 15166 } else { 15167 mUserPaddingRight = mUserPaddingRightInitial; 15168 } 15169 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15170 mUserPaddingLeft = mUserPaddingEnd; 15171 } else { 15172 mUserPaddingLeft = mUserPaddingLeftInitial; 15173 } 15174 break; 15175 case LAYOUT_DIRECTION_LTR: 15176 default: 15177 if (mUserPaddingStart != UNDEFINED_PADDING) { 15178 mUserPaddingLeft = mUserPaddingStart; 15179 } else { 15180 mUserPaddingLeft = mUserPaddingLeftInitial; 15181 } 15182 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15183 mUserPaddingRight = mUserPaddingEnd; 15184 } else { 15185 mUserPaddingRight = mUserPaddingRightInitial; 15186 } 15187 } 15188 15189 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15190 } 15191 15192 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15193 onRtlPropertiesChanged(resolvedLayoutDirection); 15194 15195 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15196 } 15197 15198 /** 15199 * Reset the resolved layout direction. 15200 * 15201 * @hide 15202 */ 15203 public void resetResolvedPadding() { 15204 resetResolvedPaddingInternal(); 15205 } 15206 15207 /** 15208 * Used when we only want to reset *this* view's padding and not trigger overrides 15209 * in ViewGroup that reset children too. 15210 */ 15211 void resetResolvedPaddingInternal() { 15212 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15213 } 15214 15215 /** 15216 * This is called when the view is detached from a window. At this point it 15217 * no longer has a surface for drawing. 15218 * 15219 * @see #onAttachedToWindow() 15220 */ 15221 @CallSuper 15222 protected void onDetachedFromWindow() { 15223 } 15224 15225 /** 15226 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15227 * after onDetachedFromWindow(). 15228 * 15229 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15230 * The super method should be called at the end of the overridden method to ensure 15231 * subclasses are destroyed first 15232 * 15233 * @hide 15234 */ 15235 @CallSuper 15236 protected void onDetachedFromWindowInternal() { 15237 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15238 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15239 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15240 15241 removeUnsetPressCallback(); 15242 removeLongPressCallback(); 15243 removePerformClickCallback(); 15244 removeSendViewScrolledAccessibilityEventCallback(); 15245 stopNestedScroll(); 15246 15247 // Anything that started animating right before detach should already 15248 // be in its final state when re-attached. 15249 jumpDrawablesToCurrentState(); 15250 15251 destroyDrawingCache(); 15252 15253 cleanupDraw(); 15254 releasePointerCapture(); 15255 mCurrentAnimation = null; 15256 } 15257 15258 private void cleanupDraw() { 15259 resetDisplayList(); 15260 if (mAttachInfo != null) { 15261 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15262 } 15263 } 15264 15265 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15266 } 15267 15268 /** 15269 * @return The number of times this view has been attached to a window 15270 */ 15271 protected int getWindowAttachCount() { 15272 return mWindowAttachCount; 15273 } 15274 15275 /** 15276 * Retrieve a unique token identifying the window this view is attached to. 15277 * @return Return the window's token for use in 15278 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15279 */ 15280 public IBinder getWindowToken() { 15281 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15282 } 15283 15284 /** 15285 * Retrieve the {@link WindowId} for the window this view is 15286 * currently attached to. 15287 */ 15288 public WindowId getWindowId() { 15289 if (mAttachInfo == null) { 15290 return null; 15291 } 15292 if (mAttachInfo.mWindowId == null) { 15293 try { 15294 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15295 mAttachInfo.mWindowToken); 15296 mAttachInfo.mWindowId = new WindowId( 15297 mAttachInfo.mIWindowId); 15298 } catch (RemoteException e) { 15299 } 15300 } 15301 return mAttachInfo.mWindowId; 15302 } 15303 15304 /** 15305 * Retrieve a unique token identifying the top-level "real" window of 15306 * the window that this view is attached to. That is, this is like 15307 * {@link #getWindowToken}, except if the window this view in is a panel 15308 * window (attached to another containing window), then the token of 15309 * the containing window is returned instead. 15310 * 15311 * @return Returns the associated window token, either 15312 * {@link #getWindowToken()} or the containing window's token. 15313 */ 15314 public IBinder getApplicationWindowToken() { 15315 AttachInfo ai = mAttachInfo; 15316 if (ai != null) { 15317 IBinder appWindowToken = ai.mPanelParentWindowToken; 15318 if (appWindowToken == null) { 15319 appWindowToken = ai.mWindowToken; 15320 } 15321 return appWindowToken; 15322 } 15323 return null; 15324 } 15325 15326 /** 15327 * Gets the logical display to which the view's window has been attached. 15328 * 15329 * @return The logical display, or null if the view is not currently attached to a window. 15330 */ 15331 public Display getDisplay() { 15332 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15333 } 15334 15335 /** 15336 * Retrieve private session object this view hierarchy is using to 15337 * communicate with the window manager. 15338 * @return the session object to communicate with the window manager 15339 */ 15340 /*package*/ IWindowSession getWindowSession() { 15341 return mAttachInfo != null ? mAttachInfo.mSession : null; 15342 } 15343 15344 /** 15345 * Return the visibility value of the least visible component passed. 15346 */ 15347 int combineVisibility(int vis1, int vis2) { 15348 // This works because VISIBLE < INVISIBLE < GONE. 15349 return Math.max(vis1, vis2); 15350 } 15351 15352 /** 15353 * @param info the {@link android.view.View.AttachInfo} to associated with 15354 * this view 15355 */ 15356 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15357 mAttachInfo = info; 15358 if (mOverlay != null) { 15359 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15360 } 15361 mWindowAttachCount++; 15362 // We will need to evaluate the drawable state at least once. 15363 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15364 if (mFloatingTreeObserver != null) { 15365 info.mTreeObserver.merge(mFloatingTreeObserver); 15366 mFloatingTreeObserver = null; 15367 } 15368 15369 registerPendingFrameMetricsObservers(); 15370 15371 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15372 mAttachInfo.mScrollContainers.add(this); 15373 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15374 } 15375 // Transfer all pending runnables. 15376 if (mRunQueue != null) { 15377 mRunQueue.executeActions(info.mHandler); 15378 mRunQueue = null; 15379 } 15380 performCollectViewAttributes(mAttachInfo, visibility); 15381 onAttachedToWindow(); 15382 15383 ListenerInfo li = mListenerInfo; 15384 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15385 li != null ? li.mOnAttachStateChangeListeners : null; 15386 if (listeners != null && listeners.size() > 0) { 15387 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15388 // perform the dispatching. The iterator is a safe guard against listeners that 15389 // could mutate the list by calling the various add/remove methods. This prevents 15390 // the array from being modified while we iterate it. 15391 for (OnAttachStateChangeListener listener : listeners) { 15392 listener.onViewAttachedToWindow(this); 15393 } 15394 } 15395 15396 int vis = info.mWindowVisibility; 15397 if (vis != GONE) { 15398 onWindowVisibilityChanged(vis); 15399 if (isShown()) { 15400 // Calling onVisibilityChanged directly here since the subtree will also 15401 // receive dispatchAttachedToWindow and this same call 15402 onVisibilityAggregated(vis == VISIBLE); 15403 } 15404 } 15405 15406 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15407 // As all views in the subtree will already receive dispatchAttachedToWindow 15408 // traversing the subtree again here is not desired. 15409 onVisibilityChanged(this, visibility); 15410 15411 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15412 // If nobody has evaluated the drawable state yet, then do it now. 15413 refreshDrawableState(); 15414 } 15415 needGlobalAttributesUpdate(false); 15416 } 15417 15418 void dispatchDetachedFromWindow() { 15419 AttachInfo info = mAttachInfo; 15420 if (info != null) { 15421 int vis = info.mWindowVisibility; 15422 if (vis != GONE) { 15423 onWindowVisibilityChanged(GONE); 15424 if (isShown()) { 15425 // Invoking onVisibilityAggregated directly here since the subtree 15426 // will also receive detached from window 15427 onVisibilityAggregated(false); 15428 } 15429 } 15430 } 15431 15432 onDetachedFromWindow(); 15433 onDetachedFromWindowInternal(); 15434 15435 InputMethodManager imm = InputMethodManager.peekInstance(); 15436 if (imm != null) { 15437 imm.onViewDetachedFromWindow(this); 15438 } 15439 15440 ListenerInfo li = mListenerInfo; 15441 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15442 li != null ? li.mOnAttachStateChangeListeners : null; 15443 if (listeners != null && listeners.size() > 0) { 15444 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15445 // perform the dispatching. The iterator is a safe guard against listeners that 15446 // could mutate the list by calling the various add/remove methods. This prevents 15447 // the array from being modified while we iterate it. 15448 for (OnAttachStateChangeListener listener : listeners) { 15449 listener.onViewDetachedFromWindow(this); 15450 } 15451 } 15452 15453 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15454 mAttachInfo.mScrollContainers.remove(this); 15455 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15456 } 15457 15458 mAttachInfo = null; 15459 if (mOverlay != null) { 15460 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15461 } 15462 } 15463 15464 /** 15465 * Cancel any deferred high-level input events that were previously posted to the event queue. 15466 * 15467 * <p>Many views post high-level events such as click handlers to the event queue 15468 * to run deferred in order to preserve a desired user experience - clearing visible 15469 * pressed states before executing, etc. This method will abort any events of this nature 15470 * that are currently in flight.</p> 15471 * 15472 * <p>Custom views that generate their own high-level deferred input events should override 15473 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15474 * 15475 * <p>This will also cancel pending input events for any child views.</p> 15476 * 15477 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15478 * This will not impact newer events posted after this call that may occur as a result of 15479 * lower-level input events still waiting in the queue. If you are trying to prevent 15480 * double-submitted events for the duration of some sort of asynchronous transaction 15481 * you should also take other steps to protect against unexpected double inputs e.g. calling 15482 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15483 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15484 */ 15485 public final void cancelPendingInputEvents() { 15486 dispatchCancelPendingInputEvents(); 15487 } 15488 15489 /** 15490 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15491 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15492 */ 15493 void dispatchCancelPendingInputEvents() { 15494 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15495 onCancelPendingInputEvents(); 15496 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15497 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15498 " did not call through to super.onCancelPendingInputEvents()"); 15499 } 15500 } 15501 15502 /** 15503 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15504 * a parent view. 15505 * 15506 * <p>This method is responsible for removing any pending high-level input events that were 15507 * posted to the event queue to run later. Custom view classes that post their own deferred 15508 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15509 * {@link android.os.Handler} should override this method, call 15510 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15511 * </p> 15512 */ 15513 public void onCancelPendingInputEvents() { 15514 removePerformClickCallback(); 15515 cancelLongPress(); 15516 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15517 } 15518 15519 /** 15520 * Store this view hierarchy's frozen state into the given container. 15521 * 15522 * @param container The SparseArray in which to save the view's state. 15523 * 15524 * @see #restoreHierarchyState(android.util.SparseArray) 15525 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15526 * @see #onSaveInstanceState() 15527 */ 15528 public void saveHierarchyState(SparseArray<Parcelable> container) { 15529 dispatchSaveInstanceState(container); 15530 } 15531 15532 /** 15533 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15534 * this view and its children. May be overridden to modify how freezing happens to a 15535 * view's children; for example, some views may want to not store state for their children. 15536 * 15537 * @param container The SparseArray in which to save the view's state. 15538 * 15539 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15540 * @see #saveHierarchyState(android.util.SparseArray) 15541 * @see #onSaveInstanceState() 15542 */ 15543 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15544 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15545 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15546 Parcelable state = onSaveInstanceState(); 15547 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15548 throw new IllegalStateException( 15549 "Derived class did not call super.onSaveInstanceState()"); 15550 } 15551 if (state != null) { 15552 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15553 // + ": " + state); 15554 container.put(mID, state); 15555 } 15556 } 15557 } 15558 15559 /** 15560 * Hook allowing a view to generate a representation of its internal state 15561 * that can later be used to create a new instance with that same state. 15562 * This state should only contain information that is not persistent or can 15563 * not be reconstructed later. For example, you will never store your 15564 * current position on screen because that will be computed again when a 15565 * new instance of the view is placed in its view hierarchy. 15566 * <p> 15567 * Some examples of things you may store here: the current cursor position 15568 * in a text view (but usually not the text itself since that is stored in a 15569 * content provider or other persistent storage), the currently selected 15570 * item in a list view. 15571 * 15572 * @return Returns a Parcelable object containing the view's current dynamic 15573 * state, or null if there is nothing interesting to save. The 15574 * default implementation returns null. 15575 * @see #onRestoreInstanceState(android.os.Parcelable) 15576 * @see #saveHierarchyState(android.util.SparseArray) 15577 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15578 * @see #setSaveEnabled(boolean) 15579 */ 15580 @CallSuper 15581 protected Parcelable onSaveInstanceState() { 15582 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15583 if (mStartActivityRequestWho != null) { 15584 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15585 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15586 return state; 15587 } 15588 return BaseSavedState.EMPTY_STATE; 15589 } 15590 15591 /** 15592 * Restore this view hierarchy's frozen state from the given container. 15593 * 15594 * @param container The SparseArray which holds previously frozen states. 15595 * 15596 * @see #saveHierarchyState(android.util.SparseArray) 15597 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15598 * @see #onRestoreInstanceState(android.os.Parcelable) 15599 */ 15600 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15601 dispatchRestoreInstanceState(container); 15602 } 15603 15604 /** 15605 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15606 * state for this view and its children. May be overridden to modify how restoring 15607 * happens to a view's children; for example, some views may want to not store state 15608 * for their children. 15609 * 15610 * @param container The SparseArray which holds previously saved state. 15611 * 15612 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15613 * @see #restoreHierarchyState(android.util.SparseArray) 15614 * @see #onRestoreInstanceState(android.os.Parcelable) 15615 */ 15616 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15617 if (mID != NO_ID) { 15618 Parcelable state = container.get(mID); 15619 if (state != null) { 15620 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15621 // + ": " + state); 15622 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15623 onRestoreInstanceState(state); 15624 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15625 throw new IllegalStateException( 15626 "Derived class did not call super.onRestoreInstanceState()"); 15627 } 15628 } 15629 } 15630 } 15631 15632 /** 15633 * Hook allowing a view to re-apply a representation of its internal state that had previously 15634 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15635 * null state. 15636 * 15637 * @param state The frozen state that had previously been returned by 15638 * {@link #onSaveInstanceState}. 15639 * 15640 * @see #onSaveInstanceState() 15641 * @see #restoreHierarchyState(android.util.SparseArray) 15642 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15643 */ 15644 @CallSuper 15645 protected void onRestoreInstanceState(Parcelable state) { 15646 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15647 if (state != null && !(state instanceof AbsSavedState)) { 15648 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15649 + "received " + state.getClass().toString() + " instead. This usually happens " 15650 + "when two views of different type have the same id in the same hierarchy. " 15651 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15652 + "other views do not use the same id."); 15653 } 15654 if (state != null && state instanceof BaseSavedState) { 15655 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15656 } 15657 } 15658 15659 /** 15660 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15661 * 15662 * @return the drawing start time in milliseconds 15663 */ 15664 public long getDrawingTime() { 15665 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15666 } 15667 15668 /** 15669 * <p>Enables or disables the duplication of the parent's state into this view. When 15670 * duplication is enabled, this view gets its drawable state from its parent rather 15671 * than from its own internal properties.</p> 15672 * 15673 * <p>Note: in the current implementation, setting this property to true after the 15674 * view was added to a ViewGroup might have no effect at all. This property should 15675 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15676 * 15677 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15678 * property is enabled, an exception will be thrown.</p> 15679 * 15680 * <p>Note: if the child view uses and updates additional states which are unknown to the 15681 * parent, these states should not be affected by this method.</p> 15682 * 15683 * @param enabled True to enable duplication of the parent's drawable state, false 15684 * to disable it. 15685 * 15686 * @see #getDrawableState() 15687 * @see #isDuplicateParentStateEnabled() 15688 */ 15689 public void setDuplicateParentStateEnabled(boolean enabled) { 15690 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15691 } 15692 15693 /** 15694 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15695 * 15696 * @return True if this view's drawable state is duplicated from the parent, 15697 * false otherwise 15698 * 15699 * @see #getDrawableState() 15700 * @see #setDuplicateParentStateEnabled(boolean) 15701 */ 15702 public boolean isDuplicateParentStateEnabled() { 15703 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15704 } 15705 15706 /** 15707 * <p>Specifies the type of layer backing this view. The layer can be 15708 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15709 * {@link #LAYER_TYPE_HARDWARE}.</p> 15710 * 15711 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15712 * instance that controls how the layer is composed on screen. The following 15713 * properties of the paint are taken into account when composing the layer:</p> 15714 * <ul> 15715 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15716 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15717 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15718 * </ul> 15719 * 15720 * <p>If this view has an alpha value set to < 1.0 by calling 15721 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15722 * by this view's alpha value.</p> 15723 * 15724 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15725 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15726 * for more information on when and how to use layers.</p> 15727 * 15728 * @param layerType The type of layer to use with this view, must be one of 15729 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15730 * {@link #LAYER_TYPE_HARDWARE} 15731 * @param paint The paint used to compose the layer. This argument is optional 15732 * and can be null. It is ignored when the layer type is 15733 * {@link #LAYER_TYPE_NONE} 15734 * 15735 * @see #getLayerType() 15736 * @see #LAYER_TYPE_NONE 15737 * @see #LAYER_TYPE_SOFTWARE 15738 * @see #LAYER_TYPE_HARDWARE 15739 * @see #setAlpha(float) 15740 * 15741 * @attr ref android.R.styleable#View_layerType 15742 */ 15743 public void setLayerType(int layerType, @Nullable Paint paint) { 15744 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15745 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15746 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15747 } 15748 15749 boolean typeChanged = mRenderNode.setLayerType(layerType); 15750 15751 if (!typeChanged) { 15752 setLayerPaint(paint); 15753 return; 15754 } 15755 15756 if (layerType != LAYER_TYPE_SOFTWARE) { 15757 // Destroy any previous software drawing cache if present 15758 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 15759 // drawing cache created in View#draw when drawing to a SW canvas. 15760 destroyDrawingCache(); 15761 } 15762 15763 mLayerType = layerType; 15764 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15765 mRenderNode.setLayerPaint(mLayerPaint); 15766 15767 // draw() behaves differently if we are on a layer, so we need to 15768 // invalidate() here 15769 invalidateParentCaches(); 15770 invalidate(true); 15771 } 15772 15773 /** 15774 * Updates the {@link Paint} object used with the current layer (used only if the current 15775 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15776 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15777 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15778 * ensure that the view gets redrawn immediately. 15779 * 15780 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15781 * instance that controls how the layer is composed on screen. The following 15782 * properties of the paint are taken into account when composing the layer:</p> 15783 * <ul> 15784 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15785 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15786 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15787 * </ul> 15788 * 15789 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15790 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15791 * 15792 * @param paint The paint used to compose the layer. This argument is optional 15793 * and can be null. It is ignored when the layer type is 15794 * {@link #LAYER_TYPE_NONE} 15795 * 15796 * @see #setLayerType(int, android.graphics.Paint) 15797 */ 15798 public void setLayerPaint(@Nullable Paint paint) { 15799 int layerType = getLayerType(); 15800 if (layerType != LAYER_TYPE_NONE) { 15801 mLayerPaint = paint; 15802 if (layerType == LAYER_TYPE_HARDWARE) { 15803 if (mRenderNode.setLayerPaint(paint)) { 15804 invalidateViewProperty(false, false); 15805 } 15806 } else { 15807 invalidate(); 15808 } 15809 } 15810 } 15811 15812 /** 15813 * Indicates what type of layer is currently associated with this view. By default 15814 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15815 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15816 * for more information on the different types of layers. 15817 * 15818 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15819 * {@link #LAYER_TYPE_HARDWARE} 15820 * 15821 * @see #setLayerType(int, android.graphics.Paint) 15822 * @see #buildLayer() 15823 * @see #LAYER_TYPE_NONE 15824 * @see #LAYER_TYPE_SOFTWARE 15825 * @see #LAYER_TYPE_HARDWARE 15826 */ 15827 public int getLayerType() { 15828 return mLayerType; 15829 } 15830 15831 /** 15832 * Forces this view's layer to be created and this view to be rendered 15833 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15834 * invoking this method will have no effect. 15835 * 15836 * This method can for instance be used to render a view into its layer before 15837 * starting an animation. If this view is complex, rendering into the layer 15838 * before starting the animation will avoid skipping frames. 15839 * 15840 * @throws IllegalStateException If this view is not attached to a window 15841 * 15842 * @see #setLayerType(int, android.graphics.Paint) 15843 */ 15844 public void buildLayer() { 15845 if (mLayerType == LAYER_TYPE_NONE) return; 15846 15847 final AttachInfo attachInfo = mAttachInfo; 15848 if (attachInfo == null) { 15849 throw new IllegalStateException("This view must be attached to a window first"); 15850 } 15851 15852 if (getWidth() == 0 || getHeight() == 0) { 15853 return; 15854 } 15855 15856 switch (mLayerType) { 15857 case LAYER_TYPE_HARDWARE: 15858 updateDisplayListIfDirty(); 15859 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 15860 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 15861 } 15862 break; 15863 case LAYER_TYPE_SOFTWARE: 15864 buildDrawingCache(true); 15865 break; 15866 } 15867 } 15868 15869 /** 15870 * Destroys all hardware rendering resources. This method is invoked 15871 * when the system needs to reclaim resources. Upon execution of this 15872 * method, you should free any OpenGL resources created by the view. 15873 * 15874 * Note: you <strong>must</strong> call 15875 * <code>super.destroyHardwareResources()</code> when overriding 15876 * this method. 15877 * 15878 * @hide 15879 */ 15880 @CallSuper 15881 protected void destroyHardwareResources() { 15882 // Although the Layer will be destroyed by RenderNode, we want to release 15883 // the staging display list, which is also a signal to RenderNode that it's 15884 // safe to free its copy of the display list as it knows that we will 15885 // push an updated DisplayList if we try to draw again 15886 resetDisplayList(); 15887 } 15888 15889 /** 15890 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15891 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15892 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15893 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15894 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15895 * null.</p> 15896 * 15897 * <p>Enabling the drawing cache is similar to 15898 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15899 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15900 * drawing cache has no effect on rendering because the system uses a different mechanism 15901 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15902 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15903 * for information on how to enable software and hardware layers.</p> 15904 * 15905 * <p>This API can be used to manually generate 15906 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15907 * {@link #getDrawingCache()}.</p> 15908 * 15909 * @param enabled true to enable the drawing cache, false otherwise 15910 * 15911 * @see #isDrawingCacheEnabled() 15912 * @see #getDrawingCache() 15913 * @see #buildDrawingCache() 15914 * @see #setLayerType(int, android.graphics.Paint) 15915 */ 15916 public void setDrawingCacheEnabled(boolean enabled) { 15917 mCachingFailed = false; 15918 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15919 } 15920 15921 /** 15922 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15923 * 15924 * @return true if the drawing cache is enabled 15925 * 15926 * @see #setDrawingCacheEnabled(boolean) 15927 * @see #getDrawingCache() 15928 */ 15929 @ViewDebug.ExportedProperty(category = "drawing") 15930 public boolean isDrawingCacheEnabled() { 15931 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15932 } 15933 15934 /** 15935 * Debugging utility which recursively outputs the dirty state of a view and its 15936 * descendants. 15937 * 15938 * @hide 15939 */ 15940 @SuppressWarnings({"UnusedDeclaration"}) 15941 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15942 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15943 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15944 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15945 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15946 if (clear) { 15947 mPrivateFlags &= clearMask; 15948 } 15949 if (this instanceof ViewGroup) { 15950 ViewGroup parent = (ViewGroup) this; 15951 final int count = parent.getChildCount(); 15952 for (int i = 0; i < count; i++) { 15953 final View child = parent.getChildAt(i); 15954 child.outputDirtyFlags(indent + " ", clear, clearMask); 15955 } 15956 } 15957 } 15958 15959 /** 15960 * This method is used by ViewGroup to cause its children to restore or recreate their 15961 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15962 * to recreate its own display list, which would happen if it went through the normal 15963 * draw/dispatchDraw mechanisms. 15964 * 15965 * @hide 15966 */ 15967 protected void dispatchGetDisplayList() {} 15968 15969 /** 15970 * A view that is not attached or hardware accelerated cannot create a display list. 15971 * This method checks these conditions and returns the appropriate result. 15972 * 15973 * @return true if view has the ability to create a display list, false otherwise. 15974 * 15975 * @hide 15976 */ 15977 public boolean canHaveDisplayList() { 15978 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15979 } 15980 15981 /** 15982 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15983 * @hide 15984 */ 15985 @NonNull 15986 public RenderNode updateDisplayListIfDirty() { 15987 final RenderNode renderNode = mRenderNode; 15988 if (!canHaveDisplayList()) { 15989 // can't populate RenderNode, don't try 15990 return renderNode; 15991 } 15992 15993 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15994 || !renderNode.isValid() 15995 || (mRecreateDisplayList)) { 15996 // Don't need to recreate the display list, just need to tell our 15997 // children to restore/recreate theirs 15998 if (renderNode.isValid() 15999 && !mRecreateDisplayList) { 16000 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16001 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16002 dispatchGetDisplayList(); 16003 16004 return renderNode; // no work needed 16005 } 16006 16007 // If we got here, we're recreating it. Mark it as such to ensure that 16008 // we copy in child display lists into ours in drawChild() 16009 mRecreateDisplayList = true; 16010 16011 int width = mRight - mLeft; 16012 int height = mBottom - mTop; 16013 int layerType = getLayerType(); 16014 16015 final DisplayListCanvas canvas = renderNode.start(width, height); 16016 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16017 16018 try { 16019 if (layerType == LAYER_TYPE_SOFTWARE) { 16020 buildDrawingCache(true); 16021 Bitmap cache = getDrawingCache(true); 16022 if (cache != null) { 16023 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16024 } 16025 } else { 16026 computeScroll(); 16027 16028 canvas.translate(-mScrollX, -mScrollY); 16029 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16030 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16031 16032 // Fast path for layouts with no backgrounds 16033 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16034 dispatchDraw(canvas); 16035 if (mOverlay != null && !mOverlay.isEmpty()) { 16036 mOverlay.getOverlayView().draw(canvas); 16037 } 16038 } else { 16039 draw(canvas); 16040 } 16041 } 16042 } finally { 16043 renderNode.end(canvas); 16044 setDisplayListProperties(renderNode); 16045 } 16046 } else { 16047 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16048 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16049 } 16050 return renderNode; 16051 } 16052 16053 private void resetDisplayList() { 16054 if (mRenderNode.isValid()) { 16055 mRenderNode.discardDisplayList(); 16056 } 16057 16058 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16059 mBackgroundRenderNode.discardDisplayList(); 16060 } 16061 } 16062 16063 /** 16064 * Called when the passed RenderNode is removed from the draw tree 16065 * @hide 16066 */ 16067 public void onRenderNodeDetached(RenderNode renderNode) { 16068 if (renderNode == mRenderNode && mRenderNodeDetachedCallback != null) { 16069 mRenderNodeDetachedCallback.run(); 16070 } 16071 } 16072 16073 /** 16074 * Set callback for functor detach. Exposed to WebView through WebViewDelegate. 16075 * Should not be used otherwise. 16076 * @hide 16077 */ 16078 public final Runnable setRenderNodeDetachedCallback(@Nullable Runnable callback) { 16079 Runnable oldCallback = mRenderNodeDetachedCallback; 16080 mRenderNodeDetachedCallback = callback; 16081 return oldCallback; 16082 } 16083 16084 /** 16085 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16086 * 16087 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16088 * 16089 * @see #getDrawingCache(boolean) 16090 */ 16091 public Bitmap getDrawingCache() { 16092 return getDrawingCache(false); 16093 } 16094 16095 /** 16096 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16097 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16098 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16099 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16100 * request the drawing cache by calling this method and draw it on screen if the 16101 * returned bitmap is not null.</p> 16102 * 16103 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16104 * this method will create a bitmap of the same size as this view. Because this bitmap 16105 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16106 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16107 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16108 * size than the view. This implies that your application must be able to handle this 16109 * size.</p> 16110 * 16111 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16112 * the current density of the screen when the application is in compatibility 16113 * mode. 16114 * 16115 * @return A bitmap representing this view or null if cache is disabled. 16116 * 16117 * @see #setDrawingCacheEnabled(boolean) 16118 * @see #isDrawingCacheEnabled() 16119 * @see #buildDrawingCache(boolean) 16120 * @see #destroyDrawingCache() 16121 */ 16122 public Bitmap getDrawingCache(boolean autoScale) { 16123 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16124 return null; 16125 } 16126 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16127 buildDrawingCache(autoScale); 16128 } 16129 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16130 } 16131 16132 /** 16133 * <p>Frees the resources used by the drawing cache. If you call 16134 * {@link #buildDrawingCache()} manually without calling 16135 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16136 * should cleanup the cache with this method afterwards.</p> 16137 * 16138 * @see #setDrawingCacheEnabled(boolean) 16139 * @see #buildDrawingCache() 16140 * @see #getDrawingCache() 16141 */ 16142 public void destroyDrawingCache() { 16143 if (mDrawingCache != null) { 16144 mDrawingCache.recycle(); 16145 mDrawingCache = null; 16146 } 16147 if (mUnscaledDrawingCache != null) { 16148 mUnscaledDrawingCache.recycle(); 16149 mUnscaledDrawingCache = null; 16150 } 16151 } 16152 16153 /** 16154 * Setting a solid background color for the drawing cache's bitmaps will improve 16155 * performance and memory usage. Note, though that this should only be used if this 16156 * view will always be drawn on top of a solid color. 16157 * 16158 * @param color The background color to use for the drawing cache's bitmap 16159 * 16160 * @see #setDrawingCacheEnabled(boolean) 16161 * @see #buildDrawingCache() 16162 * @see #getDrawingCache() 16163 */ 16164 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16165 if (color != mDrawingCacheBackgroundColor) { 16166 mDrawingCacheBackgroundColor = color; 16167 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16168 } 16169 } 16170 16171 /** 16172 * @see #setDrawingCacheBackgroundColor(int) 16173 * 16174 * @return The background color to used for the drawing cache's bitmap 16175 */ 16176 @ColorInt 16177 public int getDrawingCacheBackgroundColor() { 16178 return mDrawingCacheBackgroundColor; 16179 } 16180 16181 /** 16182 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16183 * 16184 * @see #buildDrawingCache(boolean) 16185 */ 16186 public void buildDrawingCache() { 16187 buildDrawingCache(false); 16188 } 16189 16190 /** 16191 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16192 * 16193 * <p>If you call {@link #buildDrawingCache()} manually without calling 16194 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16195 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16196 * 16197 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16198 * this method will create a bitmap of the same size as this view. Because this bitmap 16199 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16200 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16201 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16202 * size than the view. This implies that your application must be able to handle this 16203 * size.</p> 16204 * 16205 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16206 * you do not need the drawing cache bitmap, calling this method will increase memory 16207 * usage and cause the view to be rendered in software once, thus negatively impacting 16208 * performance.</p> 16209 * 16210 * @see #getDrawingCache() 16211 * @see #destroyDrawingCache() 16212 */ 16213 public void buildDrawingCache(boolean autoScale) { 16214 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16215 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16216 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16217 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16218 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16219 } 16220 try { 16221 buildDrawingCacheImpl(autoScale); 16222 } finally { 16223 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16224 } 16225 } 16226 } 16227 16228 /** 16229 * private, internal implementation of buildDrawingCache, used to enable tracing 16230 */ 16231 private void buildDrawingCacheImpl(boolean autoScale) { 16232 mCachingFailed = false; 16233 16234 int width = mRight - mLeft; 16235 int height = mBottom - mTop; 16236 16237 final AttachInfo attachInfo = mAttachInfo; 16238 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16239 16240 if (autoScale && scalingRequired) { 16241 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16242 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16243 } 16244 16245 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16246 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16247 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16248 16249 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16250 final long drawingCacheSize = 16251 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16252 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16253 if (width > 0 && height > 0) { 16254 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16255 + " too large to fit into a software layer (or drawing cache), needs " 16256 + projectedBitmapSize + " bytes, only " 16257 + drawingCacheSize + " available"); 16258 } 16259 destroyDrawingCache(); 16260 mCachingFailed = true; 16261 return; 16262 } 16263 16264 boolean clear = true; 16265 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16266 16267 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16268 Bitmap.Config quality; 16269 if (!opaque) { 16270 // Never pick ARGB_4444 because it looks awful 16271 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16272 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16273 case DRAWING_CACHE_QUALITY_AUTO: 16274 case DRAWING_CACHE_QUALITY_LOW: 16275 case DRAWING_CACHE_QUALITY_HIGH: 16276 default: 16277 quality = Bitmap.Config.ARGB_8888; 16278 break; 16279 } 16280 } else { 16281 // Optimization for translucent windows 16282 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16283 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16284 } 16285 16286 // Try to cleanup memory 16287 if (bitmap != null) bitmap.recycle(); 16288 16289 try { 16290 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16291 width, height, quality); 16292 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16293 if (autoScale) { 16294 mDrawingCache = bitmap; 16295 } else { 16296 mUnscaledDrawingCache = bitmap; 16297 } 16298 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16299 } catch (OutOfMemoryError e) { 16300 // If there is not enough memory to create the bitmap cache, just 16301 // ignore the issue as bitmap caches are not required to draw the 16302 // view hierarchy 16303 if (autoScale) { 16304 mDrawingCache = null; 16305 } else { 16306 mUnscaledDrawingCache = null; 16307 } 16308 mCachingFailed = true; 16309 return; 16310 } 16311 16312 clear = drawingCacheBackgroundColor != 0; 16313 } 16314 16315 Canvas canvas; 16316 if (attachInfo != null) { 16317 canvas = attachInfo.mCanvas; 16318 if (canvas == null) { 16319 canvas = new Canvas(); 16320 } 16321 canvas.setBitmap(bitmap); 16322 // Temporarily clobber the cached Canvas in case one of our children 16323 // is also using a drawing cache. Without this, the children would 16324 // steal the canvas by attaching their own bitmap to it and bad, bad 16325 // thing would happen (invisible views, corrupted drawings, etc.) 16326 attachInfo.mCanvas = null; 16327 } else { 16328 // This case should hopefully never or seldom happen 16329 canvas = new Canvas(bitmap); 16330 } 16331 16332 if (clear) { 16333 bitmap.eraseColor(drawingCacheBackgroundColor); 16334 } 16335 16336 computeScroll(); 16337 final int restoreCount = canvas.save(); 16338 16339 if (autoScale && scalingRequired) { 16340 final float scale = attachInfo.mApplicationScale; 16341 canvas.scale(scale, scale); 16342 } 16343 16344 canvas.translate(-mScrollX, -mScrollY); 16345 16346 mPrivateFlags |= PFLAG_DRAWN; 16347 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16348 mLayerType != LAYER_TYPE_NONE) { 16349 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16350 } 16351 16352 // Fast path for layouts with no backgrounds 16353 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16354 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16355 dispatchDraw(canvas); 16356 if (mOverlay != null && !mOverlay.isEmpty()) { 16357 mOverlay.getOverlayView().draw(canvas); 16358 } 16359 } else { 16360 draw(canvas); 16361 } 16362 16363 canvas.restoreToCount(restoreCount); 16364 canvas.setBitmap(null); 16365 16366 if (attachInfo != null) { 16367 // Restore the cached Canvas for our siblings 16368 attachInfo.mCanvas = canvas; 16369 } 16370 } 16371 16372 /** 16373 * Create a snapshot of the view into a bitmap. We should probably make 16374 * some form of this public, but should think about the API. 16375 * 16376 * @hide 16377 */ 16378 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16379 int width = mRight - mLeft; 16380 int height = mBottom - mTop; 16381 16382 final AttachInfo attachInfo = mAttachInfo; 16383 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16384 width = (int) ((width * scale) + 0.5f); 16385 height = (int) ((height * scale) + 0.5f); 16386 16387 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16388 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16389 if (bitmap == null) { 16390 throw new OutOfMemoryError(); 16391 } 16392 16393 Resources resources = getResources(); 16394 if (resources != null) { 16395 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16396 } 16397 16398 Canvas canvas; 16399 if (attachInfo != null) { 16400 canvas = attachInfo.mCanvas; 16401 if (canvas == null) { 16402 canvas = new Canvas(); 16403 } 16404 canvas.setBitmap(bitmap); 16405 // Temporarily clobber the cached Canvas in case one of our children 16406 // is also using a drawing cache. Without this, the children would 16407 // steal the canvas by attaching their own bitmap to it and bad, bad 16408 // things would happen (invisible views, corrupted drawings, etc.) 16409 attachInfo.mCanvas = null; 16410 } else { 16411 // This case should hopefully never or seldom happen 16412 canvas = new Canvas(bitmap); 16413 } 16414 16415 if ((backgroundColor & 0xff000000) != 0) { 16416 bitmap.eraseColor(backgroundColor); 16417 } 16418 16419 computeScroll(); 16420 final int restoreCount = canvas.save(); 16421 canvas.scale(scale, scale); 16422 canvas.translate(-mScrollX, -mScrollY); 16423 16424 // Temporarily remove the dirty mask 16425 int flags = mPrivateFlags; 16426 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16427 16428 // Fast path for layouts with no backgrounds 16429 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16430 dispatchDraw(canvas); 16431 if (mOverlay != null && !mOverlay.isEmpty()) { 16432 mOverlay.getOverlayView().draw(canvas); 16433 } 16434 } else { 16435 draw(canvas); 16436 } 16437 16438 mPrivateFlags = flags; 16439 16440 canvas.restoreToCount(restoreCount); 16441 canvas.setBitmap(null); 16442 16443 if (attachInfo != null) { 16444 // Restore the cached Canvas for our siblings 16445 attachInfo.mCanvas = canvas; 16446 } 16447 16448 return bitmap; 16449 } 16450 16451 /** 16452 * Indicates whether this View is currently in edit mode. A View is usually 16453 * in edit mode when displayed within a developer tool. For instance, if 16454 * this View is being drawn by a visual user interface builder, this method 16455 * should return true. 16456 * 16457 * Subclasses should check the return value of this method to provide 16458 * different behaviors if their normal behavior might interfere with the 16459 * host environment. For instance: the class spawns a thread in its 16460 * constructor, the drawing code relies on device-specific features, etc. 16461 * 16462 * This method is usually checked in the drawing code of custom widgets. 16463 * 16464 * @return True if this View is in edit mode, false otherwise. 16465 */ 16466 public boolean isInEditMode() { 16467 return false; 16468 } 16469 16470 /** 16471 * If the View draws content inside its padding and enables fading edges, 16472 * it needs to support padding offsets. Padding offsets are added to the 16473 * fading edges to extend the length of the fade so that it covers pixels 16474 * drawn inside the padding. 16475 * 16476 * Subclasses of this class should override this method if they need 16477 * to draw content inside the padding. 16478 * 16479 * @return True if padding offset must be applied, false otherwise. 16480 * 16481 * @see #getLeftPaddingOffset() 16482 * @see #getRightPaddingOffset() 16483 * @see #getTopPaddingOffset() 16484 * @see #getBottomPaddingOffset() 16485 * 16486 * @since CURRENT 16487 */ 16488 protected boolean isPaddingOffsetRequired() { 16489 return false; 16490 } 16491 16492 /** 16493 * Amount by which to extend the left fading region. Called only when 16494 * {@link #isPaddingOffsetRequired()} returns true. 16495 * 16496 * @return The left padding offset in pixels. 16497 * 16498 * @see #isPaddingOffsetRequired() 16499 * 16500 * @since CURRENT 16501 */ 16502 protected int getLeftPaddingOffset() { 16503 return 0; 16504 } 16505 16506 /** 16507 * Amount by which to extend the right fading region. Called only when 16508 * {@link #isPaddingOffsetRequired()} returns true. 16509 * 16510 * @return The right padding offset in pixels. 16511 * 16512 * @see #isPaddingOffsetRequired() 16513 * 16514 * @since CURRENT 16515 */ 16516 protected int getRightPaddingOffset() { 16517 return 0; 16518 } 16519 16520 /** 16521 * Amount by which to extend the top fading region. Called only when 16522 * {@link #isPaddingOffsetRequired()} returns true. 16523 * 16524 * @return The top padding offset in pixels. 16525 * 16526 * @see #isPaddingOffsetRequired() 16527 * 16528 * @since CURRENT 16529 */ 16530 protected int getTopPaddingOffset() { 16531 return 0; 16532 } 16533 16534 /** 16535 * Amount by which to extend the bottom fading region. Called only when 16536 * {@link #isPaddingOffsetRequired()} returns true. 16537 * 16538 * @return The bottom padding offset in pixels. 16539 * 16540 * @see #isPaddingOffsetRequired() 16541 * 16542 * @since CURRENT 16543 */ 16544 protected int getBottomPaddingOffset() { 16545 return 0; 16546 } 16547 16548 /** 16549 * @hide 16550 * @param offsetRequired 16551 */ 16552 protected int getFadeTop(boolean offsetRequired) { 16553 int top = mPaddingTop; 16554 if (offsetRequired) top += getTopPaddingOffset(); 16555 return top; 16556 } 16557 16558 /** 16559 * @hide 16560 * @param offsetRequired 16561 */ 16562 protected int getFadeHeight(boolean offsetRequired) { 16563 int padding = mPaddingTop; 16564 if (offsetRequired) padding += getTopPaddingOffset(); 16565 return mBottom - mTop - mPaddingBottom - padding; 16566 } 16567 16568 /** 16569 * <p>Indicates whether this view is attached to a hardware accelerated 16570 * window or not.</p> 16571 * 16572 * <p>Even if this method returns true, it does not mean that every call 16573 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16574 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16575 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16576 * window is hardware accelerated, 16577 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16578 * return false, and this method will return true.</p> 16579 * 16580 * @return True if the view is attached to a window and the window is 16581 * hardware accelerated; false in any other case. 16582 */ 16583 @ViewDebug.ExportedProperty(category = "drawing") 16584 public boolean isHardwareAccelerated() { 16585 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16586 } 16587 16588 /** 16589 * Sets a rectangular area on this view to which the view will be clipped 16590 * when it is drawn. Setting the value to null will remove the clip bounds 16591 * and the view will draw normally, using its full bounds. 16592 * 16593 * @param clipBounds The rectangular area, in the local coordinates of 16594 * this view, to which future drawing operations will be clipped. 16595 */ 16596 public void setClipBounds(Rect clipBounds) { 16597 if (clipBounds == mClipBounds 16598 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16599 return; 16600 } 16601 if (clipBounds != null) { 16602 if (mClipBounds == null) { 16603 mClipBounds = new Rect(clipBounds); 16604 } else { 16605 mClipBounds.set(clipBounds); 16606 } 16607 } else { 16608 mClipBounds = null; 16609 } 16610 mRenderNode.setClipBounds(mClipBounds); 16611 invalidateViewProperty(false, false); 16612 } 16613 16614 /** 16615 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16616 * 16617 * @return A copy of the current clip bounds if clip bounds are set, 16618 * otherwise null. 16619 */ 16620 public Rect getClipBounds() { 16621 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16622 } 16623 16624 16625 /** 16626 * Populates an output rectangle with the clip bounds of the view, 16627 * returning {@code true} if successful or {@code false} if the view's 16628 * clip bounds are {@code null}. 16629 * 16630 * @param outRect rectangle in which to place the clip bounds of the view 16631 * @return {@code true} if successful or {@code false} if the view's 16632 * clip bounds are {@code null} 16633 */ 16634 public boolean getClipBounds(Rect outRect) { 16635 if (mClipBounds != null) { 16636 outRect.set(mClipBounds); 16637 return true; 16638 } 16639 return false; 16640 } 16641 16642 /** 16643 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16644 * case of an active Animation being run on the view. 16645 */ 16646 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16647 Animation a, boolean scalingRequired) { 16648 Transformation invalidationTransform; 16649 final int flags = parent.mGroupFlags; 16650 final boolean initialized = a.isInitialized(); 16651 if (!initialized) { 16652 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16653 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16654 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16655 onAnimationStart(); 16656 } 16657 16658 final Transformation t = parent.getChildTransformation(); 16659 boolean more = a.getTransformation(drawingTime, t, 1f); 16660 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16661 if (parent.mInvalidationTransformation == null) { 16662 parent.mInvalidationTransformation = new Transformation(); 16663 } 16664 invalidationTransform = parent.mInvalidationTransformation; 16665 a.getTransformation(drawingTime, invalidationTransform, 1f); 16666 } else { 16667 invalidationTransform = t; 16668 } 16669 16670 if (more) { 16671 if (!a.willChangeBounds()) { 16672 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16673 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16674 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16675 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16676 // The child need to draw an animation, potentially offscreen, so 16677 // make sure we do not cancel invalidate requests 16678 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16679 parent.invalidate(mLeft, mTop, mRight, mBottom); 16680 } 16681 } else { 16682 if (parent.mInvalidateRegion == null) { 16683 parent.mInvalidateRegion = new RectF(); 16684 } 16685 final RectF region = parent.mInvalidateRegion; 16686 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16687 invalidationTransform); 16688 16689 // The child need to draw an animation, potentially offscreen, so 16690 // make sure we do not cancel invalidate requests 16691 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16692 16693 final int left = mLeft + (int) region.left; 16694 final int top = mTop + (int) region.top; 16695 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16696 top + (int) (region.height() + .5f)); 16697 } 16698 } 16699 return more; 16700 } 16701 16702 /** 16703 * This method is called by getDisplayList() when a display list is recorded for a View. 16704 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16705 */ 16706 void setDisplayListProperties(RenderNode renderNode) { 16707 if (renderNode != null) { 16708 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16709 renderNode.setClipToBounds(mParent instanceof ViewGroup 16710 && ((ViewGroup) mParent).getClipChildren()); 16711 16712 float alpha = 1; 16713 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16714 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16715 ViewGroup parentVG = (ViewGroup) mParent; 16716 final Transformation t = parentVG.getChildTransformation(); 16717 if (parentVG.getChildStaticTransformation(this, t)) { 16718 final int transformType = t.getTransformationType(); 16719 if (transformType != Transformation.TYPE_IDENTITY) { 16720 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16721 alpha = t.getAlpha(); 16722 } 16723 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16724 renderNode.setStaticMatrix(t.getMatrix()); 16725 } 16726 } 16727 } 16728 } 16729 if (mTransformationInfo != null) { 16730 alpha *= getFinalAlpha(); 16731 if (alpha < 1) { 16732 final int multipliedAlpha = (int) (255 * alpha); 16733 if (onSetAlpha(multipliedAlpha)) { 16734 alpha = 1; 16735 } 16736 } 16737 renderNode.setAlpha(alpha); 16738 } else if (alpha < 1) { 16739 renderNode.setAlpha(alpha); 16740 } 16741 } 16742 } 16743 16744 /** 16745 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16746 * 16747 * This is where the View specializes rendering behavior based on layer type, 16748 * and hardware acceleration. 16749 */ 16750 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16751 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16752 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16753 * 16754 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16755 * HW accelerated, it can't handle drawing RenderNodes. 16756 */ 16757 boolean drawingWithRenderNode = mAttachInfo != null 16758 && mAttachInfo.mHardwareAccelerated 16759 && hardwareAcceleratedCanvas; 16760 16761 boolean more = false; 16762 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16763 final int parentFlags = parent.mGroupFlags; 16764 16765 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16766 parent.getChildTransformation().clear(); 16767 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16768 } 16769 16770 Transformation transformToApply = null; 16771 boolean concatMatrix = false; 16772 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16773 final Animation a = getAnimation(); 16774 if (a != null) { 16775 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16776 concatMatrix = a.willChangeTransformationMatrix(); 16777 if (concatMatrix) { 16778 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16779 } 16780 transformToApply = parent.getChildTransformation(); 16781 } else { 16782 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16783 // No longer animating: clear out old animation matrix 16784 mRenderNode.setAnimationMatrix(null); 16785 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16786 } 16787 if (!drawingWithRenderNode 16788 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16789 final Transformation t = parent.getChildTransformation(); 16790 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16791 if (hasTransform) { 16792 final int transformType = t.getTransformationType(); 16793 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16794 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16795 } 16796 } 16797 } 16798 16799 concatMatrix |= !childHasIdentityMatrix; 16800 16801 // Sets the flag as early as possible to allow draw() implementations 16802 // to call invalidate() successfully when doing animations 16803 mPrivateFlags |= PFLAG_DRAWN; 16804 16805 if (!concatMatrix && 16806 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16807 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16808 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16809 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16810 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16811 return more; 16812 } 16813 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16814 16815 if (hardwareAcceleratedCanvas) { 16816 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16817 // retain the flag's value temporarily in the mRecreateDisplayList flag 16818 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16819 mPrivateFlags &= ~PFLAG_INVALIDATED; 16820 } 16821 16822 RenderNode renderNode = null; 16823 Bitmap cache = null; 16824 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16825 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16826 if (layerType != LAYER_TYPE_NONE) { 16827 // If not drawing with RenderNode, treat HW layers as SW 16828 layerType = LAYER_TYPE_SOFTWARE; 16829 buildDrawingCache(true); 16830 } 16831 cache = getDrawingCache(true); 16832 } 16833 16834 if (drawingWithRenderNode) { 16835 // Delay getting the display list until animation-driven alpha values are 16836 // set up and possibly passed on to the view 16837 renderNode = updateDisplayListIfDirty(); 16838 if (!renderNode.isValid()) { 16839 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16840 // to getDisplayList(), the display list will be marked invalid and we should not 16841 // try to use it again. 16842 renderNode = null; 16843 drawingWithRenderNode = false; 16844 } 16845 } 16846 16847 int sx = 0; 16848 int sy = 0; 16849 if (!drawingWithRenderNode) { 16850 computeScroll(); 16851 sx = mScrollX; 16852 sy = mScrollY; 16853 } 16854 16855 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16856 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16857 16858 int restoreTo = -1; 16859 if (!drawingWithRenderNode || transformToApply != null) { 16860 restoreTo = canvas.save(); 16861 } 16862 if (offsetForScroll) { 16863 canvas.translate(mLeft - sx, mTop - sy); 16864 } else { 16865 if (!drawingWithRenderNode) { 16866 canvas.translate(mLeft, mTop); 16867 } 16868 if (scalingRequired) { 16869 if (drawingWithRenderNode) { 16870 // TODO: Might not need this if we put everything inside the DL 16871 restoreTo = canvas.save(); 16872 } 16873 // mAttachInfo cannot be null, otherwise scalingRequired == false 16874 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16875 canvas.scale(scale, scale); 16876 } 16877 } 16878 16879 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16880 if (transformToApply != null 16881 || alpha < 1 16882 || !hasIdentityMatrix() 16883 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16884 if (transformToApply != null || !childHasIdentityMatrix) { 16885 int transX = 0; 16886 int transY = 0; 16887 16888 if (offsetForScroll) { 16889 transX = -sx; 16890 transY = -sy; 16891 } 16892 16893 if (transformToApply != null) { 16894 if (concatMatrix) { 16895 if (drawingWithRenderNode) { 16896 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16897 } else { 16898 // Undo the scroll translation, apply the transformation matrix, 16899 // then redo the scroll translate to get the correct result. 16900 canvas.translate(-transX, -transY); 16901 canvas.concat(transformToApply.getMatrix()); 16902 canvas.translate(transX, transY); 16903 } 16904 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16905 } 16906 16907 float transformAlpha = transformToApply.getAlpha(); 16908 if (transformAlpha < 1) { 16909 alpha *= transformAlpha; 16910 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16911 } 16912 } 16913 16914 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16915 canvas.translate(-transX, -transY); 16916 canvas.concat(getMatrix()); 16917 canvas.translate(transX, transY); 16918 } 16919 } 16920 16921 // Deal with alpha if it is or used to be <1 16922 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16923 if (alpha < 1) { 16924 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16925 } else { 16926 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16927 } 16928 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16929 if (!drawingWithDrawingCache) { 16930 final int multipliedAlpha = (int) (255 * alpha); 16931 if (!onSetAlpha(multipliedAlpha)) { 16932 if (drawingWithRenderNode) { 16933 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16934 } else if (layerType == LAYER_TYPE_NONE) { 16935 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16936 multipliedAlpha); 16937 } 16938 } else { 16939 // Alpha is handled by the child directly, clobber the layer's alpha 16940 mPrivateFlags |= PFLAG_ALPHA_SET; 16941 } 16942 } 16943 } 16944 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16945 onSetAlpha(255); 16946 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16947 } 16948 16949 if (!drawingWithRenderNode) { 16950 // apply clips directly, since RenderNode won't do it for this draw 16951 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16952 if (offsetForScroll) { 16953 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16954 } else { 16955 if (!scalingRequired || cache == null) { 16956 canvas.clipRect(0, 0, getWidth(), getHeight()); 16957 } else { 16958 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16959 } 16960 } 16961 } 16962 16963 if (mClipBounds != null) { 16964 // clip bounds ignore scroll 16965 canvas.clipRect(mClipBounds); 16966 } 16967 } 16968 16969 if (!drawingWithDrawingCache) { 16970 if (drawingWithRenderNode) { 16971 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16972 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16973 } else { 16974 // Fast path for layouts with no backgrounds 16975 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16976 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16977 dispatchDraw(canvas); 16978 } else { 16979 draw(canvas); 16980 } 16981 } 16982 } else if (cache != null) { 16983 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16984 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 16985 // no layer paint, use temporary paint to draw bitmap 16986 Paint cachePaint = parent.mCachePaint; 16987 if (cachePaint == null) { 16988 cachePaint = new Paint(); 16989 cachePaint.setDither(false); 16990 parent.mCachePaint = cachePaint; 16991 } 16992 cachePaint.setAlpha((int) (alpha * 255)); 16993 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16994 } else { 16995 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16996 int layerPaintAlpha = mLayerPaint.getAlpha(); 16997 if (alpha < 1) { 16998 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 16999 } 17000 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 17001 if (alpha < 1) { 17002 mLayerPaint.setAlpha(layerPaintAlpha); 17003 } 17004 } 17005 } 17006 17007 if (restoreTo >= 0) { 17008 canvas.restoreToCount(restoreTo); 17009 } 17010 17011 if (a != null && !more) { 17012 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17013 onSetAlpha(255); 17014 } 17015 parent.finishAnimatingView(this, a); 17016 } 17017 17018 if (more && hardwareAcceleratedCanvas) { 17019 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17020 // alpha animations should cause the child to recreate its display list 17021 invalidate(true); 17022 } 17023 } 17024 17025 mRecreateDisplayList = false; 17026 17027 return more; 17028 } 17029 17030 /** 17031 * Manually render this view (and all of its children) to the given Canvas. 17032 * The view must have already done a full layout before this function is 17033 * called. When implementing a view, implement 17034 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17035 * If you do need to override this method, call the superclass version. 17036 * 17037 * @param canvas The Canvas to which the View is rendered. 17038 */ 17039 @CallSuper 17040 public void draw(Canvas canvas) { 17041 final int privateFlags = mPrivateFlags; 17042 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17043 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17044 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17045 17046 /* 17047 * Draw traversal performs several drawing steps which must be executed 17048 * in the appropriate order: 17049 * 17050 * 1. Draw the background 17051 * 2. If necessary, save the canvas' layers to prepare for fading 17052 * 3. Draw view's content 17053 * 4. Draw children 17054 * 5. If necessary, draw the fading edges and restore layers 17055 * 6. Draw decorations (scrollbars for instance) 17056 */ 17057 17058 // Step 1, draw the background, if needed 17059 int saveCount; 17060 17061 if (!dirtyOpaque) { 17062 drawBackground(canvas); 17063 } 17064 17065 // skip step 2 & 5 if possible (common case) 17066 final int viewFlags = mViewFlags; 17067 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17068 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17069 if (!verticalEdges && !horizontalEdges) { 17070 // Step 3, draw the content 17071 if (!dirtyOpaque) onDraw(canvas); 17072 17073 // Step 4, draw the children 17074 dispatchDraw(canvas); 17075 17076 // Overlay is part of the content and draws beneath Foreground 17077 if (mOverlay != null && !mOverlay.isEmpty()) { 17078 mOverlay.getOverlayView().dispatchDraw(canvas); 17079 } 17080 17081 // Step 6, draw decorations (foreground, scrollbars) 17082 onDrawForeground(canvas); 17083 17084 // we're done... 17085 return; 17086 } 17087 17088 /* 17089 * Here we do the full fledged routine... 17090 * (this is an uncommon case where speed matters less, 17091 * this is why we repeat some of the tests that have been 17092 * done above) 17093 */ 17094 17095 boolean drawTop = false; 17096 boolean drawBottom = false; 17097 boolean drawLeft = false; 17098 boolean drawRight = false; 17099 17100 float topFadeStrength = 0.0f; 17101 float bottomFadeStrength = 0.0f; 17102 float leftFadeStrength = 0.0f; 17103 float rightFadeStrength = 0.0f; 17104 17105 // Step 2, save the canvas' layers 17106 int paddingLeft = mPaddingLeft; 17107 17108 final boolean offsetRequired = isPaddingOffsetRequired(); 17109 if (offsetRequired) { 17110 paddingLeft += getLeftPaddingOffset(); 17111 } 17112 17113 int left = mScrollX + paddingLeft; 17114 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17115 int top = mScrollY + getFadeTop(offsetRequired); 17116 int bottom = top + getFadeHeight(offsetRequired); 17117 17118 if (offsetRequired) { 17119 right += getRightPaddingOffset(); 17120 bottom += getBottomPaddingOffset(); 17121 } 17122 17123 final ScrollabilityCache scrollabilityCache = mScrollCache; 17124 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17125 int length = (int) fadeHeight; 17126 17127 // clip the fade length if top and bottom fades overlap 17128 // overlapping fades produce odd-looking artifacts 17129 if (verticalEdges && (top + length > bottom - length)) { 17130 length = (bottom - top) / 2; 17131 } 17132 17133 // also clip horizontal fades if necessary 17134 if (horizontalEdges && (left + length > right - length)) { 17135 length = (right - left) / 2; 17136 } 17137 17138 if (verticalEdges) { 17139 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17140 drawTop = topFadeStrength * fadeHeight > 1.0f; 17141 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17142 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17143 } 17144 17145 if (horizontalEdges) { 17146 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17147 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17148 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17149 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17150 } 17151 17152 saveCount = canvas.getSaveCount(); 17153 17154 int solidColor = getSolidColor(); 17155 if (solidColor == 0) { 17156 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17157 17158 if (drawTop) { 17159 canvas.saveLayer(left, top, right, top + length, null, flags); 17160 } 17161 17162 if (drawBottom) { 17163 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17164 } 17165 17166 if (drawLeft) { 17167 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17168 } 17169 17170 if (drawRight) { 17171 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17172 } 17173 } else { 17174 scrollabilityCache.setFadeColor(solidColor); 17175 } 17176 17177 // Step 3, draw the content 17178 if (!dirtyOpaque) onDraw(canvas); 17179 17180 // Step 4, draw the children 17181 dispatchDraw(canvas); 17182 17183 // Step 5, draw the fade effect and restore layers 17184 final Paint p = scrollabilityCache.paint; 17185 final Matrix matrix = scrollabilityCache.matrix; 17186 final Shader fade = scrollabilityCache.shader; 17187 17188 if (drawTop) { 17189 matrix.setScale(1, fadeHeight * topFadeStrength); 17190 matrix.postTranslate(left, top); 17191 fade.setLocalMatrix(matrix); 17192 p.setShader(fade); 17193 canvas.drawRect(left, top, right, top + length, p); 17194 } 17195 17196 if (drawBottom) { 17197 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17198 matrix.postRotate(180); 17199 matrix.postTranslate(left, bottom); 17200 fade.setLocalMatrix(matrix); 17201 p.setShader(fade); 17202 canvas.drawRect(left, bottom - length, right, bottom, p); 17203 } 17204 17205 if (drawLeft) { 17206 matrix.setScale(1, fadeHeight * leftFadeStrength); 17207 matrix.postRotate(-90); 17208 matrix.postTranslate(left, top); 17209 fade.setLocalMatrix(matrix); 17210 p.setShader(fade); 17211 canvas.drawRect(left, top, left + length, bottom, p); 17212 } 17213 17214 if (drawRight) { 17215 matrix.setScale(1, fadeHeight * rightFadeStrength); 17216 matrix.postRotate(90); 17217 matrix.postTranslate(right, top); 17218 fade.setLocalMatrix(matrix); 17219 p.setShader(fade); 17220 canvas.drawRect(right - length, top, right, bottom, p); 17221 } 17222 17223 canvas.restoreToCount(saveCount); 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 17234 /** 17235 * Draws the background onto the specified canvas. 17236 * 17237 * @param canvas Canvas on which to draw the background 17238 */ 17239 private void drawBackground(Canvas canvas) { 17240 final Drawable background = mBackground; 17241 if (background == null) { 17242 return; 17243 } 17244 17245 setBackgroundBounds(); 17246 17247 // Attempt to use a display list if requested. 17248 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17249 && mAttachInfo.mHardwareRenderer != null) { 17250 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17251 17252 final RenderNode renderNode = mBackgroundRenderNode; 17253 if (renderNode != null && renderNode.isValid()) { 17254 setBackgroundRenderNodeProperties(renderNode); 17255 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17256 return; 17257 } 17258 } 17259 17260 final int scrollX = mScrollX; 17261 final int scrollY = mScrollY; 17262 if ((scrollX | scrollY) == 0) { 17263 background.draw(canvas); 17264 } else { 17265 canvas.translate(scrollX, scrollY); 17266 background.draw(canvas); 17267 canvas.translate(-scrollX, -scrollY); 17268 } 17269 } 17270 17271 /** 17272 * Sets the correct background bounds and rebuilds the outline, if needed. 17273 * <p/> 17274 * This is called by LayoutLib. 17275 */ 17276 void setBackgroundBounds() { 17277 if (mBackgroundSizeChanged && mBackground != null) { 17278 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17279 mBackgroundSizeChanged = false; 17280 rebuildOutline(); 17281 } 17282 } 17283 17284 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17285 renderNode.setTranslationX(mScrollX); 17286 renderNode.setTranslationY(mScrollY); 17287 } 17288 17289 /** 17290 * Creates a new display list or updates the existing display list for the 17291 * specified Drawable. 17292 * 17293 * @param drawable Drawable for which to create a display list 17294 * @param renderNode Existing RenderNode, or {@code null} 17295 * @return A valid display list for the specified drawable 17296 */ 17297 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17298 if (renderNode == null) { 17299 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17300 } 17301 17302 final Rect bounds = drawable.getBounds(); 17303 final int width = bounds.width(); 17304 final int height = bounds.height(); 17305 final DisplayListCanvas canvas = renderNode.start(width, height); 17306 17307 // Reverse left/top translation done by drawable canvas, which will 17308 // instead be applied by rendernode's LTRB bounds below. This way, the 17309 // drawable's bounds match with its rendernode bounds and its content 17310 // will lie within those bounds in the rendernode tree. 17311 canvas.translate(-bounds.left, -bounds.top); 17312 17313 try { 17314 drawable.draw(canvas); 17315 } finally { 17316 renderNode.end(canvas); 17317 } 17318 17319 // Set up drawable properties that are view-independent. 17320 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17321 renderNode.setProjectBackwards(drawable.isProjected()); 17322 renderNode.setProjectionReceiver(true); 17323 renderNode.setClipToBounds(false); 17324 return renderNode; 17325 } 17326 17327 /** 17328 * Returns the overlay for this view, creating it if it does not yet exist. 17329 * Adding drawables to the overlay will cause them to be displayed whenever 17330 * the view itself is redrawn. Objects in the overlay should be actively 17331 * managed: remove them when they should not be displayed anymore. The 17332 * overlay will always have the same size as its host view. 17333 * 17334 * <p>Note: Overlays do not currently work correctly with {@link 17335 * SurfaceView} or {@link TextureView}; contents in overlays for these 17336 * types of views may not display correctly.</p> 17337 * 17338 * @return The ViewOverlay object for this view. 17339 * @see ViewOverlay 17340 */ 17341 public ViewOverlay getOverlay() { 17342 if (mOverlay == null) { 17343 mOverlay = new ViewOverlay(mContext, this); 17344 } 17345 return mOverlay; 17346 } 17347 17348 /** 17349 * Override this if your view is known to always be drawn on top of a solid color background, 17350 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17351 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17352 * should be set to 0xFF. 17353 * 17354 * @see #setVerticalFadingEdgeEnabled(boolean) 17355 * @see #setHorizontalFadingEdgeEnabled(boolean) 17356 * 17357 * @return The known solid color background for this view, or 0 if the color may vary 17358 */ 17359 @ViewDebug.ExportedProperty(category = "drawing") 17360 @ColorInt 17361 public int getSolidColor() { 17362 return 0; 17363 } 17364 17365 /** 17366 * Build a human readable string representation of the specified view flags. 17367 * 17368 * @param flags the view flags to convert to a string 17369 * @return a String representing the supplied flags 17370 */ 17371 private static String printFlags(int flags) { 17372 String output = ""; 17373 int numFlags = 0; 17374 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17375 output += "TAKES_FOCUS"; 17376 numFlags++; 17377 } 17378 17379 switch (flags & VISIBILITY_MASK) { 17380 case INVISIBLE: 17381 if (numFlags > 0) { 17382 output += " "; 17383 } 17384 output += "INVISIBLE"; 17385 // USELESS HERE numFlags++; 17386 break; 17387 case GONE: 17388 if (numFlags > 0) { 17389 output += " "; 17390 } 17391 output += "GONE"; 17392 // USELESS HERE numFlags++; 17393 break; 17394 default: 17395 break; 17396 } 17397 return output; 17398 } 17399 17400 /** 17401 * Build a human readable string representation of the specified private 17402 * view flags. 17403 * 17404 * @param privateFlags the private view flags to convert to a string 17405 * @return a String representing the supplied flags 17406 */ 17407 private static String printPrivateFlags(int privateFlags) { 17408 String output = ""; 17409 int numFlags = 0; 17410 17411 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17412 output += "WANTS_FOCUS"; 17413 numFlags++; 17414 } 17415 17416 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17417 if (numFlags > 0) { 17418 output += " "; 17419 } 17420 output += "FOCUSED"; 17421 numFlags++; 17422 } 17423 17424 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17425 if (numFlags > 0) { 17426 output += " "; 17427 } 17428 output += "SELECTED"; 17429 numFlags++; 17430 } 17431 17432 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17433 if (numFlags > 0) { 17434 output += " "; 17435 } 17436 output += "IS_ROOT_NAMESPACE"; 17437 numFlags++; 17438 } 17439 17440 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17441 if (numFlags > 0) { 17442 output += " "; 17443 } 17444 output += "HAS_BOUNDS"; 17445 numFlags++; 17446 } 17447 17448 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17449 if (numFlags > 0) { 17450 output += " "; 17451 } 17452 output += "DRAWN"; 17453 // USELESS HERE numFlags++; 17454 } 17455 return output; 17456 } 17457 17458 /** 17459 * <p>Indicates whether or not this view's layout will be requested during 17460 * the next hierarchy layout pass.</p> 17461 * 17462 * @return true if the layout will be forced during next layout pass 17463 */ 17464 public boolean isLayoutRequested() { 17465 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17466 } 17467 17468 /** 17469 * Return true if o is a ViewGroup that is laying out using optical bounds. 17470 * @hide 17471 */ 17472 public static boolean isLayoutModeOptical(Object o) { 17473 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17474 } 17475 17476 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17477 Insets parentInsets = mParent instanceof View ? 17478 ((View) mParent).getOpticalInsets() : Insets.NONE; 17479 Insets childInsets = getOpticalInsets(); 17480 return setFrame( 17481 left + parentInsets.left - childInsets.left, 17482 top + parentInsets.top - childInsets.top, 17483 right + parentInsets.left + childInsets.right, 17484 bottom + parentInsets.top + childInsets.bottom); 17485 } 17486 17487 /** 17488 * Assign a size and position to a view and all of its 17489 * descendants 17490 * 17491 * <p>This is the second phase of the layout mechanism. 17492 * (The first is measuring). In this phase, each parent calls 17493 * layout on all of its children to position them. 17494 * This is typically done using the child measurements 17495 * that were stored in the measure pass().</p> 17496 * 17497 * <p>Derived classes should not override this method. 17498 * Derived classes with children should override 17499 * onLayout. In that method, they should 17500 * call layout on each of their children.</p> 17501 * 17502 * @param l Left position, relative to parent 17503 * @param t Top position, relative to parent 17504 * @param r Right position, relative to parent 17505 * @param b Bottom position, relative to parent 17506 */ 17507 @SuppressWarnings({"unchecked"}) 17508 public void layout(int l, int t, int r, int b) { 17509 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17510 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17511 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17512 } 17513 17514 int oldL = mLeft; 17515 int oldT = mTop; 17516 int oldB = mBottom; 17517 int oldR = mRight; 17518 17519 boolean changed = isLayoutModeOptical(mParent) ? 17520 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17521 17522 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17523 onLayout(changed, l, t, r, b); 17524 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17525 17526 ListenerInfo li = mListenerInfo; 17527 if (li != null && li.mOnLayoutChangeListeners != null) { 17528 ArrayList<OnLayoutChangeListener> listenersCopy = 17529 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17530 int numListeners = listenersCopy.size(); 17531 for (int i = 0; i < numListeners; ++i) { 17532 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17533 } 17534 } 17535 } 17536 17537 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17538 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17539 } 17540 17541 /** 17542 * Called from layout when this view should 17543 * assign a size and position to each of its children. 17544 * 17545 * Derived classes with children should override 17546 * this method and call layout on each of 17547 * their children. 17548 * @param changed This is a new size or position for this view 17549 * @param left Left position, relative to parent 17550 * @param top Top position, relative to parent 17551 * @param right Right position, relative to parent 17552 * @param bottom Bottom position, relative to parent 17553 */ 17554 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17555 } 17556 17557 /** 17558 * Assign a size and position to this view. 17559 * 17560 * This is called from layout. 17561 * 17562 * @param left Left position, relative to parent 17563 * @param top Top position, relative to parent 17564 * @param right Right position, relative to parent 17565 * @param bottom Bottom position, relative to parent 17566 * @return true if the new size and position are different than the 17567 * previous ones 17568 * {@hide} 17569 */ 17570 protected boolean setFrame(int left, int top, int right, int bottom) { 17571 boolean changed = false; 17572 17573 if (DBG) { 17574 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17575 + right + "," + bottom + ")"); 17576 } 17577 17578 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17579 changed = true; 17580 17581 // Remember our drawn bit 17582 int drawn = mPrivateFlags & PFLAG_DRAWN; 17583 17584 int oldWidth = mRight - mLeft; 17585 int oldHeight = mBottom - mTop; 17586 int newWidth = right - left; 17587 int newHeight = bottom - top; 17588 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17589 17590 // Invalidate our old position 17591 invalidate(sizeChanged); 17592 17593 mLeft = left; 17594 mTop = top; 17595 mRight = right; 17596 mBottom = bottom; 17597 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17598 17599 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17600 17601 17602 if (sizeChanged) { 17603 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17604 } 17605 17606 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17607 // If we are visible, force the DRAWN bit to on so that 17608 // this invalidate will go through (at least to our parent). 17609 // This is because someone may have invalidated this view 17610 // before this call to setFrame came in, thereby clearing 17611 // the DRAWN bit. 17612 mPrivateFlags |= PFLAG_DRAWN; 17613 invalidate(sizeChanged); 17614 // parent display list may need to be recreated based on a change in the bounds 17615 // of any child 17616 invalidateParentCaches(); 17617 } 17618 17619 // Reset drawn bit to original value (invalidate turns it off) 17620 mPrivateFlags |= drawn; 17621 17622 mBackgroundSizeChanged = true; 17623 if (mForegroundInfo != null) { 17624 mForegroundInfo.mBoundsChanged = true; 17625 } 17626 17627 notifySubtreeAccessibilityStateChangedIfNeeded(); 17628 } 17629 return changed; 17630 } 17631 17632 /** 17633 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17634 * @hide 17635 */ 17636 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17637 setFrame(left, top, right, bottom); 17638 } 17639 17640 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17641 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17642 if (mOverlay != null) { 17643 mOverlay.getOverlayView().setRight(newWidth); 17644 mOverlay.getOverlayView().setBottom(newHeight); 17645 } 17646 rebuildOutline(); 17647 } 17648 17649 /** 17650 * Finalize inflating a view from XML. This is called as the last phase 17651 * of inflation, after all child views have been added. 17652 * 17653 * <p>Even if the subclass overrides onFinishInflate, they should always be 17654 * sure to call the super method, so that we get called. 17655 */ 17656 @CallSuper 17657 protected void onFinishInflate() { 17658 } 17659 17660 /** 17661 * Returns the resources associated with this view. 17662 * 17663 * @return Resources object. 17664 */ 17665 public Resources getResources() { 17666 return mResources; 17667 } 17668 17669 /** 17670 * Invalidates the specified Drawable. 17671 * 17672 * @param drawable the drawable to invalidate 17673 */ 17674 @Override 17675 public void invalidateDrawable(@NonNull Drawable drawable) { 17676 if (verifyDrawable(drawable)) { 17677 final Rect dirty = drawable.getDirtyBounds(); 17678 final int scrollX = mScrollX; 17679 final int scrollY = mScrollY; 17680 17681 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17682 dirty.right + scrollX, dirty.bottom + scrollY); 17683 rebuildOutline(); 17684 } 17685 } 17686 17687 /** 17688 * Schedules an action on a drawable to occur at a specified time. 17689 * 17690 * @param who the recipient of the action 17691 * @param what the action to run on the drawable 17692 * @param when the time at which the action must occur. Uses the 17693 * {@link SystemClock#uptimeMillis} timebase. 17694 */ 17695 @Override 17696 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17697 if (verifyDrawable(who) && what != null) { 17698 final long delay = when - SystemClock.uptimeMillis(); 17699 if (mAttachInfo != null) { 17700 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17701 Choreographer.CALLBACK_ANIMATION, what, who, 17702 Choreographer.subtractFrameDelay(delay)); 17703 } else { 17704 // Postpone the runnable until we know 17705 // on which thread it needs to run. 17706 getRunQueue().postDelayed(what, delay); 17707 } 17708 } 17709 } 17710 17711 /** 17712 * Cancels a scheduled action on a drawable. 17713 * 17714 * @param who the recipient of the action 17715 * @param what the action to cancel 17716 */ 17717 @Override 17718 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17719 if (verifyDrawable(who) && what != null) { 17720 if (mAttachInfo != null) { 17721 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17722 Choreographer.CALLBACK_ANIMATION, what, who); 17723 } 17724 getRunQueue().removeCallbacks(what); 17725 } 17726 } 17727 17728 /** 17729 * Unschedule any events associated with the given Drawable. This can be 17730 * used when selecting a new Drawable into a view, so that the previous 17731 * one is completely unscheduled. 17732 * 17733 * @param who The Drawable to unschedule. 17734 * 17735 * @see #drawableStateChanged 17736 */ 17737 public void unscheduleDrawable(Drawable who) { 17738 if (mAttachInfo != null && who != null) { 17739 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17740 Choreographer.CALLBACK_ANIMATION, null, who); 17741 } 17742 } 17743 17744 /** 17745 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17746 * that the View directionality can and will be resolved before its Drawables. 17747 * 17748 * Will call {@link View#onResolveDrawables} when resolution is done. 17749 * 17750 * @hide 17751 */ 17752 protected void resolveDrawables() { 17753 // Drawables resolution may need to happen before resolving the layout direction (which is 17754 // done only during the measure() call). 17755 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17756 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17757 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17758 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17759 // direction to be resolved as its resolved value will be the same as its raw value. 17760 if (!isLayoutDirectionResolved() && 17761 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17762 return; 17763 } 17764 17765 final int layoutDirection = isLayoutDirectionResolved() ? 17766 getLayoutDirection() : getRawLayoutDirection(); 17767 17768 if (mBackground != null) { 17769 mBackground.setLayoutDirection(layoutDirection); 17770 } 17771 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17772 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17773 } 17774 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17775 onResolveDrawables(layoutDirection); 17776 } 17777 17778 boolean areDrawablesResolved() { 17779 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17780 } 17781 17782 /** 17783 * Called when layout direction has been resolved. 17784 * 17785 * The default implementation does nothing. 17786 * 17787 * @param layoutDirection The resolved layout direction. 17788 * 17789 * @see #LAYOUT_DIRECTION_LTR 17790 * @see #LAYOUT_DIRECTION_RTL 17791 * 17792 * @hide 17793 */ 17794 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17795 } 17796 17797 /** 17798 * @hide 17799 */ 17800 protected void resetResolvedDrawables() { 17801 resetResolvedDrawablesInternal(); 17802 } 17803 17804 void resetResolvedDrawablesInternal() { 17805 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17806 } 17807 17808 /** 17809 * If your view subclass is displaying its own Drawable objects, it should 17810 * override this function and return true for any Drawable it is 17811 * displaying. This allows animations for those drawables to be 17812 * scheduled. 17813 * 17814 * <p>Be sure to call through to the super class when overriding this 17815 * function. 17816 * 17817 * @param who The Drawable to verify. Return true if it is one you are 17818 * displaying, else return the result of calling through to the 17819 * super class. 17820 * 17821 * @return boolean If true than the Drawable is being displayed in the 17822 * view; else false and it is not allowed to animate. 17823 * 17824 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17825 * @see #drawableStateChanged() 17826 */ 17827 @CallSuper 17828 protected boolean verifyDrawable(@NonNull Drawable who) { 17829 // Avoid verifying the scroll bar drawable so that we don't end up in 17830 // an invalidation loop. This effectively prevents the scroll bar 17831 // drawable from triggering invalidations and scheduling runnables. 17832 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17833 } 17834 17835 /** 17836 * This function is called whenever the state of the view changes in such 17837 * a way that it impacts the state of drawables being shown. 17838 * <p> 17839 * If the View has a StateListAnimator, it will also be called to run necessary state 17840 * change animations. 17841 * <p> 17842 * Be sure to call through to the superclass when overriding this function. 17843 * 17844 * @see Drawable#setState(int[]) 17845 */ 17846 @CallSuper 17847 protected void drawableStateChanged() { 17848 final int[] state = getDrawableState(); 17849 boolean changed = false; 17850 17851 final Drawable bg = mBackground; 17852 if (bg != null && bg.isStateful()) { 17853 changed |= bg.setState(state); 17854 } 17855 17856 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17857 if (fg != null && fg.isStateful()) { 17858 changed |= fg.setState(state); 17859 } 17860 17861 if (mScrollCache != null) { 17862 final Drawable scrollBar = mScrollCache.scrollBar; 17863 if (scrollBar != null && scrollBar.isStateful()) { 17864 changed |= scrollBar.setState(state) 17865 && mScrollCache.state != ScrollabilityCache.OFF; 17866 } 17867 } 17868 17869 if (mStateListAnimator != null) { 17870 mStateListAnimator.setState(state); 17871 } 17872 17873 if (changed) { 17874 invalidate(); 17875 } 17876 } 17877 17878 /** 17879 * This function is called whenever the view hotspot changes and needs to 17880 * be propagated to drawables or child views managed by the view. 17881 * <p> 17882 * Dispatching to child views is handled by 17883 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17884 * <p> 17885 * Be sure to call through to the superclass when overriding this function. 17886 * 17887 * @param x hotspot x coordinate 17888 * @param y hotspot y coordinate 17889 */ 17890 @CallSuper 17891 public void drawableHotspotChanged(float x, float y) { 17892 if (mBackground != null) { 17893 mBackground.setHotspot(x, y); 17894 } 17895 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17896 mForegroundInfo.mDrawable.setHotspot(x, y); 17897 } 17898 17899 dispatchDrawableHotspotChanged(x, y); 17900 } 17901 17902 /** 17903 * Dispatches drawableHotspotChanged to all of this View's children. 17904 * 17905 * @param x hotspot x coordinate 17906 * @param y hotspot y coordinate 17907 * @see #drawableHotspotChanged(float, float) 17908 */ 17909 public void dispatchDrawableHotspotChanged(float x, float y) { 17910 } 17911 17912 /** 17913 * Call this to force a view to update its drawable state. This will cause 17914 * drawableStateChanged to be called on this view. Views that are interested 17915 * in the new state should call getDrawableState. 17916 * 17917 * @see #drawableStateChanged 17918 * @see #getDrawableState 17919 */ 17920 public void refreshDrawableState() { 17921 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17922 drawableStateChanged(); 17923 17924 ViewParent parent = mParent; 17925 if (parent != null) { 17926 parent.childDrawableStateChanged(this); 17927 } 17928 } 17929 17930 /** 17931 * Return an array of resource IDs of the drawable states representing the 17932 * current state of the view. 17933 * 17934 * @return The current drawable state 17935 * 17936 * @see Drawable#setState(int[]) 17937 * @see #drawableStateChanged() 17938 * @see #onCreateDrawableState(int) 17939 */ 17940 public final int[] getDrawableState() { 17941 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17942 return mDrawableState; 17943 } else { 17944 mDrawableState = onCreateDrawableState(0); 17945 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17946 return mDrawableState; 17947 } 17948 } 17949 17950 /** 17951 * Generate the new {@link android.graphics.drawable.Drawable} state for 17952 * this view. This is called by the view 17953 * system when the cached Drawable state is determined to be invalid. To 17954 * retrieve the current state, you should use {@link #getDrawableState}. 17955 * 17956 * @param extraSpace if non-zero, this is the number of extra entries you 17957 * would like in the returned array in which you can place your own 17958 * states. 17959 * 17960 * @return Returns an array holding the current {@link Drawable} state of 17961 * the view. 17962 * 17963 * @see #mergeDrawableStates(int[], int[]) 17964 */ 17965 protected int[] onCreateDrawableState(int extraSpace) { 17966 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17967 mParent instanceof View) { 17968 return ((View) mParent).onCreateDrawableState(extraSpace); 17969 } 17970 17971 int[] drawableState; 17972 17973 int privateFlags = mPrivateFlags; 17974 17975 int viewStateIndex = 0; 17976 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17977 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17978 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17979 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17980 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17981 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17982 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17983 ThreadedRenderer.isAvailable()) { 17984 // This is set if HW acceleration is requested, even if the current 17985 // process doesn't allow it. This is just to allow app preview 17986 // windows to better match their app. 17987 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17988 } 17989 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17990 17991 final int privateFlags2 = mPrivateFlags2; 17992 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17993 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17994 } 17995 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17996 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17997 } 17998 17999 drawableState = StateSet.get(viewStateIndex); 18000 18001 //noinspection ConstantIfStatement 18002 if (false) { 18003 Log.i("View", "drawableStateIndex=" + viewStateIndex); 18004 Log.i("View", toString() 18005 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 18006 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 18007 + " fo=" + hasFocus() 18008 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 18009 + " wf=" + hasWindowFocus() 18010 + ": " + Arrays.toString(drawableState)); 18011 } 18012 18013 if (extraSpace == 0) { 18014 return drawableState; 18015 } 18016 18017 final int[] fullState; 18018 if (drawableState != null) { 18019 fullState = new int[drawableState.length + extraSpace]; 18020 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18021 } else { 18022 fullState = new int[extraSpace]; 18023 } 18024 18025 return fullState; 18026 } 18027 18028 /** 18029 * Merge your own state values in <var>additionalState</var> into the base 18030 * state values <var>baseState</var> that were returned by 18031 * {@link #onCreateDrawableState(int)}. 18032 * 18033 * @param baseState The base state values returned by 18034 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18035 * own additional state values. 18036 * 18037 * @param additionalState The additional state values you would like 18038 * added to <var>baseState</var>; this array is not modified. 18039 * 18040 * @return As a convenience, the <var>baseState</var> array you originally 18041 * passed into the function is returned. 18042 * 18043 * @see #onCreateDrawableState(int) 18044 */ 18045 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18046 final int N = baseState.length; 18047 int i = N - 1; 18048 while (i >= 0 && baseState[i] == 0) { 18049 i--; 18050 } 18051 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18052 return baseState; 18053 } 18054 18055 /** 18056 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18057 * on all Drawable objects associated with this view. 18058 * <p> 18059 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18060 * attached to this view. 18061 */ 18062 @CallSuper 18063 public void jumpDrawablesToCurrentState() { 18064 if (mBackground != null) { 18065 mBackground.jumpToCurrentState(); 18066 } 18067 if (mStateListAnimator != null) { 18068 mStateListAnimator.jumpToCurrentState(); 18069 } 18070 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18071 mForegroundInfo.mDrawable.jumpToCurrentState(); 18072 } 18073 } 18074 18075 /** 18076 * Sets the background color for this view. 18077 * @param color the color of the background 18078 */ 18079 @RemotableViewMethod 18080 public void setBackgroundColor(@ColorInt int color) { 18081 if (mBackground instanceof ColorDrawable) { 18082 ((ColorDrawable) mBackground.mutate()).setColor(color); 18083 computeOpaqueFlags(); 18084 mBackgroundResource = 0; 18085 } else { 18086 setBackground(new ColorDrawable(color)); 18087 } 18088 } 18089 18090 /** 18091 * Set the background to a given resource. The resource should refer to 18092 * a Drawable object or 0 to remove the background. 18093 * @param resid The identifier of the resource. 18094 * 18095 * @attr ref android.R.styleable#View_background 18096 */ 18097 @RemotableViewMethod 18098 public void setBackgroundResource(@DrawableRes int resid) { 18099 if (resid != 0 && resid == mBackgroundResource) { 18100 return; 18101 } 18102 18103 Drawable d = null; 18104 if (resid != 0) { 18105 d = mContext.getDrawable(resid); 18106 } 18107 setBackground(d); 18108 18109 mBackgroundResource = resid; 18110 } 18111 18112 /** 18113 * Set the background to a given Drawable, or remove the background. If the 18114 * background has padding, this View's padding is set to the background's 18115 * padding. However, when a background is removed, this View's padding isn't 18116 * touched. If setting the padding is desired, please use 18117 * {@link #setPadding(int, int, int, int)}. 18118 * 18119 * @param background The Drawable to use as the background, or null to remove the 18120 * background 18121 */ 18122 public void setBackground(Drawable background) { 18123 //noinspection deprecation 18124 setBackgroundDrawable(background); 18125 } 18126 18127 /** 18128 * @deprecated use {@link #setBackground(Drawable)} instead 18129 */ 18130 @Deprecated 18131 public void setBackgroundDrawable(Drawable background) { 18132 computeOpaqueFlags(); 18133 18134 if (background == mBackground) { 18135 return; 18136 } 18137 18138 boolean requestLayout = false; 18139 18140 mBackgroundResource = 0; 18141 18142 /* 18143 * Regardless of whether we're setting a new background or not, we want 18144 * to clear the previous drawable. setVisible first while we still have the callback set. 18145 */ 18146 if (mBackground != null) { 18147 if (isAttachedToWindow()) { 18148 mBackground.setVisible(false, false); 18149 } 18150 mBackground.setCallback(null); 18151 unscheduleDrawable(mBackground); 18152 } 18153 18154 if (background != null) { 18155 Rect padding = sThreadLocal.get(); 18156 if (padding == null) { 18157 padding = new Rect(); 18158 sThreadLocal.set(padding); 18159 } 18160 resetResolvedDrawablesInternal(); 18161 background.setLayoutDirection(getLayoutDirection()); 18162 if (background.getPadding(padding)) { 18163 resetResolvedPaddingInternal(); 18164 switch (background.getLayoutDirection()) { 18165 case LAYOUT_DIRECTION_RTL: 18166 mUserPaddingLeftInitial = padding.right; 18167 mUserPaddingRightInitial = padding.left; 18168 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18169 break; 18170 case LAYOUT_DIRECTION_LTR: 18171 default: 18172 mUserPaddingLeftInitial = padding.left; 18173 mUserPaddingRightInitial = padding.right; 18174 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18175 } 18176 mLeftPaddingDefined = false; 18177 mRightPaddingDefined = false; 18178 } 18179 18180 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18181 // if it has a different minimum size, we should layout again 18182 if (mBackground == null 18183 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18184 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18185 requestLayout = true; 18186 } 18187 18188 // Set mBackground before we set this as the callback and start making other 18189 // background drawable state change calls. In particular, the setVisible call below 18190 // can result in drawables attempting to start animations or otherwise invalidate, 18191 // which requires the view set as the callback (us) to recognize the drawable as 18192 // belonging to it as per verifyDrawable. 18193 mBackground = background; 18194 if (background.isStateful()) { 18195 background.setState(getDrawableState()); 18196 } 18197 if (isAttachedToWindow()) { 18198 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18199 } 18200 18201 applyBackgroundTint(); 18202 18203 // Set callback last, since the view may still be initializing. 18204 background.setCallback(this); 18205 18206 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18207 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18208 requestLayout = true; 18209 } 18210 } else { 18211 /* Remove the background */ 18212 mBackground = null; 18213 if ((mViewFlags & WILL_NOT_DRAW) != 0 18214 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18215 mPrivateFlags |= PFLAG_SKIP_DRAW; 18216 } 18217 18218 /* 18219 * When the background is set, we try to apply its padding to this 18220 * View. When the background is removed, we don't touch this View's 18221 * padding. This is noted in the Javadocs. Hence, we don't need to 18222 * requestLayout(), the invalidate() below is sufficient. 18223 */ 18224 18225 // The old background's minimum size could have affected this 18226 // View's layout, so let's requestLayout 18227 requestLayout = true; 18228 } 18229 18230 computeOpaqueFlags(); 18231 18232 if (requestLayout) { 18233 requestLayout(); 18234 } 18235 18236 mBackgroundSizeChanged = true; 18237 invalidate(true); 18238 invalidateOutline(); 18239 } 18240 18241 /** 18242 * Gets the background drawable 18243 * 18244 * @return The drawable used as the background for this view, if any. 18245 * 18246 * @see #setBackground(Drawable) 18247 * 18248 * @attr ref android.R.styleable#View_background 18249 */ 18250 public Drawable getBackground() { 18251 return mBackground; 18252 } 18253 18254 /** 18255 * Applies a tint to the background drawable. Does not modify the current tint 18256 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18257 * <p> 18258 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18259 * mutate the drawable and apply the specified tint and tint mode using 18260 * {@link Drawable#setTintList(ColorStateList)}. 18261 * 18262 * @param tint the tint to apply, may be {@code null} to clear tint 18263 * 18264 * @attr ref android.R.styleable#View_backgroundTint 18265 * @see #getBackgroundTintList() 18266 * @see Drawable#setTintList(ColorStateList) 18267 */ 18268 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18269 if (mBackgroundTint == null) { 18270 mBackgroundTint = new TintInfo(); 18271 } 18272 mBackgroundTint.mTintList = tint; 18273 mBackgroundTint.mHasTintList = true; 18274 18275 applyBackgroundTint(); 18276 } 18277 18278 /** 18279 * Return the tint applied to the background drawable, if specified. 18280 * 18281 * @return the tint applied to the background drawable 18282 * @attr ref android.R.styleable#View_backgroundTint 18283 * @see #setBackgroundTintList(ColorStateList) 18284 */ 18285 @Nullable 18286 public ColorStateList getBackgroundTintList() { 18287 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18288 } 18289 18290 /** 18291 * Specifies the blending mode used to apply the tint specified by 18292 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18293 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18294 * 18295 * @param tintMode the blending mode used to apply the tint, may be 18296 * {@code null} to clear tint 18297 * @attr ref android.R.styleable#View_backgroundTintMode 18298 * @see #getBackgroundTintMode() 18299 * @see Drawable#setTintMode(PorterDuff.Mode) 18300 */ 18301 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18302 if (mBackgroundTint == null) { 18303 mBackgroundTint = new TintInfo(); 18304 } 18305 mBackgroundTint.mTintMode = tintMode; 18306 mBackgroundTint.mHasTintMode = true; 18307 18308 applyBackgroundTint(); 18309 } 18310 18311 /** 18312 * Return the blending mode used to apply the tint to the background 18313 * drawable, if specified. 18314 * 18315 * @return the blending mode used to apply the tint to the background 18316 * drawable 18317 * @attr ref android.R.styleable#View_backgroundTintMode 18318 * @see #setBackgroundTintMode(PorterDuff.Mode) 18319 */ 18320 @Nullable 18321 public PorterDuff.Mode getBackgroundTintMode() { 18322 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18323 } 18324 18325 private void applyBackgroundTint() { 18326 if (mBackground != null && mBackgroundTint != null) { 18327 final TintInfo tintInfo = mBackgroundTint; 18328 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18329 mBackground = mBackground.mutate(); 18330 18331 if (tintInfo.mHasTintList) { 18332 mBackground.setTintList(tintInfo.mTintList); 18333 } 18334 18335 if (tintInfo.mHasTintMode) { 18336 mBackground.setTintMode(tintInfo.mTintMode); 18337 } 18338 18339 // The drawable (or one of its children) may not have been 18340 // stateful before applying the tint, so let's try again. 18341 if (mBackground.isStateful()) { 18342 mBackground.setState(getDrawableState()); 18343 } 18344 } 18345 } 18346 } 18347 18348 /** 18349 * Returns the drawable used as the foreground of this View. The 18350 * foreground drawable, if non-null, is always drawn on top of the view's content. 18351 * 18352 * @return a Drawable or null if no foreground was set 18353 * 18354 * @see #onDrawForeground(Canvas) 18355 */ 18356 public Drawable getForeground() { 18357 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18358 } 18359 18360 /** 18361 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18362 * 18363 * @param foreground the Drawable to be drawn on top of the children 18364 * 18365 * @attr ref android.R.styleable#View_foreground 18366 */ 18367 public void setForeground(Drawable foreground) { 18368 if (mForegroundInfo == null) { 18369 if (foreground == null) { 18370 // Nothing to do. 18371 return; 18372 } 18373 mForegroundInfo = new ForegroundInfo(); 18374 } 18375 18376 if (foreground == mForegroundInfo.mDrawable) { 18377 // Nothing to do 18378 return; 18379 } 18380 18381 if (mForegroundInfo.mDrawable != null) { 18382 if (isAttachedToWindow()) { 18383 mForegroundInfo.mDrawable.setVisible(false, false); 18384 } 18385 mForegroundInfo.mDrawable.setCallback(null); 18386 unscheduleDrawable(mForegroundInfo.mDrawable); 18387 } 18388 18389 mForegroundInfo.mDrawable = foreground; 18390 mForegroundInfo.mBoundsChanged = true; 18391 if (foreground != null) { 18392 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18393 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18394 } 18395 foreground.setLayoutDirection(getLayoutDirection()); 18396 if (foreground.isStateful()) { 18397 foreground.setState(getDrawableState()); 18398 } 18399 applyForegroundTint(); 18400 if (isAttachedToWindow()) { 18401 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18402 } 18403 // Set callback last, since the view may still be initializing. 18404 foreground.setCallback(this); 18405 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18406 mPrivateFlags |= PFLAG_SKIP_DRAW; 18407 } 18408 requestLayout(); 18409 invalidate(); 18410 } 18411 18412 /** 18413 * Magic bit used to support features of framework-internal window decor implementation details. 18414 * This used to live exclusively in FrameLayout. 18415 * 18416 * @return true if the foreground should draw inside the padding region or false 18417 * if it should draw inset by the view's padding 18418 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18419 */ 18420 public boolean isForegroundInsidePadding() { 18421 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18422 } 18423 18424 /** 18425 * Describes how the foreground is positioned. 18426 * 18427 * @return foreground gravity. 18428 * 18429 * @see #setForegroundGravity(int) 18430 * 18431 * @attr ref android.R.styleable#View_foregroundGravity 18432 */ 18433 public int getForegroundGravity() { 18434 return mForegroundInfo != null ? mForegroundInfo.mGravity 18435 : Gravity.START | Gravity.TOP; 18436 } 18437 18438 /** 18439 * Describes how the foreground is positioned. Defaults to START and TOP. 18440 * 18441 * @param gravity see {@link android.view.Gravity} 18442 * 18443 * @see #getForegroundGravity() 18444 * 18445 * @attr ref android.R.styleable#View_foregroundGravity 18446 */ 18447 public void setForegroundGravity(int gravity) { 18448 if (mForegroundInfo == null) { 18449 mForegroundInfo = new ForegroundInfo(); 18450 } 18451 18452 if (mForegroundInfo.mGravity != gravity) { 18453 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18454 gravity |= Gravity.START; 18455 } 18456 18457 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18458 gravity |= Gravity.TOP; 18459 } 18460 18461 mForegroundInfo.mGravity = gravity; 18462 requestLayout(); 18463 } 18464 } 18465 18466 /** 18467 * Applies a tint to the foreground drawable. Does not modify the current tint 18468 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18469 * <p> 18470 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18471 * mutate the drawable and apply the specified tint and tint mode using 18472 * {@link Drawable#setTintList(ColorStateList)}. 18473 * 18474 * @param tint the tint to apply, may be {@code null} to clear tint 18475 * 18476 * @attr ref android.R.styleable#View_foregroundTint 18477 * @see #getForegroundTintList() 18478 * @see Drawable#setTintList(ColorStateList) 18479 */ 18480 public void setForegroundTintList(@Nullable ColorStateList tint) { 18481 if (mForegroundInfo == null) { 18482 mForegroundInfo = new ForegroundInfo(); 18483 } 18484 if (mForegroundInfo.mTintInfo == null) { 18485 mForegroundInfo.mTintInfo = new TintInfo(); 18486 } 18487 mForegroundInfo.mTintInfo.mTintList = tint; 18488 mForegroundInfo.mTintInfo.mHasTintList = true; 18489 18490 applyForegroundTint(); 18491 } 18492 18493 /** 18494 * Return the tint applied to the foreground drawable, if specified. 18495 * 18496 * @return the tint applied to the foreground drawable 18497 * @attr ref android.R.styleable#View_foregroundTint 18498 * @see #setForegroundTintList(ColorStateList) 18499 */ 18500 @Nullable 18501 public ColorStateList getForegroundTintList() { 18502 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18503 ? mForegroundInfo.mTintInfo.mTintList : null; 18504 } 18505 18506 /** 18507 * Specifies the blending mode used to apply the tint specified by 18508 * {@link #setForegroundTintList(ColorStateList)}} to the background 18509 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18510 * 18511 * @param tintMode the blending mode used to apply the tint, may be 18512 * {@code null} to clear tint 18513 * @attr ref android.R.styleable#View_foregroundTintMode 18514 * @see #getForegroundTintMode() 18515 * @see Drawable#setTintMode(PorterDuff.Mode) 18516 */ 18517 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18518 if (mForegroundInfo == null) { 18519 mForegroundInfo = new ForegroundInfo(); 18520 } 18521 if (mForegroundInfo.mTintInfo == null) { 18522 mForegroundInfo.mTintInfo = new TintInfo(); 18523 } 18524 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18525 mForegroundInfo.mTintInfo.mHasTintMode = true; 18526 18527 applyForegroundTint(); 18528 } 18529 18530 /** 18531 * Return the blending mode used to apply the tint to the foreground 18532 * drawable, if specified. 18533 * 18534 * @return the blending mode used to apply the tint to the foreground 18535 * drawable 18536 * @attr ref android.R.styleable#View_foregroundTintMode 18537 * @see #setForegroundTintMode(PorterDuff.Mode) 18538 */ 18539 @Nullable 18540 public PorterDuff.Mode getForegroundTintMode() { 18541 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18542 ? mForegroundInfo.mTintInfo.mTintMode : null; 18543 } 18544 18545 private void applyForegroundTint() { 18546 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18547 && mForegroundInfo.mTintInfo != null) { 18548 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18549 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18550 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18551 18552 if (tintInfo.mHasTintList) { 18553 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18554 } 18555 18556 if (tintInfo.mHasTintMode) { 18557 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18558 } 18559 18560 // The drawable (or one of its children) may not have been 18561 // stateful before applying the tint, so let's try again. 18562 if (mForegroundInfo.mDrawable.isStateful()) { 18563 mForegroundInfo.mDrawable.setState(getDrawableState()); 18564 } 18565 } 18566 } 18567 } 18568 18569 /** 18570 * Draw any foreground content for this view. 18571 * 18572 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18573 * drawable or other view-specific decorations. The foreground is drawn on top of the 18574 * primary view content.</p> 18575 * 18576 * @param canvas canvas to draw into 18577 */ 18578 public void onDrawForeground(Canvas canvas) { 18579 onDrawScrollIndicators(canvas); 18580 onDrawScrollBars(canvas); 18581 18582 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18583 if (foreground != null) { 18584 if (mForegroundInfo.mBoundsChanged) { 18585 mForegroundInfo.mBoundsChanged = false; 18586 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18587 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18588 18589 if (mForegroundInfo.mInsidePadding) { 18590 selfBounds.set(0, 0, getWidth(), getHeight()); 18591 } else { 18592 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18593 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18594 } 18595 18596 final int ld = getLayoutDirection(); 18597 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18598 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18599 foreground.setBounds(overlayBounds); 18600 } 18601 18602 foreground.draw(canvas); 18603 } 18604 } 18605 18606 /** 18607 * Sets the padding. The view may add on the space required to display 18608 * the scrollbars, depending on the style and visibility of the scrollbars. 18609 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18610 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18611 * from the values set in this call. 18612 * 18613 * @attr ref android.R.styleable#View_padding 18614 * @attr ref android.R.styleable#View_paddingBottom 18615 * @attr ref android.R.styleable#View_paddingLeft 18616 * @attr ref android.R.styleable#View_paddingRight 18617 * @attr ref android.R.styleable#View_paddingTop 18618 * @param left the left padding in pixels 18619 * @param top the top padding in pixels 18620 * @param right the right padding in pixels 18621 * @param bottom the bottom padding in pixels 18622 */ 18623 public void setPadding(int left, int top, int right, int bottom) { 18624 resetResolvedPaddingInternal(); 18625 18626 mUserPaddingStart = UNDEFINED_PADDING; 18627 mUserPaddingEnd = UNDEFINED_PADDING; 18628 18629 mUserPaddingLeftInitial = left; 18630 mUserPaddingRightInitial = right; 18631 18632 mLeftPaddingDefined = true; 18633 mRightPaddingDefined = true; 18634 18635 internalSetPadding(left, top, right, bottom); 18636 } 18637 18638 /** 18639 * @hide 18640 */ 18641 protected void internalSetPadding(int left, int top, int right, int bottom) { 18642 mUserPaddingLeft = left; 18643 mUserPaddingRight = right; 18644 mUserPaddingBottom = bottom; 18645 18646 final int viewFlags = mViewFlags; 18647 boolean changed = false; 18648 18649 // Common case is there are no scroll bars. 18650 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18651 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18652 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18653 ? 0 : getVerticalScrollbarWidth(); 18654 switch (mVerticalScrollbarPosition) { 18655 case SCROLLBAR_POSITION_DEFAULT: 18656 if (isLayoutRtl()) { 18657 left += offset; 18658 } else { 18659 right += offset; 18660 } 18661 break; 18662 case SCROLLBAR_POSITION_RIGHT: 18663 right += offset; 18664 break; 18665 case SCROLLBAR_POSITION_LEFT: 18666 left += offset; 18667 break; 18668 } 18669 } 18670 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18671 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18672 ? 0 : getHorizontalScrollbarHeight(); 18673 } 18674 } 18675 18676 if (mPaddingLeft != left) { 18677 changed = true; 18678 mPaddingLeft = left; 18679 } 18680 if (mPaddingTop != top) { 18681 changed = true; 18682 mPaddingTop = top; 18683 } 18684 if (mPaddingRight != right) { 18685 changed = true; 18686 mPaddingRight = right; 18687 } 18688 if (mPaddingBottom != bottom) { 18689 changed = true; 18690 mPaddingBottom = bottom; 18691 } 18692 18693 if (changed) { 18694 requestLayout(); 18695 invalidateOutline(); 18696 } 18697 } 18698 18699 /** 18700 * Sets the relative padding. The view may add on the space required to display 18701 * the scrollbars, depending on the style and visibility of the scrollbars. 18702 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18703 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18704 * from the values set in this call. 18705 * 18706 * @attr ref android.R.styleable#View_padding 18707 * @attr ref android.R.styleable#View_paddingBottom 18708 * @attr ref android.R.styleable#View_paddingStart 18709 * @attr ref android.R.styleable#View_paddingEnd 18710 * @attr ref android.R.styleable#View_paddingTop 18711 * @param start the start padding in pixels 18712 * @param top the top padding in pixels 18713 * @param end the end padding in pixels 18714 * @param bottom the bottom padding in pixels 18715 */ 18716 public void setPaddingRelative(int start, int top, int end, int bottom) { 18717 resetResolvedPaddingInternal(); 18718 18719 mUserPaddingStart = start; 18720 mUserPaddingEnd = end; 18721 mLeftPaddingDefined = true; 18722 mRightPaddingDefined = true; 18723 18724 switch(getLayoutDirection()) { 18725 case LAYOUT_DIRECTION_RTL: 18726 mUserPaddingLeftInitial = end; 18727 mUserPaddingRightInitial = start; 18728 internalSetPadding(end, top, start, bottom); 18729 break; 18730 case LAYOUT_DIRECTION_LTR: 18731 default: 18732 mUserPaddingLeftInitial = start; 18733 mUserPaddingRightInitial = end; 18734 internalSetPadding(start, top, end, bottom); 18735 } 18736 } 18737 18738 /** 18739 * Returns the top padding of this view. 18740 * 18741 * @return the top padding in pixels 18742 */ 18743 public int getPaddingTop() { 18744 return mPaddingTop; 18745 } 18746 18747 /** 18748 * Returns the bottom padding of this view. If there are inset and enabled 18749 * scrollbars, this value may include the space required to display the 18750 * scrollbars as well. 18751 * 18752 * @return the bottom padding in pixels 18753 */ 18754 public int getPaddingBottom() { 18755 return mPaddingBottom; 18756 } 18757 18758 /** 18759 * Returns the left padding of this view. If there are inset and enabled 18760 * scrollbars, this value may include the space required to display the 18761 * scrollbars as well. 18762 * 18763 * @return the left padding in pixels 18764 */ 18765 public int getPaddingLeft() { 18766 if (!isPaddingResolved()) { 18767 resolvePadding(); 18768 } 18769 return mPaddingLeft; 18770 } 18771 18772 /** 18773 * Returns the start padding of this view depending on its resolved layout direction. 18774 * If there are inset and enabled scrollbars, this value may include the space 18775 * required to display the scrollbars as well. 18776 * 18777 * @return the start padding in pixels 18778 */ 18779 public int getPaddingStart() { 18780 if (!isPaddingResolved()) { 18781 resolvePadding(); 18782 } 18783 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18784 mPaddingRight : mPaddingLeft; 18785 } 18786 18787 /** 18788 * Returns the right padding of this view. If there are inset and enabled 18789 * scrollbars, this value may include the space required to display the 18790 * scrollbars as well. 18791 * 18792 * @return the right padding in pixels 18793 */ 18794 public int getPaddingRight() { 18795 if (!isPaddingResolved()) { 18796 resolvePadding(); 18797 } 18798 return mPaddingRight; 18799 } 18800 18801 /** 18802 * Returns the end padding of this view depending on its resolved layout direction. 18803 * If there are inset and enabled scrollbars, this value may include the space 18804 * required to display the scrollbars as well. 18805 * 18806 * @return the end padding in pixels 18807 */ 18808 public int getPaddingEnd() { 18809 if (!isPaddingResolved()) { 18810 resolvePadding(); 18811 } 18812 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18813 mPaddingLeft : mPaddingRight; 18814 } 18815 18816 /** 18817 * Return if the padding has been set through relative values 18818 * {@link #setPaddingRelative(int, int, int, int)} or through 18819 * @attr ref android.R.styleable#View_paddingStart or 18820 * @attr ref android.R.styleable#View_paddingEnd 18821 * 18822 * @return true if the padding is relative or false if it is not. 18823 */ 18824 public boolean isPaddingRelative() { 18825 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18826 } 18827 18828 Insets computeOpticalInsets() { 18829 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18830 } 18831 18832 /** 18833 * @hide 18834 */ 18835 public void resetPaddingToInitialValues() { 18836 if (isRtlCompatibilityMode()) { 18837 mPaddingLeft = mUserPaddingLeftInitial; 18838 mPaddingRight = mUserPaddingRightInitial; 18839 return; 18840 } 18841 if (isLayoutRtl()) { 18842 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18843 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18844 } else { 18845 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18846 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18847 } 18848 } 18849 18850 /** 18851 * @hide 18852 */ 18853 public Insets getOpticalInsets() { 18854 if (mLayoutInsets == null) { 18855 mLayoutInsets = computeOpticalInsets(); 18856 } 18857 return mLayoutInsets; 18858 } 18859 18860 /** 18861 * Set this view's optical insets. 18862 * 18863 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18864 * property. Views that compute their own optical insets should call it as part of measurement. 18865 * This method does not request layout. If you are setting optical insets outside of 18866 * measure/layout itself you will want to call requestLayout() yourself. 18867 * </p> 18868 * @hide 18869 */ 18870 public void setOpticalInsets(Insets insets) { 18871 mLayoutInsets = insets; 18872 } 18873 18874 /** 18875 * Changes the selection state of this view. A view can be selected or not. 18876 * Note that selection is not the same as focus. Views are typically 18877 * selected in the context of an AdapterView like ListView or GridView; 18878 * the selected view is the view that is highlighted. 18879 * 18880 * @param selected true if the view must be selected, false otherwise 18881 */ 18882 public void setSelected(boolean selected) { 18883 //noinspection DoubleNegation 18884 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18885 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18886 if (!selected) resetPressedState(); 18887 invalidate(true); 18888 refreshDrawableState(); 18889 dispatchSetSelected(selected); 18890 if (selected) { 18891 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18892 } else { 18893 notifyViewAccessibilityStateChangedIfNeeded( 18894 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18895 } 18896 } 18897 } 18898 18899 /** 18900 * Dispatch setSelected to all of this View's children. 18901 * 18902 * @see #setSelected(boolean) 18903 * 18904 * @param selected The new selected state 18905 */ 18906 protected void dispatchSetSelected(boolean selected) { 18907 } 18908 18909 /** 18910 * Indicates the selection state of this view. 18911 * 18912 * @return true if the view is selected, false otherwise 18913 */ 18914 @ViewDebug.ExportedProperty 18915 public boolean isSelected() { 18916 return (mPrivateFlags & PFLAG_SELECTED) != 0; 18917 } 18918 18919 /** 18920 * Changes the activated state of this view. A view can be activated or not. 18921 * Note that activation is not the same as selection. Selection is 18922 * a transient property, representing the view (hierarchy) the user is 18923 * currently interacting with. Activation is a longer-term state that the 18924 * user can move views in and out of. For example, in a list view with 18925 * single or multiple selection enabled, the views in the current selection 18926 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18927 * here.) The activated state is propagated down to children of the view it 18928 * is set on. 18929 * 18930 * @param activated true if the view must be activated, false otherwise 18931 */ 18932 public void setActivated(boolean activated) { 18933 //noinspection DoubleNegation 18934 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18935 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18936 invalidate(true); 18937 refreshDrawableState(); 18938 dispatchSetActivated(activated); 18939 } 18940 } 18941 18942 /** 18943 * Dispatch setActivated to all of this View's children. 18944 * 18945 * @see #setActivated(boolean) 18946 * 18947 * @param activated The new activated state 18948 */ 18949 protected void dispatchSetActivated(boolean activated) { 18950 } 18951 18952 /** 18953 * Indicates the activation state of this view. 18954 * 18955 * @return true if the view is activated, false otherwise 18956 */ 18957 @ViewDebug.ExportedProperty 18958 public boolean isActivated() { 18959 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18960 } 18961 18962 /** 18963 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18964 * observer can be used to get notifications when global events, like 18965 * layout, happen. 18966 * 18967 * The returned ViewTreeObserver observer is not guaranteed to remain 18968 * valid for the lifetime of this View. If the caller of this method keeps 18969 * a long-lived reference to ViewTreeObserver, it should always check for 18970 * the return value of {@link ViewTreeObserver#isAlive()}. 18971 * 18972 * @return The ViewTreeObserver for this view's hierarchy. 18973 */ 18974 public ViewTreeObserver getViewTreeObserver() { 18975 if (mAttachInfo != null) { 18976 return mAttachInfo.mTreeObserver; 18977 } 18978 if (mFloatingTreeObserver == null) { 18979 mFloatingTreeObserver = new ViewTreeObserver(); 18980 } 18981 return mFloatingTreeObserver; 18982 } 18983 18984 /** 18985 * <p>Finds the topmost view in the current view hierarchy.</p> 18986 * 18987 * @return the topmost view containing this view 18988 */ 18989 public View getRootView() { 18990 if (mAttachInfo != null) { 18991 final View v = mAttachInfo.mRootView; 18992 if (v != null) { 18993 return v; 18994 } 18995 } 18996 18997 View parent = this; 18998 18999 while (parent.mParent != null && parent.mParent instanceof View) { 19000 parent = (View) parent.mParent; 19001 } 19002 19003 return parent; 19004 } 19005 19006 /** 19007 * Transforms a motion event from view-local coordinates to on-screen 19008 * coordinates. 19009 * 19010 * @param ev the view-local motion event 19011 * @return false if the transformation could not be applied 19012 * @hide 19013 */ 19014 public boolean toGlobalMotionEvent(MotionEvent ev) { 19015 final AttachInfo info = mAttachInfo; 19016 if (info == null) { 19017 return false; 19018 } 19019 19020 final Matrix m = info.mTmpMatrix; 19021 m.set(Matrix.IDENTITY_MATRIX); 19022 transformMatrixToGlobal(m); 19023 ev.transform(m); 19024 return true; 19025 } 19026 19027 /** 19028 * Transforms a motion event from on-screen coordinates to view-local 19029 * coordinates. 19030 * 19031 * @param ev the on-screen motion event 19032 * @return false if the transformation could not be applied 19033 * @hide 19034 */ 19035 public boolean toLocalMotionEvent(MotionEvent ev) { 19036 final AttachInfo info = mAttachInfo; 19037 if (info == null) { 19038 return false; 19039 } 19040 19041 final Matrix m = info.mTmpMatrix; 19042 m.set(Matrix.IDENTITY_MATRIX); 19043 transformMatrixToLocal(m); 19044 ev.transform(m); 19045 return true; 19046 } 19047 19048 /** 19049 * Modifies the input matrix such that it maps view-local coordinates to 19050 * on-screen coordinates. 19051 * 19052 * @param m input matrix to modify 19053 * @hide 19054 */ 19055 public void transformMatrixToGlobal(Matrix m) { 19056 final ViewParent parent = mParent; 19057 if (parent instanceof View) { 19058 final View vp = (View) parent; 19059 vp.transformMatrixToGlobal(m); 19060 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19061 } else if (parent instanceof ViewRootImpl) { 19062 final ViewRootImpl vr = (ViewRootImpl) parent; 19063 vr.transformMatrixToGlobal(m); 19064 m.preTranslate(0, -vr.mCurScrollY); 19065 } 19066 19067 m.preTranslate(mLeft, mTop); 19068 19069 if (!hasIdentityMatrix()) { 19070 m.preConcat(getMatrix()); 19071 } 19072 } 19073 19074 /** 19075 * Modifies the input matrix such that it maps on-screen coordinates to 19076 * view-local coordinates. 19077 * 19078 * @param m input matrix to modify 19079 * @hide 19080 */ 19081 public void transformMatrixToLocal(Matrix m) { 19082 final ViewParent parent = mParent; 19083 if (parent instanceof View) { 19084 final View vp = (View) parent; 19085 vp.transformMatrixToLocal(m); 19086 m.postTranslate(vp.mScrollX, vp.mScrollY); 19087 } else if (parent instanceof ViewRootImpl) { 19088 final ViewRootImpl vr = (ViewRootImpl) parent; 19089 vr.transformMatrixToLocal(m); 19090 m.postTranslate(0, vr.mCurScrollY); 19091 } 19092 19093 m.postTranslate(-mLeft, -mTop); 19094 19095 if (!hasIdentityMatrix()) { 19096 m.postConcat(getInverseMatrix()); 19097 } 19098 } 19099 19100 /** 19101 * @hide 19102 */ 19103 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19104 @ViewDebug.IntToString(from = 0, to = "x"), 19105 @ViewDebug.IntToString(from = 1, to = "y") 19106 }) 19107 public int[] getLocationOnScreen() { 19108 int[] location = new int[2]; 19109 getLocationOnScreen(location); 19110 return location; 19111 } 19112 19113 /** 19114 * <p>Computes the coordinates of this view on the screen. The argument 19115 * must be an array of two integers. After the method returns, the array 19116 * contains the x and y location in that order.</p> 19117 * 19118 * @param outLocation an array of two integers in which to hold the coordinates 19119 */ 19120 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19121 getLocationInWindow(outLocation); 19122 19123 final AttachInfo info = mAttachInfo; 19124 if (info != null) { 19125 outLocation[0] += info.mWindowLeft; 19126 outLocation[1] += info.mWindowTop; 19127 } 19128 } 19129 19130 /** 19131 * <p>Computes the coordinates of this view in its window. The argument 19132 * must be an array of two integers. After the method returns, the array 19133 * contains the x and y location in that order.</p> 19134 * 19135 * @param outLocation an array of two integers in which to hold the coordinates 19136 */ 19137 public void getLocationInWindow(@Size(2) int[] outLocation) { 19138 if (outLocation == null || outLocation.length < 2) { 19139 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19140 } 19141 19142 outLocation[0] = 0; 19143 outLocation[1] = 0; 19144 19145 transformFromViewToWindowSpace(outLocation); 19146 } 19147 19148 /** @hide */ 19149 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19150 if (inOutLocation == null || inOutLocation.length < 2) { 19151 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19152 } 19153 19154 if (mAttachInfo == null) { 19155 // When the view is not attached to a window, this method does not make sense 19156 inOutLocation[0] = inOutLocation[1] = 0; 19157 return; 19158 } 19159 19160 float position[] = mAttachInfo.mTmpTransformLocation; 19161 position[0] = inOutLocation[0]; 19162 position[1] = inOutLocation[1]; 19163 19164 if (!hasIdentityMatrix()) { 19165 getMatrix().mapPoints(position); 19166 } 19167 19168 position[0] += mLeft; 19169 position[1] += mTop; 19170 19171 ViewParent viewParent = mParent; 19172 while (viewParent instanceof View) { 19173 final View view = (View) viewParent; 19174 19175 position[0] -= view.mScrollX; 19176 position[1] -= view.mScrollY; 19177 19178 if (!view.hasIdentityMatrix()) { 19179 view.getMatrix().mapPoints(position); 19180 } 19181 19182 position[0] += view.mLeft; 19183 position[1] += view.mTop; 19184 19185 viewParent = view.mParent; 19186 } 19187 19188 if (viewParent instanceof ViewRootImpl) { 19189 // *cough* 19190 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19191 position[1] -= vr.mCurScrollY; 19192 } 19193 19194 inOutLocation[0] = Math.round(position[0]); 19195 inOutLocation[1] = Math.round(position[1]); 19196 } 19197 19198 /** 19199 * {@hide} 19200 * @param id the id of the view to be found 19201 * @return the view of the specified id, null if cannot be found 19202 */ 19203 protected View findViewTraversal(@IdRes int id) { 19204 if (id == mID) { 19205 return this; 19206 } 19207 return null; 19208 } 19209 19210 /** 19211 * {@hide} 19212 * @param tag the tag of the view to be found 19213 * @return the view of specified tag, null if cannot be found 19214 */ 19215 protected View findViewWithTagTraversal(Object tag) { 19216 if (tag != null && tag.equals(mTag)) { 19217 return this; 19218 } 19219 return null; 19220 } 19221 19222 /** 19223 * {@hide} 19224 * @param predicate The predicate to evaluate. 19225 * @param childToSkip If not null, ignores this child during the recursive traversal. 19226 * @return The first view that matches the predicate or null. 19227 */ 19228 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19229 if (predicate.apply(this)) { 19230 return this; 19231 } 19232 return null; 19233 } 19234 19235 /** 19236 * Look for a child view with the given id. If this view has the given 19237 * id, return this view. 19238 * 19239 * @param id The id to search for. 19240 * @return The view that has the given id in the hierarchy or null 19241 */ 19242 @Nullable 19243 public final View findViewById(@IdRes int id) { 19244 if (id < 0) { 19245 return null; 19246 } 19247 return findViewTraversal(id); 19248 } 19249 19250 /** 19251 * Finds a view by its unuque and stable accessibility id. 19252 * 19253 * @param accessibilityId The searched accessibility id. 19254 * @return The found view. 19255 */ 19256 final View findViewByAccessibilityId(int accessibilityId) { 19257 if (accessibilityId < 0) { 19258 return null; 19259 } 19260 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19261 if (view != null) { 19262 return view.includeForAccessibility() ? view : null; 19263 } 19264 return null; 19265 } 19266 19267 /** 19268 * Performs the traversal to find a view by its unuque and stable accessibility id. 19269 * 19270 * <strong>Note:</strong>This method does not stop at the root namespace 19271 * boundary since the user can touch the screen at an arbitrary location 19272 * potentially crossing the root namespace bounday which will send an 19273 * accessibility event to accessibility services and they should be able 19274 * to obtain the event source. Also accessibility ids are guaranteed to be 19275 * unique in the window. 19276 * 19277 * @param accessibilityId The accessibility id. 19278 * @return The found view. 19279 * 19280 * @hide 19281 */ 19282 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19283 if (getAccessibilityViewId() == accessibilityId) { 19284 return this; 19285 } 19286 return null; 19287 } 19288 19289 /** 19290 * Look for a child view with the given tag. If this view has the given 19291 * tag, return this view. 19292 * 19293 * @param tag The tag to search for, using "tag.equals(getTag())". 19294 * @return The View that has the given tag in the hierarchy or null 19295 */ 19296 public final View findViewWithTag(Object tag) { 19297 if (tag == null) { 19298 return null; 19299 } 19300 return findViewWithTagTraversal(tag); 19301 } 19302 19303 /** 19304 * {@hide} 19305 * Look for a child view that matches the specified predicate. 19306 * If this view matches the predicate, return this view. 19307 * 19308 * @param predicate The predicate to evaluate. 19309 * @return The first view that matches the predicate or null. 19310 */ 19311 public final View findViewByPredicate(Predicate<View> predicate) { 19312 return findViewByPredicateTraversal(predicate, null); 19313 } 19314 19315 /** 19316 * {@hide} 19317 * Look for a child view that matches the specified predicate, 19318 * starting with the specified view and its descendents and then 19319 * recusively searching the ancestors and siblings of that view 19320 * until this view is reached. 19321 * 19322 * This method is useful in cases where the predicate does not match 19323 * a single unique view (perhaps multiple views use the same id) 19324 * and we are trying to find the view that is "closest" in scope to the 19325 * starting view. 19326 * 19327 * @param start The view to start from. 19328 * @param predicate The predicate to evaluate. 19329 * @return The first view that matches the predicate or null. 19330 */ 19331 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19332 View childToSkip = null; 19333 for (;;) { 19334 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19335 if (view != null || start == this) { 19336 return view; 19337 } 19338 19339 ViewParent parent = start.getParent(); 19340 if (parent == null || !(parent instanceof View)) { 19341 return null; 19342 } 19343 19344 childToSkip = start; 19345 start = (View) parent; 19346 } 19347 } 19348 19349 /** 19350 * Sets the identifier for this view. The identifier does not have to be 19351 * unique in this view's hierarchy. The identifier should be a positive 19352 * number. 19353 * 19354 * @see #NO_ID 19355 * @see #getId() 19356 * @see #findViewById(int) 19357 * 19358 * @param id a number used to identify the view 19359 * 19360 * @attr ref android.R.styleable#View_id 19361 */ 19362 public void setId(@IdRes int id) { 19363 mID = id; 19364 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19365 mID = generateViewId(); 19366 } 19367 } 19368 19369 /** 19370 * {@hide} 19371 * 19372 * @param isRoot true if the view belongs to the root namespace, false 19373 * otherwise 19374 */ 19375 public void setIsRootNamespace(boolean isRoot) { 19376 if (isRoot) { 19377 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19378 } else { 19379 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19380 } 19381 } 19382 19383 /** 19384 * {@hide} 19385 * 19386 * @return true if the view belongs to the root namespace, false otherwise 19387 */ 19388 public boolean isRootNamespace() { 19389 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19390 } 19391 19392 /** 19393 * Returns this view's identifier. 19394 * 19395 * @return a positive integer used to identify the view or {@link #NO_ID} 19396 * if the view has no ID 19397 * 19398 * @see #setId(int) 19399 * @see #findViewById(int) 19400 * @attr ref android.R.styleable#View_id 19401 */ 19402 @IdRes 19403 @ViewDebug.CapturedViewProperty 19404 public int getId() { 19405 return mID; 19406 } 19407 19408 /** 19409 * Returns this view's tag. 19410 * 19411 * @return the Object stored in this view as a tag, or {@code null} if not 19412 * set 19413 * 19414 * @see #setTag(Object) 19415 * @see #getTag(int) 19416 */ 19417 @ViewDebug.ExportedProperty 19418 public Object getTag() { 19419 return mTag; 19420 } 19421 19422 /** 19423 * Sets the tag associated with this view. A tag can be used to mark 19424 * a view in its hierarchy and does not have to be unique within the 19425 * hierarchy. Tags can also be used to store data within a view without 19426 * resorting to another data structure. 19427 * 19428 * @param tag an Object to tag the view with 19429 * 19430 * @see #getTag() 19431 * @see #setTag(int, Object) 19432 */ 19433 public void setTag(final Object tag) { 19434 mTag = tag; 19435 } 19436 19437 /** 19438 * Returns the tag associated with this view and the specified key. 19439 * 19440 * @param key The key identifying the tag 19441 * 19442 * @return the Object stored in this view as a tag, or {@code null} if not 19443 * set 19444 * 19445 * @see #setTag(int, Object) 19446 * @see #getTag() 19447 */ 19448 public Object getTag(int key) { 19449 if (mKeyedTags != null) return mKeyedTags.get(key); 19450 return null; 19451 } 19452 19453 /** 19454 * Sets a tag associated with this view and a key. A tag can be used 19455 * to mark a view in its hierarchy and does not have to be unique within 19456 * the hierarchy. Tags can also be used to store data within a view 19457 * without resorting to another data structure. 19458 * 19459 * The specified key should be an id declared in the resources of the 19460 * application to ensure it is unique (see the <a 19461 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19462 * Keys identified as belonging to 19463 * the Android framework or not associated with any package will cause 19464 * an {@link IllegalArgumentException} to be thrown. 19465 * 19466 * @param key The key identifying the tag 19467 * @param tag An Object to tag the view with 19468 * 19469 * @throws IllegalArgumentException If they specified key is not valid 19470 * 19471 * @see #setTag(Object) 19472 * @see #getTag(int) 19473 */ 19474 public void setTag(int key, final Object tag) { 19475 // If the package id is 0x00 or 0x01, it's either an undefined package 19476 // or a framework id 19477 if ((key >>> 24) < 2) { 19478 throw new IllegalArgumentException("The key must be an application-specific " 19479 + "resource id."); 19480 } 19481 19482 setKeyedTag(key, tag); 19483 } 19484 19485 /** 19486 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19487 * framework id. 19488 * 19489 * @hide 19490 */ 19491 public void setTagInternal(int key, Object tag) { 19492 if ((key >>> 24) != 0x1) { 19493 throw new IllegalArgumentException("The key must be a framework-specific " 19494 + "resource id."); 19495 } 19496 19497 setKeyedTag(key, tag); 19498 } 19499 19500 private void setKeyedTag(int key, Object tag) { 19501 if (mKeyedTags == null) { 19502 mKeyedTags = new SparseArray<Object>(2); 19503 } 19504 19505 mKeyedTags.put(key, tag); 19506 } 19507 19508 /** 19509 * Prints information about this view in the log output, with the tag 19510 * {@link #VIEW_LOG_TAG}. 19511 * 19512 * @hide 19513 */ 19514 public void debug() { 19515 debug(0); 19516 } 19517 19518 /** 19519 * Prints information about this view in the log output, with the tag 19520 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19521 * indentation defined by the <code>depth</code>. 19522 * 19523 * @param depth the indentation level 19524 * 19525 * @hide 19526 */ 19527 protected void debug(int depth) { 19528 String output = debugIndent(depth - 1); 19529 19530 output += "+ " + this; 19531 int id = getId(); 19532 if (id != -1) { 19533 output += " (id=" + id + ")"; 19534 } 19535 Object tag = getTag(); 19536 if (tag != null) { 19537 output += " (tag=" + tag + ")"; 19538 } 19539 Log.d(VIEW_LOG_TAG, output); 19540 19541 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19542 output = debugIndent(depth) + " FOCUSED"; 19543 Log.d(VIEW_LOG_TAG, output); 19544 } 19545 19546 output = debugIndent(depth); 19547 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19548 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19549 + "} "; 19550 Log.d(VIEW_LOG_TAG, output); 19551 19552 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19553 || mPaddingBottom != 0) { 19554 output = debugIndent(depth); 19555 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19556 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19557 Log.d(VIEW_LOG_TAG, output); 19558 } 19559 19560 output = debugIndent(depth); 19561 output += "mMeasureWidth=" + mMeasuredWidth + 19562 " mMeasureHeight=" + mMeasuredHeight; 19563 Log.d(VIEW_LOG_TAG, output); 19564 19565 output = debugIndent(depth); 19566 if (mLayoutParams == null) { 19567 output += "BAD! no layout params"; 19568 } else { 19569 output = mLayoutParams.debug(output); 19570 } 19571 Log.d(VIEW_LOG_TAG, output); 19572 19573 output = debugIndent(depth); 19574 output += "flags={"; 19575 output += View.printFlags(mViewFlags); 19576 output += "}"; 19577 Log.d(VIEW_LOG_TAG, output); 19578 19579 output = debugIndent(depth); 19580 output += "privateFlags={"; 19581 output += View.printPrivateFlags(mPrivateFlags); 19582 output += "}"; 19583 Log.d(VIEW_LOG_TAG, output); 19584 } 19585 19586 /** 19587 * Creates a string of whitespaces used for indentation. 19588 * 19589 * @param depth the indentation level 19590 * @return a String containing (depth * 2 + 3) * 2 white spaces 19591 * 19592 * @hide 19593 */ 19594 protected static String debugIndent(int depth) { 19595 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19596 for (int i = 0; i < (depth * 2) + 3; i++) { 19597 spaces.append(' ').append(' '); 19598 } 19599 return spaces.toString(); 19600 } 19601 19602 /** 19603 * <p>Return the offset of the widget's text baseline from the widget's top 19604 * boundary. If this widget does not support baseline alignment, this 19605 * method returns -1. </p> 19606 * 19607 * @return the offset of the baseline within the widget's bounds or -1 19608 * if baseline alignment is not supported 19609 */ 19610 @ViewDebug.ExportedProperty(category = "layout") 19611 public int getBaseline() { 19612 return -1; 19613 } 19614 19615 /** 19616 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19617 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19618 * a layout pass. 19619 * 19620 * @return whether the view hierarchy is currently undergoing a layout pass 19621 */ 19622 public boolean isInLayout() { 19623 ViewRootImpl viewRoot = getViewRootImpl(); 19624 return (viewRoot != null && viewRoot.isInLayout()); 19625 } 19626 19627 /** 19628 * Call this when something has changed which has invalidated the 19629 * layout of this view. This will schedule a layout pass of the view 19630 * tree. This should not be called while the view hierarchy is currently in a layout 19631 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19632 * end of the current layout pass (and then layout will run again) or after the current 19633 * frame is drawn and the next layout occurs. 19634 * 19635 * <p>Subclasses which override this method should call the superclass method to 19636 * handle possible request-during-layout errors correctly.</p> 19637 */ 19638 @CallSuper 19639 public void requestLayout() { 19640 if (mMeasureCache != null) mMeasureCache.clear(); 19641 19642 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19643 // Only trigger request-during-layout logic if this is the view requesting it, 19644 // not the views in its parent hierarchy 19645 ViewRootImpl viewRoot = getViewRootImpl(); 19646 if (viewRoot != null && viewRoot.isInLayout()) { 19647 if (!viewRoot.requestLayoutDuringLayout(this)) { 19648 return; 19649 } 19650 } 19651 mAttachInfo.mViewRequestingLayout = this; 19652 } 19653 19654 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19655 mPrivateFlags |= PFLAG_INVALIDATED; 19656 19657 if (mParent != null && !mParent.isLayoutRequested()) { 19658 mParent.requestLayout(); 19659 } 19660 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19661 mAttachInfo.mViewRequestingLayout = null; 19662 } 19663 } 19664 19665 /** 19666 * Forces this view to be laid out during the next layout pass. 19667 * This method does not call requestLayout() or forceLayout() 19668 * on the parent. 19669 */ 19670 public void forceLayout() { 19671 if (mMeasureCache != null) mMeasureCache.clear(); 19672 19673 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19674 mPrivateFlags |= PFLAG_INVALIDATED; 19675 } 19676 19677 /** 19678 * <p> 19679 * This is called to find out how big a view should be. The parent 19680 * supplies constraint information in the width and height parameters. 19681 * </p> 19682 * 19683 * <p> 19684 * The actual measurement work of a view is performed in 19685 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19686 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19687 * </p> 19688 * 19689 * 19690 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19691 * parent 19692 * @param heightMeasureSpec Vertical space requirements as imposed by the 19693 * parent 19694 * 19695 * @see #onMeasure(int, int) 19696 */ 19697 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19698 boolean optical = isLayoutModeOptical(this); 19699 if (optical != isLayoutModeOptical(mParent)) { 19700 Insets insets = getOpticalInsets(); 19701 int oWidth = insets.left + insets.right; 19702 int oHeight = insets.top + insets.bottom; 19703 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19704 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19705 } 19706 19707 // Suppress sign extension for the low bytes 19708 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19709 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19710 19711 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19712 19713 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19714 // already measured as the correct size. In API 23 and below, this 19715 // extra pass is required to make LinearLayout re-distribute weight. 19716 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19717 || heightMeasureSpec != mOldHeightMeasureSpec; 19718 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19719 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19720 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19721 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19722 final boolean needsLayout = specChanged 19723 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19724 19725 if (forceLayout || needsLayout) { 19726 // first clears the measured dimension flag 19727 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19728 19729 resolveRtlPropertiesIfNeeded(); 19730 19731 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19732 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19733 // measure ourselves, this should set the measured dimension flag back 19734 onMeasure(widthMeasureSpec, heightMeasureSpec); 19735 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19736 } else { 19737 long value = mMeasureCache.valueAt(cacheIndex); 19738 // Casting a long to int drops the high 32 bits, no mask needed 19739 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19740 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19741 } 19742 19743 // flag not set, setMeasuredDimension() was not invoked, we raise 19744 // an exception to warn the developer 19745 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19746 throw new IllegalStateException("View with id " + getId() + ": " 19747 + getClass().getName() + "#onMeasure() did not set the" 19748 + " measured dimension by calling" 19749 + " setMeasuredDimension()"); 19750 } 19751 19752 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19753 } 19754 19755 mOldWidthMeasureSpec = widthMeasureSpec; 19756 mOldHeightMeasureSpec = heightMeasureSpec; 19757 19758 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19759 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19760 } 19761 19762 /** 19763 * <p> 19764 * Measure the view and its content to determine the measured width and the 19765 * measured height. This method is invoked by {@link #measure(int, int)} and 19766 * should be overridden by subclasses to provide accurate and efficient 19767 * measurement of their contents. 19768 * </p> 19769 * 19770 * <p> 19771 * <strong>CONTRACT:</strong> When overriding this method, you 19772 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19773 * measured width and height of this view. Failure to do so will trigger an 19774 * <code>IllegalStateException</code>, thrown by 19775 * {@link #measure(int, int)}. Calling the superclass' 19776 * {@link #onMeasure(int, int)} is a valid use. 19777 * </p> 19778 * 19779 * <p> 19780 * The base class implementation of measure defaults to the background size, 19781 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19782 * override {@link #onMeasure(int, int)} to provide better measurements of 19783 * their content. 19784 * </p> 19785 * 19786 * <p> 19787 * If this method is overridden, it is the subclass's responsibility to make 19788 * sure the measured height and width are at least the view's minimum height 19789 * and width ({@link #getSuggestedMinimumHeight()} and 19790 * {@link #getSuggestedMinimumWidth()}). 19791 * </p> 19792 * 19793 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19794 * The requirements are encoded with 19795 * {@link android.view.View.MeasureSpec}. 19796 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19797 * The requirements are encoded with 19798 * {@link android.view.View.MeasureSpec}. 19799 * 19800 * @see #getMeasuredWidth() 19801 * @see #getMeasuredHeight() 19802 * @see #setMeasuredDimension(int, int) 19803 * @see #getSuggestedMinimumHeight() 19804 * @see #getSuggestedMinimumWidth() 19805 * @see android.view.View.MeasureSpec#getMode(int) 19806 * @see android.view.View.MeasureSpec#getSize(int) 19807 */ 19808 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19809 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19810 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19811 } 19812 19813 /** 19814 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19815 * measured width and measured height. Failing to do so will trigger an 19816 * exception at measurement time.</p> 19817 * 19818 * @param measuredWidth The measured width of this view. May be a complex 19819 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19820 * {@link #MEASURED_STATE_TOO_SMALL}. 19821 * @param measuredHeight The measured height of this view. May be a complex 19822 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19823 * {@link #MEASURED_STATE_TOO_SMALL}. 19824 */ 19825 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19826 boolean optical = isLayoutModeOptical(this); 19827 if (optical != isLayoutModeOptical(mParent)) { 19828 Insets insets = getOpticalInsets(); 19829 int opticalWidth = insets.left + insets.right; 19830 int opticalHeight = insets.top + insets.bottom; 19831 19832 measuredWidth += optical ? opticalWidth : -opticalWidth; 19833 measuredHeight += optical ? opticalHeight : -opticalHeight; 19834 } 19835 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19836 } 19837 19838 /** 19839 * Sets the measured dimension without extra processing for things like optical bounds. 19840 * Useful for reapplying consistent values that have already been cooked with adjustments 19841 * for optical bounds, etc. such as those from the measurement cache. 19842 * 19843 * @param measuredWidth The measured width of this view. May be a complex 19844 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19845 * {@link #MEASURED_STATE_TOO_SMALL}. 19846 * @param measuredHeight The measured height of this view. May be a complex 19847 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19848 * {@link #MEASURED_STATE_TOO_SMALL}. 19849 */ 19850 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19851 mMeasuredWidth = measuredWidth; 19852 mMeasuredHeight = measuredHeight; 19853 19854 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19855 } 19856 19857 /** 19858 * Merge two states as returned by {@link #getMeasuredState()}. 19859 * @param curState The current state as returned from a view or the result 19860 * of combining multiple views. 19861 * @param newState The new view state to combine. 19862 * @return Returns a new integer reflecting the combination of the two 19863 * states. 19864 */ 19865 public static int combineMeasuredStates(int curState, int newState) { 19866 return curState | newState; 19867 } 19868 19869 /** 19870 * Version of {@link #resolveSizeAndState(int, int, int)} 19871 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19872 */ 19873 public static int resolveSize(int size, int measureSpec) { 19874 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19875 } 19876 19877 /** 19878 * Utility to reconcile a desired size and state, with constraints imposed 19879 * by a MeasureSpec. Will take the desired size, unless a different size 19880 * is imposed by the constraints. The returned value is a compound integer, 19881 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19882 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19883 * resulting size is smaller than the size the view wants to be. 19884 * 19885 * @param size How big the view wants to be. 19886 * @param measureSpec Constraints imposed by the parent. 19887 * @param childMeasuredState Size information bit mask for the view's 19888 * children. 19889 * @return Size information bit mask as defined by 19890 * {@link #MEASURED_SIZE_MASK} and 19891 * {@link #MEASURED_STATE_TOO_SMALL}. 19892 */ 19893 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19894 final int specMode = MeasureSpec.getMode(measureSpec); 19895 final int specSize = MeasureSpec.getSize(measureSpec); 19896 final int result; 19897 switch (specMode) { 19898 case MeasureSpec.AT_MOST: 19899 if (specSize < size) { 19900 result = specSize | MEASURED_STATE_TOO_SMALL; 19901 } else { 19902 result = size; 19903 } 19904 break; 19905 case MeasureSpec.EXACTLY: 19906 result = specSize; 19907 break; 19908 case MeasureSpec.UNSPECIFIED: 19909 default: 19910 result = size; 19911 } 19912 return result | (childMeasuredState & MEASURED_STATE_MASK); 19913 } 19914 19915 /** 19916 * Utility to return a default size. Uses the supplied size if the 19917 * MeasureSpec imposed no constraints. Will get larger if allowed 19918 * by the MeasureSpec. 19919 * 19920 * @param size Default size for this view 19921 * @param measureSpec Constraints imposed by the parent 19922 * @return The size this view should be. 19923 */ 19924 public static int getDefaultSize(int size, int measureSpec) { 19925 int result = size; 19926 int specMode = MeasureSpec.getMode(measureSpec); 19927 int specSize = MeasureSpec.getSize(measureSpec); 19928 19929 switch (specMode) { 19930 case MeasureSpec.UNSPECIFIED: 19931 result = size; 19932 break; 19933 case MeasureSpec.AT_MOST: 19934 case MeasureSpec.EXACTLY: 19935 result = specSize; 19936 break; 19937 } 19938 return result; 19939 } 19940 19941 /** 19942 * Returns the suggested minimum height that the view should use. This 19943 * returns the maximum of the view's minimum height 19944 * and the background's minimum height 19945 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19946 * <p> 19947 * When being used in {@link #onMeasure(int, int)}, the caller should still 19948 * ensure the returned height is within the requirements of the parent. 19949 * 19950 * @return The suggested minimum height of the view. 19951 */ 19952 protected int getSuggestedMinimumHeight() { 19953 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19954 19955 } 19956 19957 /** 19958 * Returns the suggested minimum width that the view should use. This 19959 * returns the maximum of the view's minimum width 19960 * and the background's minimum width 19961 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19962 * <p> 19963 * When being used in {@link #onMeasure(int, int)}, the caller should still 19964 * ensure the returned width is within the requirements of the parent. 19965 * 19966 * @return The suggested minimum width of the view. 19967 */ 19968 protected int getSuggestedMinimumWidth() { 19969 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19970 } 19971 19972 /** 19973 * Returns the minimum height of the view. 19974 * 19975 * @return the minimum height the view will try to be. 19976 * 19977 * @see #setMinimumHeight(int) 19978 * 19979 * @attr ref android.R.styleable#View_minHeight 19980 */ 19981 public int getMinimumHeight() { 19982 return mMinHeight; 19983 } 19984 19985 /** 19986 * Sets the minimum height of the view. It is not guaranteed the view will 19987 * be able to achieve this minimum height (for example, if its parent layout 19988 * constrains it with less available height). 19989 * 19990 * @param minHeight The minimum height the view will try to be. 19991 * 19992 * @see #getMinimumHeight() 19993 * 19994 * @attr ref android.R.styleable#View_minHeight 19995 */ 19996 @RemotableViewMethod 19997 public void setMinimumHeight(int minHeight) { 19998 mMinHeight = minHeight; 19999 requestLayout(); 20000 } 20001 20002 /** 20003 * Returns the minimum width of the view. 20004 * 20005 * @return the minimum width the view will try to be. 20006 * 20007 * @see #setMinimumWidth(int) 20008 * 20009 * @attr ref android.R.styleable#View_minWidth 20010 */ 20011 public int getMinimumWidth() { 20012 return mMinWidth; 20013 } 20014 20015 /** 20016 * Sets the minimum width of the view. It is not guaranteed the view will 20017 * be able to achieve this minimum width (for example, if its parent layout 20018 * constrains it with less available width). 20019 * 20020 * @param minWidth The minimum width the view will try to be. 20021 * 20022 * @see #getMinimumWidth() 20023 * 20024 * @attr ref android.R.styleable#View_minWidth 20025 */ 20026 public void setMinimumWidth(int minWidth) { 20027 mMinWidth = minWidth; 20028 requestLayout(); 20029 20030 } 20031 20032 /** 20033 * Get the animation currently associated with this view. 20034 * 20035 * @return The animation that is currently playing or 20036 * scheduled to play for this view. 20037 */ 20038 public Animation getAnimation() { 20039 return mCurrentAnimation; 20040 } 20041 20042 /** 20043 * Start the specified animation now. 20044 * 20045 * @param animation the animation to start now 20046 */ 20047 public void startAnimation(Animation animation) { 20048 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20049 setAnimation(animation); 20050 invalidateParentCaches(); 20051 invalidate(true); 20052 } 20053 20054 /** 20055 * Cancels any animations for this view. 20056 */ 20057 public void clearAnimation() { 20058 if (mCurrentAnimation != null) { 20059 mCurrentAnimation.detach(); 20060 } 20061 mCurrentAnimation = null; 20062 invalidateParentIfNeeded(); 20063 } 20064 20065 /** 20066 * Sets the next animation to play for this view. 20067 * If you want the animation to play immediately, use 20068 * {@link #startAnimation(android.view.animation.Animation)} instead. 20069 * This method provides allows fine-grained 20070 * control over the start time and invalidation, but you 20071 * must make sure that 1) the animation has a start time set, and 20072 * 2) the view's parent (which controls animations on its children) 20073 * will be invalidated when the animation is supposed to 20074 * start. 20075 * 20076 * @param animation The next animation, or null. 20077 */ 20078 public void setAnimation(Animation animation) { 20079 mCurrentAnimation = animation; 20080 20081 if (animation != null) { 20082 // If the screen is off assume the animation start time is now instead of 20083 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20084 // would cause the animation to start when the screen turns back on 20085 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20086 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20087 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20088 } 20089 animation.reset(); 20090 } 20091 } 20092 20093 /** 20094 * Invoked by a parent ViewGroup to notify the start of the animation 20095 * currently associated with this view. If you override this method, 20096 * always call super.onAnimationStart(); 20097 * 20098 * @see #setAnimation(android.view.animation.Animation) 20099 * @see #getAnimation() 20100 */ 20101 @CallSuper 20102 protected void onAnimationStart() { 20103 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20104 } 20105 20106 /** 20107 * Invoked by a parent ViewGroup to notify the end of the animation 20108 * currently associated with this view. If you override this method, 20109 * always call super.onAnimationEnd(); 20110 * 20111 * @see #setAnimation(android.view.animation.Animation) 20112 * @see #getAnimation() 20113 */ 20114 @CallSuper 20115 protected void onAnimationEnd() { 20116 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20117 } 20118 20119 /** 20120 * Invoked if there is a Transform that involves alpha. Subclass that can 20121 * draw themselves with the specified alpha should return true, and then 20122 * respect that alpha when their onDraw() is called. If this returns false 20123 * then the view may be redirected to draw into an offscreen buffer to 20124 * fulfill the request, which will look fine, but may be slower than if the 20125 * subclass handles it internally. The default implementation returns false. 20126 * 20127 * @param alpha The alpha (0..255) to apply to the view's drawing 20128 * @return true if the view can draw with the specified alpha. 20129 */ 20130 protected boolean onSetAlpha(int alpha) { 20131 return false; 20132 } 20133 20134 /** 20135 * This is used by the RootView to perform an optimization when 20136 * the view hierarchy contains one or several SurfaceView. 20137 * SurfaceView is always considered transparent, but its children are not, 20138 * therefore all View objects remove themselves from the global transparent 20139 * region (passed as a parameter to this function). 20140 * 20141 * @param region The transparent region for this ViewAncestor (window). 20142 * 20143 * @return Returns true if the effective visibility of the view at this 20144 * point is opaque, regardless of the transparent region; returns false 20145 * if it is possible for underlying windows to be seen behind the view. 20146 * 20147 * {@hide} 20148 */ 20149 public boolean gatherTransparentRegion(Region region) { 20150 final AttachInfo attachInfo = mAttachInfo; 20151 if (region != null && attachInfo != null) { 20152 final int pflags = mPrivateFlags; 20153 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20154 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20155 // remove it from the transparent region. 20156 final int[] location = attachInfo.mTransparentLocation; 20157 getLocationInWindow(location); 20158 region.op(location[0], location[1], location[0] + mRight - mLeft, 20159 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 20160 } else { 20161 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20162 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20163 // the background drawable's non-transparent parts from this transparent region. 20164 applyDrawableToTransparentRegion(mBackground, region); 20165 } 20166 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20167 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20168 // Similarly, we remove the foreground drawable's non-transparent parts. 20169 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20170 } 20171 } 20172 } 20173 return true; 20174 } 20175 20176 /** 20177 * Play a sound effect for this view. 20178 * 20179 * <p>The framework will play sound effects for some built in actions, such as 20180 * clicking, but you may wish to play these effects in your widget, 20181 * for instance, for internal navigation. 20182 * 20183 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20184 * {@link #isSoundEffectsEnabled()} is true. 20185 * 20186 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20187 */ 20188 public void playSoundEffect(int soundConstant) { 20189 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20190 return; 20191 } 20192 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20193 } 20194 20195 /** 20196 * BZZZTT!!1! 20197 * 20198 * <p>Provide haptic feedback to the user for this view. 20199 * 20200 * <p>The framework will provide haptic feedback for some built in actions, 20201 * such as long presses, but you may wish to provide feedback for your 20202 * own widget. 20203 * 20204 * <p>The feedback will only be performed if 20205 * {@link #isHapticFeedbackEnabled()} is true. 20206 * 20207 * @param feedbackConstant One of the constants defined in 20208 * {@link HapticFeedbackConstants} 20209 */ 20210 public boolean performHapticFeedback(int feedbackConstant) { 20211 return performHapticFeedback(feedbackConstant, 0); 20212 } 20213 20214 /** 20215 * BZZZTT!!1! 20216 * 20217 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20218 * 20219 * @param feedbackConstant One of the constants defined in 20220 * {@link HapticFeedbackConstants} 20221 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20222 */ 20223 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20224 if (mAttachInfo == null) { 20225 return false; 20226 } 20227 //noinspection SimplifiableIfStatement 20228 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20229 && !isHapticFeedbackEnabled()) { 20230 return false; 20231 } 20232 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20233 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20234 } 20235 20236 /** 20237 * Request that the visibility of the status bar or other screen/window 20238 * decorations be changed. 20239 * 20240 * <p>This method is used to put the over device UI into temporary modes 20241 * where the user's attention is focused more on the application content, 20242 * by dimming or hiding surrounding system affordances. This is typically 20243 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20244 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20245 * to be placed behind the action bar (and with these flags other system 20246 * affordances) so that smooth transitions between hiding and showing them 20247 * can be done. 20248 * 20249 * <p>Two representative examples of the use of system UI visibility is 20250 * implementing a content browsing application (like a magazine reader) 20251 * and a video playing application. 20252 * 20253 * <p>The first code shows a typical implementation of a View in a content 20254 * browsing application. In this implementation, the application goes 20255 * into a content-oriented mode by hiding the status bar and action bar, 20256 * and putting the navigation elements into lights out mode. The user can 20257 * then interact with content while in this mode. Such an application should 20258 * provide an easy way for the user to toggle out of the mode (such as to 20259 * check information in the status bar or access notifications). In the 20260 * implementation here, this is done simply by tapping on the content. 20261 * 20262 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20263 * content} 20264 * 20265 * <p>This second code sample shows a typical implementation of a View 20266 * in a video playing application. In this situation, while the video is 20267 * playing the application would like to go into a complete full-screen mode, 20268 * to use as much of the display as possible for the video. When in this state 20269 * the user can not interact with the application; the system intercepts 20270 * touching on the screen to pop the UI out of full screen mode. See 20271 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20272 * 20273 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20274 * content} 20275 * 20276 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20277 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20278 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20279 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20280 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20281 */ 20282 public void setSystemUiVisibility(int visibility) { 20283 if (visibility != mSystemUiVisibility) { 20284 mSystemUiVisibility = visibility; 20285 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20286 mParent.recomputeViewAttributes(this); 20287 } 20288 } 20289 } 20290 20291 /** 20292 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20293 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20294 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20295 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20296 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20297 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20298 */ 20299 public int getSystemUiVisibility() { 20300 return mSystemUiVisibility; 20301 } 20302 20303 /** 20304 * Returns the current system UI visibility that is currently set for 20305 * the entire window. This is the combination of the 20306 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20307 * views in the window. 20308 */ 20309 public int getWindowSystemUiVisibility() { 20310 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20311 } 20312 20313 /** 20314 * Override to find out when the window's requested system UI visibility 20315 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20316 * This is different from the callbacks received through 20317 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20318 * in that this is only telling you about the local request of the window, 20319 * not the actual values applied by the system. 20320 */ 20321 public void onWindowSystemUiVisibilityChanged(int visible) { 20322 } 20323 20324 /** 20325 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20326 * the view hierarchy. 20327 */ 20328 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20329 onWindowSystemUiVisibilityChanged(visible); 20330 } 20331 20332 /** 20333 * Set a listener to receive callbacks when the visibility of the system bar changes. 20334 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20335 */ 20336 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20337 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20338 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20339 mParent.recomputeViewAttributes(this); 20340 } 20341 } 20342 20343 /** 20344 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20345 * the view hierarchy. 20346 */ 20347 public void dispatchSystemUiVisibilityChanged(int visibility) { 20348 ListenerInfo li = mListenerInfo; 20349 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20350 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20351 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20352 } 20353 } 20354 20355 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20356 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20357 if (val != mSystemUiVisibility) { 20358 setSystemUiVisibility(val); 20359 return true; 20360 } 20361 return false; 20362 } 20363 20364 /** @hide */ 20365 public void setDisabledSystemUiVisibility(int flags) { 20366 if (mAttachInfo != null) { 20367 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20368 mAttachInfo.mDisabledSystemUiVisibility = flags; 20369 if (mParent != null) { 20370 mParent.recomputeViewAttributes(this); 20371 } 20372 } 20373 } 20374 } 20375 20376 /** 20377 * Creates an image that the system displays during the drag and drop 20378 * operation. This is called a "drag shadow". The default implementation 20379 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20380 * appearance as the given View. The default also positions the center of the drag shadow 20381 * directly under the touch point. If no View is provided (the constructor with no parameters 20382 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20383 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20384 * default is an invisible drag shadow. 20385 * <p> 20386 * You are not required to use the View you provide to the constructor as the basis of the 20387 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20388 * anything you want as the drag shadow. 20389 * </p> 20390 * <p> 20391 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20392 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20393 * size and position of the drag shadow. It uses this data to construct a 20394 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20395 * so that your application can draw the shadow image in the Canvas. 20396 * </p> 20397 * 20398 * <div class="special reference"> 20399 * <h3>Developer Guides</h3> 20400 * <p>For a guide to implementing drag and drop features, read the 20401 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20402 * </div> 20403 */ 20404 public static class DragShadowBuilder { 20405 private final WeakReference<View> mView; 20406 20407 /** 20408 * Constructs a shadow image builder based on a View. By default, the resulting drag 20409 * shadow will have the same appearance and dimensions as the View, with the touch point 20410 * over the center of the View. 20411 * @param view A View. Any View in scope can be used. 20412 */ 20413 public DragShadowBuilder(View view) { 20414 mView = new WeakReference<View>(view); 20415 } 20416 20417 /** 20418 * Construct a shadow builder object with no associated View. This 20419 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20420 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20421 * to supply the drag shadow's dimensions and appearance without 20422 * reference to any View object. If they are not overridden, then the result is an 20423 * invisible drag shadow. 20424 */ 20425 public DragShadowBuilder() { 20426 mView = new WeakReference<View>(null); 20427 } 20428 20429 /** 20430 * Returns the View object that had been passed to the 20431 * {@link #View.DragShadowBuilder(View)} 20432 * constructor. If that View parameter was {@code null} or if the 20433 * {@link #View.DragShadowBuilder()} 20434 * constructor was used to instantiate the builder object, this method will return 20435 * null. 20436 * 20437 * @return The View object associate with this builder object. 20438 */ 20439 @SuppressWarnings({"JavadocReference"}) 20440 final public View getView() { 20441 return mView.get(); 20442 } 20443 20444 /** 20445 * Provides the metrics for the shadow image. These include the dimensions of 20446 * the shadow image, and the point within that shadow that should 20447 * be centered under the touch location while dragging. 20448 * <p> 20449 * The default implementation sets the dimensions of the shadow to be the 20450 * same as the dimensions of the View itself and centers the shadow under 20451 * the touch point. 20452 * </p> 20453 * 20454 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20455 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20456 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20457 * image. 20458 * 20459 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20460 * shadow image that should be underneath the touch point during the drag and drop 20461 * operation. Your application must set {@link android.graphics.Point#x} to the 20462 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20463 */ 20464 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20465 final View view = mView.get(); 20466 if (view != null) { 20467 outShadowSize.set(view.getWidth(), view.getHeight()); 20468 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20469 } else { 20470 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20471 } 20472 } 20473 20474 /** 20475 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20476 * based on the dimensions it received from the 20477 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20478 * 20479 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20480 */ 20481 public void onDrawShadow(Canvas canvas) { 20482 final View view = mView.get(); 20483 if (view != null) { 20484 view.draw(canvas); 20485 } else { 20486 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20487 } 20488 } 20489 } 20490 20491 /** 20492 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20493 * startDragAndDrop()} for newer platform versions. 20494 */ 20495 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20496 Object myLocalState, int flags) { 20497 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20498 } 20499 20500 /** 20501 * Starts a drag and drop operation. When your application calls this method, it passes a 20502 * {@link android.view.View.DragShadowBuilder} object to the system. The 20503 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20504 * to get metrics for the drag shadow, and then calls the object's 20505 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20506 * <p> 20507 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20508 * drag events to all the View objects in your application that are currently visible. It does 20509 * this either by calling the View object's drag listener (an implementation of 20510 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20511 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20512 * Both are passed a {@link android.view.DragEvent} object that has a 20513 * {@link android.view.DragEvent#getAction()} value of 20514 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20515 * </p> 20516 * <p> 20517 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20518 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20519 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20520 * to the View the user selected for dragging. 20521 * </p> 20522 * @param data A {@link android.content.ClipData} object pointing to the data to be 20523 * transferred by the drag and drop operation. 20524 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20525 * drag shadow. 20526 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20527 * drop operation. This Object is put into every DragEvent object sent by the system during the 20528 * current drag. 20529 * <p> 20530 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20531 * to the target Views. For example, it can contain flags that differentiate between a 20532 * a copy operation and a move operation. 20533 * </p> 20534 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 20535 * so the parameter should be set to 0. 20536 * @return {@code true} if the method completes successfully, or 20537 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20538 * do a drag, and so no drag operation is in progress. 20539 */ 20540 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20541 Object myLocalState, int flags) { 20542 if (ViewDebug.DEBUG_DRAG) { 20543 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20544 } 20545 boolean okay = false; 20546 20547 Point shadowSize = new Point(); 20548 Point shadowTouchPoint = new Point(); 20549 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20550 20551 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20552 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20553 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20554 } 20555 20556 if (ViewDebug.DEBUG_DRAG) { 20557 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20558 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20559 } 20560 if (mAttachInfo.mDragSurface != null) { 20561 mAttachInfo.mDragSurface.release(); 20562 } 20563 mAttachInfo.mDragSurface = new Surface(); 20564 try { 20565 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20566 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20567 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20568 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20569 if (mAttachInfo.mDragToken != null) { 20570 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20571 try { 20572 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20573 shadowBuilder.onDrawShadow(canvas); 20574 } finally { 20575 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20576 } 20577 20578 final ViewRootImpl root = getViewRootImpl(); 20579 20580 // Cache the local state object for delivery with DragEvents 20581 root.setLocalDragState(myLocalState); 20582 20583 // repurpose 'shadowSize' for the last touch point 20584 root.getLastTouchPoint(shadowSize); 20585 20586 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20587 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20588 shadowTouchPoint.x, shadowTouchPoint.y, data); 20589 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20590 } 20591 } catch (Exception e) { 20592 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20593 mAttachInfo.mDragSurface.destroy(); 20594 mAttachInfo.mDragSurface = null; 20595 } 20596 20597 return okay; 20598 } 20599 20600 /** 20601 * Cancels an ongoing drag and drop operation. 20602 * <p> 20603 * A {@link android.view.DragEvent} object with 20604 * {@link android.view.DragEvent#getAction()} value of 20605 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20606 * {@link android.view.DragEvent#getResult()} value of {@code false} 20607 * will be sent to every 20608 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20609 * even if they are not currently visible. 20610 * </p> 20611 * <p> 20612 * This method can be called on any View in the same window as the View on which 20613 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20614 * was called. 20615 * </p> 20616 */ 20617 public final void cancelDragAndDrop() { 20618 if (ViewDebug.DEBUG_DRAG) { 20619 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20620 } 20621 if (mAttachInfo.mDragToken != null) { 20622 try { 20623 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20624 } catch (Exception e) { 20625 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20626 } 20627 mAttachInfo.mDragToken = null; 20628 } else { 20629 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20630 } 20631 } 20632 20633 /** 20634 * Updates the drag shadow for the ongoing drag and drop operation. 20635 * 20636 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20637 * new drag shadow. 20638 */ 20639 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20640 if (ViewDebug.DEBUG_DRAG) { 20641 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20642 } 20643 if (mAttachInfo.mDragToken != null) { 20644 try { 20645 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20646 try { 20647 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20648 shadowBuilder.onDrawShadow(canvas); 20649 } finally { 20650 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20651 } 20652 } catch (Exception e) { 20653 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20654 } 20655 } else { 20656 Log.e(VIEW_LOG_TAG, "No active drag"); 20657 } 20658 } 20659 20660 /** 20661 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20662 * between {startX, startY} and the new cursor positon. 20663 * @param startX horizontal coordinate where the move started. 20664 * @param startY vertical coordinate where the move started. 20665 * @return whether moving was started successfully. 20666 * @hide 20667 */ 20668 public final boolean startMovingTask(float startX, float startY) { 20669 if (ViewDebug.DEBUG_POSITIONING) { 20670 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20671 } 20672 try { 20673 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20674 } catch (RemoteException e) { 20675 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20676 } 20677 return false; 20678 } 20679 20680 /** 20681 * Handles drag events sent by the system following a call to 20682 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20683 * startDragAndDrop()}. 20684 *<p> 20685 * When the system calls this method, it passes a 20686 * {@link android.view.DragEvent} object. A call to 20687 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20688 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20689 * operation. 20690 * @param event The {@link android.view.DragEvent} sent by the system. 20691 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20692 * in DragEvent, indicating the type of drag event represented by this object. 20693 * @return {@code true} if the method was successful, otherwise {@code false}. 20694 * <p> 20695 * The method should return {@code true} in response to an action type of 20696 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20697 * operation. 20698 * </p> 20699 * <p> 20700 * The method should also return {@code true} in response to an action type of 20701 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20702 * {@code false} if it didn't. 20703 * </p> 20704 */ 20705 public boolean onDragEvent(DragEvent event) { 20706 return false; 20707 } 20708 20709 /** 20710 * Detects if this View is enabled and has a drag event listener. 20711 * If both are true, then it calls the drag event listener with the 20712 * {@link android.view.DragEvent} it received. If the drag event listener returns 20713 * {@code true}, then dispatchDragEvent() returns {@code true}. 20714 * <p> 20715 * For all other cases, the method calls the 20716 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20717 * method and returns its result. 20718 * </p> 20719 * <p> 20720 * This ensures that a drag event is always consumed, even if the View does not have a drag 20721 * event listener. However, if the View has a listener and the listener returns true, then 20722 * onDragEvent() is not called. 20723 * </p> 20724 */ 20725 public boolean dispatchDragEvent(DragEvent event) { 20726 ListenerInfo li = mListenerInfo; 20727 //noinspection SimplifiableIfStatement 20728 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20729 && li.mOnDragListener.onDrag(this, event)) { 20730 return true; 20731 } 20732 return onDragEvent(event); 20733 } 20734 20735 boolean canAcceptDrag() { 20736 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20737 } 20738 20739 /** 20740 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20741 * it is ever exposed at all. 20742 * @hide 20743 */ 20744 public void onCloseSystemDialogs(String reason) { 20745 } 20746 20747 /** 20748 * Given a Drawable whose bounds have been set to draw into this view, 20749 * update a Region being computed for 20750 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20751 * that any non-transparent parts of the Drawable are removed from the 20752 * given transparent region. 20753 * 20754 * @param dr The Drawable whose transparency is to be applied to the region. 20755 * @param region A Region holding the current transparency information, 20756 * where any parts of the region that are set are considered to be 20757 * transparent. On return, this region will be modified to have the 20758 * transparency information reduced by the corresponding parts of the 20759 * Drawable that are not transparent. 20760 * {@hide} 20761 */ 20762 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20763 if (DBG) { 20764 Log.i("View", "Getting transparent region for: " + this); 20765 } 20766 final Region r = dr.getTransparentRegion(); 20767 final Rect db = dr.getBounds(); 20768 final AttachInfo attachInfo = mAttachInfo; 20769 if (r != null && attachInfo != null) { 20770 final int w = getRight()-getLeft(); 20771 final int h = getBottom()-getTop(); 20772 if (db.left > 0) { 20773 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20774 r.op(0, 0, db.left, h, Region.Op.UNION); 20775 } 20776 if (db.right < w) { 20777 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20778 r.op(db.right, 0, w, h, Region.Op.UNION); 20779 } 20780 if (db.top > 0) { 20781 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20782 r.op(0, 0, w, db.top, Region.Op.UNION); 20783 } 20784 if (db.bottom < h) { 20785 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20786 r.op(0, db.bottom, w, h, Region.Op.UNION); 20787 } 20788 final int[] location = attachInfo.mTransparentLocation; 20789 getLocationInWindow(location); 20790 r.translate(location[0], location[1]); 20791 region.op(r, Region.Op.INTERSECT); 20792 } else { 20793 region.op(db, Region.Op.DIFFERENCE); 20794 } 20795 } 20796 20797 private void checkForLongClick(int delayOffset, float x, float y) { 20798 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20799 mHasPerformedLongPress = false; 20800 20801 if (mPendingCheckForLongPress == null) { 20802 mPendingCheckForLongPress = new CheckForLongPress(); 20803 } 20804 mPendingCheckForLongPress.setAnchor(x, y); 20805 mPendingCheckForLongPress.rememberWindowAttachCount(); 20806 postDelayed(mPendingCheckForLongPress, 20807 ViewConfiguration.getLongPressTimeout() - delayOffset); 20808 } 20809 } 20810 20811 /** 20812 * Inflate a view from an XML resource. This convenience method wraps the {@link 20813 * LayoutInflater} class, which provides a full range of options for view inflation. 20814 * 20815 * @param context The Context object for your activity or application. 20816 * @param resource The resource ID to inflate 20817 * @param root A view group that will be the parent. Used to properly inflate the 20818 * layout_* parameters. 20819 * @see LayoutInflater 20820 */ 20821 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20822 LayoutInflater factory = LayoutInflater.from(context); 20823 return factory.inflate(resource, root); 20824 } 20825 20826 /** 20827 * Scroll the view with standard behavior for scrolling beyond the normal 20828 * content boundaries. Views that call this method should override 20829 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 20830 * results of an over-scroll operation. 20831 * 20832 * Views can use this method to handle any touch or fling-based scrolling. 20833 * 20834 * @param deltaX Change in X in pixels 20835 * @param deltaY Change in Y in pixels 20836 * @param scrollX Current X scroll value in pixels before applying deltaX 20837 * @param scrollY Current Y scroll value in pixels before applying deltaY 20838 * @param scrollRangeX Maximum content scroll range along the X axis 20839 * @param scrollRangeY Maximum content scroll range along the Y axis 20840 * @param maxOverScrollX Number of pixels to overscroll by in either direction 20841 * along the X axis. 20842 * @param maxOverScrollY Number of pixels to overscroll by in either direction 20843 * along the Y axis. 20844 * @param isTouchEvent true if this scroll operation is the result of a touch event. 20845 * @return true if scrolling was clamped to an over-scroll boundary along either 20846 * axis, false otherwise. 20847 */ 20848 @SuppressWarnings({"UnusedParameters"}) 20849 protected boolean overScrollBy(int deltaX, int deltaY, 20850 int scrollX, int scrollY, 20851 int scrollRangeX, int scrollRangeY, 20852 int maxOverScrollX, int maxOverScrollY, 20853 boolean isTouchEvent) { 20854 final int overScrollMode = mOverScrollMode; 20855 final boolean canScrollHorizontal = 20856 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 20857 final boolean canScrollVertical = 20858 computeVerticalScrollRange() > computeVerticalScrollExtent(); 20859 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 20860 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 20861 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 20862 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 20863 20864 int newScrollX = scrollX + deltaX; 20865 if (!overScrollHorizontal) { 20866 maxOverScrollX = 0; 20867 } 20868 20869 int newScrollY = scrollY + deltaY; 20870 if (!overScrollVertical) { 20871 maxOverScrollY = 0; 20872 } 20873 20874 // Clamp values if at the limits and record 20875 final int left = -maxOverScrollX; 20876 final int right = maxOverScrollX + scrollRangeX; 20877 final int top = -maxOverScrollY; 20878 final int bottom = maxOverScrollY + scrollRangeY; 20879 20880 boolean clampedX = false; 20881 if (newScrollX > right) { 20882 newScrollX = right; 20883 clampedX = true; 20884 } else if (newScrollX < left) { 20885 newScrollX = left; 20886 clampedX = true; 20887 } 20888 20889 boolean clampedY = false; 20890 if (newScrollY > bottom) { 20891 newScrollY = bottom; 20892 clampedY = true; 20893 } else if (newScrollY < top) { 20894 newScrollY = top; 20895 clampedY = true; 20896 } 20897 20898 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 20899 20900 return clampedX || clampedY; 20901 } 20902 20903 /** 20904 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 20905 * respond to the results of an over-scroll operation. 20906 * 20907 * @param scrollX New X scroll value in pixels 20908 * @param scrollY New Y scroll value in pixels 20909 * @param clampedX True if scrollX was clamped to an over-scroll boundary 20910 * @param clampedY True if scrollY was clamped to an over-scroll boundary 20911 */ 20912 protected void onOverScrolled(int scrollX, int scrollY, 20913 boolean clampedX, boolean clampedY) { 20914 // Intentionally empty. 20915 } 20916 20917 /** 20918 * Returns the over-scroll mode for this view. The result will be 20919 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20920 * (allow over-scrolling only if the view content is larger than the container), 20921 * or {@link #OVER_SCROLL_NEVER}. 20922 * 20923 * @return This view's over-scroll mode. 20924 */ 20925 public int getOverScrollMode() { 20926 return mOverScrollMode; 20927 } 20928 20929 /** 20930 * Set the over-scroll mode for this view. Valid over-scroll modes are 20931 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20932 * (allow over-scrolling only if the view content is larger than the container), 20933 * or {@link #OVER_SCROLL_NEVER}. 20934 * 20935 * Setting the over-scroll mode of a view will have an effect only if the 20936 * view is capable of scrolling. 20937 * 20938 * @param overScrollMode The new over-scroll mode for this view. 20939 */ 20940 public void setOverScrollMode(int overScrollMode) { 20941 if (overScrollMode != OVER_SCROLL_ALWAYS && 20942 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 20943 overScrollMode != OVER_SCROLL_NEVER) { 20944 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 20945 } 20946 mOverScrollMode = overScrollMode; 20947 } 20948 20949 /** 20950 * Enable or disable nested scrolling for this view. 20951 * 20952 * <p>If this property is set to true the view will be permitted to initiate nested 20953 * scrolling operations with a compatible parent view in the current hierarchy. If this 20954 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 20955 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 20956 * the nested scroll.</p> 20957 * 20958 * @param enabled true to enable nested scrolling, false to disable 20959 * 20960 * @see #isNestedScrollingEnabled() 20961 */ 20962 public void setNestedScrollingEnabled(boolean enabled) { 20963 if (enabled) { 20964 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 20965 } else { 20966 stopNestedScroll(); 20967 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 20968 } 20969 } 20970 20971 /** 20972 * Returns true if nested scrolling is enabled for this view. 20973 * 20974 * <p>If nested scrolling is enabled and this View class implementation supports it, 20975 * this view will act as a nested scrolling child view when applicable, forwarding data 20976 * about the scroll operation in progress to a compatible and cooperating nested scrolling 20977 * parent.</p> 20978 * 20979 * @return true if nested scrolling is enabled 20980 * 20981 * @see #setNestedScrollingEnabled(boolean) 20982 */ 20983 public boolean isNestedScrollingEnabled() { 20984 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 20985 PFLAG3_NESTED_SCROLLING_ENABLED; 20986 } 20987 20988 /** 20989 * Begin a nestable scroll operation along the given axes. 20990 * 20991 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 20992 * 20993 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 20994 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 20995 * In the case of touch scrolling the nested scroll will be terminated automatically in 20996 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 20997 * In the event of programmatic scrolling the caller must explicitly call 20998 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 20999 * 21000 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 21001 * If it returns false the caller may ignore the rest of this contract until the next scroll. 21002 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 21003 * 21004 * <p>At each incremental step of the scroll the caller should invoke 21005 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 21006 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 21007 * parent at least partially consumed the scroll and the caller should adjust the amount it 21008 * scrolls by.</p> 21009 * 21010 * <p>After applying the remainder of the scroll delta the caller should invoke 21011 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 21012 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 21013 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 21014 * </p> 21015 * 21016 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 21017 * {@link #SCROLL_AXIS_VERTICAL}. 21018 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21019 * the current gesture. 21020 * 21021 * @see #stopNestedScroll() 21022 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21023 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21024 */ 21025 public boolean startNestedScroll(int axes) { 21026 if (hasNestedScrollingParent()) { 21027 // Already in progress 21028 return true; 21029 } 21030 if (isNestedScrollingEnabled()) { 21031 ViewParent p = getParent(); 21032 View child = this; 21033 while (p != null) { 21034 try { 21035 if (p.onStartNestedScroll(child, this, axes)) { 21036 mNestedScrollingParent = p; 21037 p.onNestedScrollAccepted(child, this, axes); 21038 return true; 21039 } 21040 } catch (AbstractMethodError e) { 21041 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21042 "method onStartNestedScroll", e); 21043 // Allow the search upward to continue 21044 } 21045 if (p instanceof View) { 21046 child = (View) p; 21047 } 21048 p = p.getParent(); 21049 } 21050 } 21051 return false; 21052 } 21053 21054 /** 21055 * Stop a nested scroll in progress. 21056 * 21057 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21058 * 21059 * @see #startNestedScroll(int) 21060 */ 21061 public void stopNestedScroll() { 21062 if (mNestedScrollingParent != null) { 21063 mNestedScrollingParent.onStopNestedScroll(this); 21064 mNestedScrollingParent = null; 21065 } 21066 } 21067 21068 /** 21069 * Returns true if this view has a nested scrolling parent. 21070 * 21071 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21072 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21073 * 21074 * @return whether this view has a nested scrolling parent 21075 */ 21076 public boolean hasNestedScrollingParent() { 21077 return mNestedScrollingParent != null; 21078 } 21079 21080 /** 21081 * Dispatch one step of a nested scroll in progress. 21082 * 21083 * <p>Implementations of views that support nested scrolling should call this to report 21084 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21085 * is not currently in progress or nested scrolling is not 21086 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21087 * 21088 * <p>Compatible View implementations should also call 21089 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21090 * consuming a component of the scroll event themselves.</p> 21091 * 21092 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21093 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21094 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21095 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21096 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21097 * in local view coordinates of this view from before this operation 21098 * to after it completes. View implementations may use this to adjust 21099 * expected input coordinate tracking. 21100 * @return true if the event was dispatched, false if it could not be dispatched. 21101 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21102 */ 21103 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21104 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21105 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21106 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21107 int startX = 0; 21108 int startY = 0; 21109 if (offsetInWindow != null) { 21110 getLocationInWindow(offsetInWindow); 21111 startX = offsetInWindow[0]; 21112 startY = offsetInWindow[1]; 21113 } 21114 21115 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21116 dxUnconsumed, dyUnconsumed); 21117 21118 if (offsetInWindow != null) { 21119 getLocationInWindow(offsetInWindow); 21120 offsetInWindow[0] -= startX; 21121 offsetInWindow[1] -= startY; 21122 } 21123 return true; 21124 } else if (offsetInWindow != null) { 21125 // No motion, no dispatch. Keep offsetInWindow up to date. 21126 offsetInWindow[0] = 0; 21127 offsetInWindow[1] = 0; 21128 } 21129 } 21130 return false; 21131 } 21132 21133 /** 21134 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21135 * 21136 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21137 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21138 * scrolling operation to consume some or all of the scroll operation before the child view 21139 * consumes it.</p> 21140 * 21141 * @param dx Horizontal scroll distance in pixels 21142 * @param dy Vertical scroll distance in pixels 21143 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21144 * and consumed[1] the consumed dy. 21145 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21146 * in local view coordinates of this view from before this operation 21147 * to after it completes. View implementations may use this to adjust 21148 * expected input coordinate tracking. 21149 * @return true if the parent consumed some or all of the scroll delta 21150 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21151 */ 21152 public boolean dispatchNestedPreScroll(int dx, int dy, 21153 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21154 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21155 if (dx != 0 || dy != 0) { 21156 int startX = 0; 21157 int startY = 0; 21158 if (offsetInWindow != null) { 21159 getLocationInWindow(offsetInWindow); 21160 startX = offsetInWindow[0]; 21161 startY = offsetInWindow[1]; 21162 } 21163 21164 if (consumed == null) { 21165 if (mTempNestedScrollConsumed == null) { 21166 mTempNestedScrollConsumed = new int[2]; 21167 } 21168 consumed = mTempNestedScrollConsumed; 21169 } 21170 consumed[0] = 0; 21171 consumed[1] = 0; 21172 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21173 21174 if (offsetInWindow != null) { 21175 getLocationInWindow(offsetInWindow); 21176 offsetInWindow[0] -= startX; 21177 offsetInWindow[1] -= startY; 21178 } 21179 return consumed[0] != 0 || consumed[1] != 0; 21180 } else if (offsetInWindow != null) { 21181 offsetInWindow[0] = 0; 21182 offsetInWindow[1] = 0; 21183 } 21184 } 21185 return false; 21186 } 21187 21188 /** 21189 * Dispatch a fling to a nested scrolling parent. 21190 * 21191 * <p>This method should be used to indicate that a nested scrolling child has detected 21192 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21193 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21194 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21195 * along a scrollable axis.</p> 21196 * 21197 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21198 * its own content, it can use this method to delegate the fling to its nested scrolling 21199 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21200 * 21201 * @param velocityX Horizontal fling velocity in pixels per second 21202 * @param velocityY Vertical fling velocity in pixels per second 21203 * @param consumed true if the child consumed the fling, false otherwise 21204 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21205 */ 21206 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21207 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21208 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21209 } 21210 return false; 21211 } 21212 21213 /** 21214 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21215 * 21216 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21217 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21218 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21219 * before the child view consumes it. If this method returns <code>true</code>, a nested 21220 * parent view consumed the fling and this view should not scroll as a result.</p> 21221 * 21222 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21223 * the fling at a time. If a parent view consumed the fling this method will return false. 21224 * Custom view implementations should account for this in two ways:</p> 21225 * 21226 * <ul> 21227 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21228 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21229 * position regardless.</li> 21230 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21231 * even to settle back to a valid idle position.</li> 21232 * </ul> 21233 * 21234 * <p>Views should also not offer fling velocities to nested parent views along an axis 21235 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21236 * should not offer a horizontal fling velocity to its parents since scrolling along that 21237 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21238 * 21239 * @param velocityX Horizontal fling velocity in pixels per second 21240 * @param velocityY Vertical fling velocity in pixels per second 21241 * @return true if a nested scrolling parent consumed the fling 21242 */ 21243 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21244 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21245 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21246 } 21247 return false; 21248 } 21249 21250 /** 21251 * Gets a scale factor that determines the distance the view should scroll 21252 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21253 * @return The vertical scroll scale factor. 21254 * @hide 21255 */ 21256 protected float getVerticalScrollFactor() { 21257 if (mVerticalScrollFactor == 0) { 21258 TypedValue outValue = new TypedValue(); 21259 if (!mContext.getTheme().resolveAttribute( 21260 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21261 throw new IllegalStateException( 21262 "Expected theme to define listPreferredItemHeight."); 21263 } 21264 mVerticalScrollFactor = outValue.getDimension( 21265 mContext.getResources().getDisplayMetrics()); 21266 } 21267 return mVerticalScrollFactor; 21268 } 21269 21270 /** 21271 * Gets a scale factor that determines the distance the view should scroll 21272 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21273 * @return The horizontal scroll scale factor. 21274 * @hide 21275 */ 21276 protected float getHorizontalScrollFactor() { 21277 // TODO: Should use something else. 21278 return getVerticalScrollFactor(); 21279 } 21280 21281 /** 21282 * Return the value specifying the text direction or policy that was set with 21283 * {@link #setTextDirection(int)}. 21284 * 21285 * @return the defined text direction. It can be one of: 21286 * 21287 * {@link #TEXT_DIRECTION_INHERIT}, 21288 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21289 * {@link #TEXT_DIRECTION_ANY_RTL}, 21290 * {@link #TEXT_DIRECTION_LTR}, 21291 * {@link #TEXT_DIRECTION_RTL}, 21292 * {@link #TEXT_DIRECTION_LOCALE}, 21293 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21294 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21295 * 21296 * @attr ref android.R.styleable#View_textDirection 21297 * 21298 * @hide 21299 */ 21300 @ViewDebug.ExportedProperty(category = "text", mapping = { 21301 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21302 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21303 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21304 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21305 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21306 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21307 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21308 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21309 }) 21310 public int getRawTextDirection() { 21311 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21312 } 21313 21314 /** 21315 * Set the text direction. 21316 * 21317 * @param textDirection the direction to set. Should be one of: 21318 * 21319 * {@link #TEXT_DIRECTION_INHERIT}, 21320 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21321 * {@link #TEXT_DIRECTION_ANY_RTL}, 21322 * {@link #TEXT_DIRECTION_LTR}, 21323 * {@link #TEXT_DIRECTION_RTL}, 21324 * {@link #TEXT_DIRECTION_LOCALE} 21325 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21326 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21327 * 21328 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21329 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21330 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21331 * 21332 * @attr ref android.R.styleable#View_textDirection 21333 */ 21334 public void setTextDirection(int textDirection) { 21335 if (getRawTextDirection() != textDirection) { 21336 // Reset the current text direction and the resolved one 21337 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21338 resetResolvedTextDirection(); 21339 // Set the new text direction 21340 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21341 // Do resolution 21342 resolveTextDirection(); 21343 // Notify change 21344 onRtlPropertiesChanged(getLayoutDirection()); 21345 // Refresh 21346 requestLayout(); 21347 invalidate(true); 21348 } 21349 } 21350 21351 /** 21352 * Return the resolved text direction. 21353 * 21354 * @return the resolved text direction. Returns one of: 21355 * 21356 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21357 * {@link #TEXT_DIRECTION_ANY_RTL}, 21358 * {@link #TEXT_DIRECTION_LTR}, 21359 * {@link #TEXT_DIRECTION_RTL}, 21360 * {@link #TEXT_DIRECTION_LOCALE}, 21361 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21362 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21363 * 21364 * @attr ref android.R.styleable#View_textDirection 21365 */ 21366 @ViewDebug.ExportedProperty(category = "text", mapping = { 21367 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21368 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21369 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21370 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21371 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21372 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21373 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21374 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21375 }) 21376 public int getTextDirection() { 21377 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21378 } 21379 21380 /** 21381 * Resolve the text direction. 21382 * 21383 * @return true if resolution has been done, false otherwise. 21384 * 21385 * @hide 21386 */ 21387 public boolean resolveTextDirection() { 21388 // Reset any previous text direction resolution 21389 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21390 21391 if (hasRtlSupport()) { 21392 // Set resolved text direction flag depending on text direction flag 21393 final int textDirection = getRawTextDirection(); 21394 switch(textDirection) { 21395 case TEXT_DIRECTION_INHERIT: 21396 if (!canResolveTextDirection()) { 21397 // We cannot do the resolution if there is no parent, so use the default one 21398 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21399 // Resolution will need to happen again later 21400 return false; 21401 } 21402 21403 // Parent has not yet resolved, so we still return the default 21404 try { 21405 if (!mParent.isTextDirectionResolved()) { 21406 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21407 // Resolution will need to happen again later 21408 return false; 21409 } 21410 } catch (AbstractMethodError e) { 21411 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21412 " does not fully implement ViewParent", e); 21413 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21414 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21415 return true; 21416 } 21417 21418 // Set current resolved direction to the same value as the parent's one 21419 int parentResolvedDirection; 21420 try { 21421 parentResolvedDirection = mParent.getTextDirection(); 21422 } catch (AbstractMethodError e) { 21423 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21424 " does not fully implement ViewParent", e); 21425 parentResolvedDirection = TEXT_DIRECTION_LTR; 21426 } 21427 switch (parentResolvedDirection) { 21428 case TEXT_DIRECTION_FIRST_STRONG: 21429 case TEXT_DIRECTION_ANY_RTL: 21430 case TEXT_DIRECTION_LTR: 21431 case TEXT_DIRECTION_RTL: 21432 case TEXT_DIRECTION_LOCALE: 21433 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21434 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21435 mPrivateFlags2 |= 21436 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21437 break; 21438 default: 21439 // Default resolved direction is "first strong" heuristic 21440 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21441 } 21442 break; 21443 case TEXT_DIRECTION_FIRST_STRONG: 21444 case TEXT_DIRECTION_ANY_RTL: 21445 case TEXT_DIRECTION_LTR: 21446 case TEXT_DIRECTION_RTL: 21447 case TEXT_DIRECTION_LOCALE: 21448 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21449 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21450 // Resolved direction is the same as text direction 21451 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21452 break; 21453 default: 21454 // Default resolved direction is "first strong" heuristic 21455 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21456 } 21457 } else { 21458 // Default resolved direction is "first strong" heuristic 21459 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21460 } 21461 21462 // Set to resolved 21463 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21464 return true; 21465 } 21466 21467 /** 21468 * Check if text direction resolution can be done. 21469 * 21470 * @return true if text direction resolution can be done otherwise return false. 21471 */ 21472 public boolean canResolveTextDirection() { 21473 switch (getRawTextDirection()) { 21474 case TEXT_DIRECTION_INHERIT: 21475 if (mParent != null) { 21476 try { 21477 return mParent.canResolveTextDirection(); 21478 } catch (AbstractMethodError e) { 21479 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21480 " does not fully implement ViewParent", e); 21481 } 21482 } 21483 return false; 21484 21485 default: 21486 return true; 21487 } 21488 } 21489 21490 /** 21491 * Reset resolved text direction. Text direction will be resolved during a call to 21492 * {@link #onMeasure(int, int)}. 21493 * 21494 * @hide 21495 */ 21496 public void resetResolvedTextDirection() { 21497 // Reset any previous text direction resolution 21498 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21499 // Set to default value 21500 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21501 } 21502 21503 /** 21504 * @return true if text direction is inherited. 21505 * 21506 * @hide 21507 */ 21508 public boolean isTextDirectionInherited() { 21509 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21510 } 21511 21512 /** 21513 * @return true if text direction is resolved. 21514 */ 21515 public boolean isTextDirectionResolved() { 21516 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21517 } 21518 21519 /** 21520 * Return the value specifying the text alignment or policy that was set with 21521 * {@link #setTextAlignment(int)}. 21522 * 21523 * @return the defined text alignment. It can be one of: 21524 * 21525 * {@link #TEXT_ALIGNMENT_INHERIT}, 21526 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21527 * {@link #TEXT_ALIGNMENT_CENTER}, 21528 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21529 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21530 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21531 * {@link #TEXT_ALIGNMENT_VIEW_END} 21532 * 21533 * @attr ref android.R.styleable#View_textAlignment 21534 * 21535 * @hide 21536 */ 21537 @ViewDebug.ExportedProperty(category = "text", mapping = { 21538 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21539 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21540 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21541 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21542 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21543 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21544 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21545 }) 21546 @TextAlignment 21547 public int getRawTextAlignment() { 21548 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21549 } 21550 21551 /** 21552 * Set the text alignment. 21553 * 21554 * @param textAlignment The text alignment to set. Should be one of 21555 * 21556 * {@link #TEXT_ALIGNMENT_INHERIT}, 21557 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21558 * {@link #TEXT_ALIGNMENT_CENTER}, 21559 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21560 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21561 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21562 * {@link #TEXT_ALIGNMENT_VIEW_END} 21563 * 21564 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21565 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21566 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21567 * 21568 * @attr ref android.R.styleable#View_textAlignment 21569 */ 21570 public void setTextAlignment(@TextAlignment int textAlignment) { 21571 if (textAlignment != getRawTextAlignment()) { 21572 // Reset the current and resolved text alignment 21573 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21574 resetResolvedTextAlignment(); 21575 // Set the new text alignment 21576 mPrivateFlags2 |= 21577 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21578 // Do resolution 21579 resolveTextAlignment(); 21580 // Notify change 21581 onRtlPropertiesChanged(getLayoutDirection()); 21582 // Refresh 21583 requestLayout(); 21584 invalidate(true); 21585 } 21586 } 21587 21588 /** 21589 * Return the resolved text alignment. 21590 * 21591 * @return the resolved text alignment. Returns one of: 21592 * 21593 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21594 * {@link #TEXT_ALIGNMENT_CENTER}, 21595 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21596 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21597 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21598 * {@link #TEXT_ALIGNMENT_VIEW_END} 21599 * 21600 * @attr ref android.R.styleable#View_textAlignment 21601 */ 21602 @ViewDebug.ExportedProperty(category = "text", mapping = { 21603 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21604 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21605 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21606 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21607 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21608 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21609 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21610 }) 21611 @TextAlignment 21612 public int getTextAlignment() { 21613 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21614 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21615 } 21616 21617 /** 21618 * Resolve the text alignment. 21619 * 21620 * @return true if resolution has been done, false otherwise. 21621 * 21622 * @hide 21623 */ 21624 public boolean resolveTextAlignment() { 21625 // Reset any previous text alignment resolution 21626 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21627 21628 if (hasRtlSupport()) { 21629 // Set resolved text alignment flag depending on text alignment flag 21630 final int textAlignment = getRawTextAlignment(); 21631 switch (textAlignment) { 21632 case TEXT_ALIGNMENT_INHERIT: 21633 // Check if we can resolve the text alignment 21634 if (!canResolveTextAlignment()) { 21635 // We cannot do the resolution if there is no parent so use the default 21636 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21637 // Resolution will need to happen again later 21638 return false; 21639 } 21640 21641 // Parent has not yet resolved, so we still return the default 21642 try { 21643 if (!mParent.isTextAlignmentResolved()) { 21644 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21645 // Resolution will need to happen again later 21646 return false; 21647 } 21648 } catch (AbstractMethodError e) { 21649 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21650 " does not fully implement ViewParent", e); 21651 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21652 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21653 return true; 21654 } 21655 21656 int parentResolvedTextAlignment; 21657 try { 21658 parentResolvedTextAlignment = mParent.getTextAlignment(); 21659 } catch (AbstractMethodError e) { 21660 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21661 " does not fully implement ViewParent", e); 21662 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21663 } 21664 switch (parentResolvedTextAlignment) { 21665 case TEXT_ALIGNMENT_GRAVITY: 21666 case TEXT_ALIGNMENT_TEXT_START: 21667 case TEXT_ALIGNMENT_TEXT_END: 21668 case TEXT_ALIGNMENT_CENTER: 21669 case TEXT_ALIGNMENT_VIEW_START: 21670 case TEXT_ALIGNMENT_VIEW_END: 21671 // Resolved text alignment is the same as the parent resolved 21672 // text alignment 21673 mPrivateFlags2 |= 21674 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21675 break; 21676 default: 21677 // Use default resolved text alignment 21678 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21679 } 21680 break; 21681 case TEXT_ALIGNMENT_GRAVITY: 21682 case TEXT_ALIGNMENT_TEXT_START: 21683 case TEXT_ALIGNMENT_TEXT_END: 21684 case TEXT_ALIGNMENT_CENTER: 21685 case TEXT_ALIGNMENT_VIEW_START: 21686 case TEXT_ALIGNMENT_VIEW_END: 21687 // Resolved text alignment is the same as text alignment 21688 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21689 break; 21690 default: 21691 // Use default resolved text alignment 21692 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21693 } 21694 } else { 21695 // Use default resolved text alignment 21696 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21697 } 21698 21699 // Set the resolved 21700 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21701 return true; 21702 } 21703 21704 /** 21705 * Check if text alignment resolution can be done. 21706 * 21707 * @return true if text alignment resolution can be done otherwise return false. 21708 */ 21709 public boolean canResolveTextAlignment() { 21710 switch (getRawTextAlignment()) { 21711 case TEXT_DIRECTION_INHERIT: 21712 if (mParent != null) { 21713 try { 21714 return mParent.canResolveTextAlignment(); 21715 } catch (AbstractMethodError e) { 21716 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21717 " does not fully implement ViewParent", e); 21718 } 21719 } 21720 return false; 21721 21722 default: 21723 return true; 21724 } 21725 } 21726 21727 /** 21728 * Reset resolved text alignment. Text alignment will be resolved during a call to 21729 * {@link #onMeasure(int, int)}. 21730 * 21731 * @hide 21732 */ 21733 public void resetResolvedTextAlignment() { 21734 // Reset any previous text alignment resolution 21735 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21736 // Set to default 21737 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21738 } 21739 21740 /** 21741 * @return true if text alignment is inherited. 21742 * 21743 * @hide 21744 */ 21745 public boolean isTextAlignmentInherited() { 21746 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21747 } 21748 21749 /** 21750 * @return true if text alignment is resolved. 21751 */ 21752 public boolean isTextAlignmentResolved() { 21753 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21754 } 21755 21756 /** 21757 * Generate a value suitable for use in {@link #setId(int)}. 21758 * This value will not collide with ID values generated at build time by aapt for R.id. 21759 * 21760 * @return a generated ID value 21761 */ 21762 public static int generateViewId() { 21763 for (;;) { 21764 final int result = sNextGeneratedId.get(); 21765 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21766 int newValue = result + 1; 21767 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21768 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21769 return result; 21770 } 21771 } 21772 } 21773 21774 /** 21775 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21776 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21777 * a normal View or a ViewGroup with 21778 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21779 * @hide 21780 */ 21781 public void captureTransitioningViews(List<View> transitioningViews) { 21782 if (getVisibility() == View.VISIBLE) { 21783 transitioningViews.add(this); 21784 } 21785 } 21786 21787 /** 21788 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21789 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21790 * @hide 21791 */ 21792 public void findNamedViews(Map<String, View> namedElements) { 21793 if (getVisibility() == VISIBLE || mGhostView != null) { 21794 String transitionName = getTransitionName(); 21795 if (transitionName != null) { 21796 namedElements.put(transitionName, this); 21797 } 21798 } 21799 } 21800 21801 /** 21802 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21803 * The default implementation does not care the location or event types, but some subclasses 21804 * may use it (such as WebViews). 21805 * @param event The MotionEvent from a mouse 21806 * @param x The x position of the event, local to the view 21807 * @param y The y position of the event, local to the view 21808 * @see PointerIcon 21809 */ 21810 public PointerIcon getPointerIcon(MotionEvent event, float x, float y) { 21811 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21812 return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW); 21813 } 21814 return mPointerIcon; 21815 } 21816 21817 /** 21818 * Set the pointer icon for the current view. 21819 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21820 */ 21821 public void setPointerIcon(PointerIcon pointerIcon) { 21822 mPointerIcon = pointerIcon; 21823 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 21824 return; 21825 } 21826 try { 21827 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 21828 } catch (RemoteException e) { 21829 } 21830 } 21831 21832 /** 21833 * Request capturing further mouse events. 21834 * 21835 * When the view captures, the mouse pointer icon will disappear and will not change its 21836 * position. Further mouse events will come to the capturing view, and the mouse movements 21837 * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and 21838 * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not 21839 * be affected. 21840 * 21841 * The capture will be released through {@link #releasePointerCapture()}, or will be lost 21842 * automatically when the view or containing window disappear. 21843 * 21844 * @return true when succeeds. 21845 * @see #releasePointerCapture() 21846 * @see #hasPointerCapture() 21847 */ 21848 public void setPointerCapture() { 21849 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21850 if (viewRootImpl != null) { 21851 viewRootImpl.setPointerCapture(this); 21852 } 21853 } 21854 21855 21856 /** 21857 * Release the current capture of mouse events. 21858 * 21859 * If the view does not have the capture, it will do nothing. 21860 * @see #setPointerCapture() 21861 * @see #hasPointerCapture() 21862 */ 21863 public void releasePointerCapture() { 21864 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21865 if (viewRootImpl != null) { 21866 viewRootImpl.releasePointerCapture(this); 21867 } 21868 } 21869 21870 /** 21871 * Checks the capture status of mouse events. 21872 * 21873 * @return true if the view has the capture. 21874 * @see #setPointerCapture() 21875 * @see #hasPointerCapture() 21876 */ 21877 public boolean hasPointerCapture() { 21878 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21879 return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this); 21880 } 21881 21882 // 21883 // Properties 21884 // 21885 /** 21886 * A Property wrapper around the <code>alpha</code> functionality handled by the 21887 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 21888 */ 21889 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 21890 @Override 21891 public void setValue(View object, float value) { 21892 object.setAlpha(value); 21893 } 21894 21895 @Override 21896 public Float get(View object) { 21897 return object.getAlpha(); 21898 } 21899 }; 21900 21901 /** 21902 * A Property wrapper around the <code>translationX</code> functionality handled by the 21903 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 21904 */ 21905 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 21906 @Override 21907 public void setValue(View object, float value) { 21908 object.setTranslationX(value); 21909 } 21910 21911 @Override 21912 public Float get(View object) { 21913 return object.getTranslationX(); 21914 } 21915 }; 21916 21917 /** 21918 * A Property wrapper around the <code>translationY</code> functionality handled by the 21919 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 21920 */ 21921 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 21922 @Override 21923 public void setValue(View object, float value) { 21924 object.setTranslationY(value); 21925 } 21926 21927 @Override 21928 public Float get(View object) { 21929 return object.getTranslationY(); 21930 } 21931 }; 21932 21933 /** 21934 * A Property wrapper around the <code>translationZ</code> functionality handled by the 21935 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 21936 */ 21937 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 21938 @Override 21939 public void setValue(View object, float value) { 21940 object.setTranslationZ(value); 21941 } 21942 21943 @Override 21944 public Float get(View object) { 21945 return object.getTranslationZ(); 21946 } 21947 }; 21948 21949 /** 21950 * A Property wrapper around the <code>x</code> functionality handled by the 21951 * {@link View#setX(float)} and {@link View#getX()} methods. 21952 */ 21953 public static final Property<View, Float> X = new FloatProperty<View>("x") { 21954 @Override 21955 public void setValue(View object, float value) { 21956 object.setX(value); 21957 } 21958 21959 @Override 21960 public Float get(View object) { 21961 return object.getX(); 21962 } 21963 }; 21964 21965 /** 21966 * A Property wrapper around the <code>y</code> functionality handled by the 21967 * {@link View#setY(float)} and {@link View#getY()} methods. 21968 */ 21969 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 21970 @Override 21971 public void setValue(View object, float value) { 21972 object.setY(value); 21973 } 21974 21975 @Override 21976 public Float get(View object) { 21977 return object.getY(); 21978 } 21979 }; 21980 21981 /** 21982 * A Property wrapper around the <code>z</code> functionality handled by the 21983 * {@link View#setZ(float)} and {@link View#getZ()} methods. 21984 */ 21985 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 21986 @Override 21987 public void setValue(View object, float value) { 21988 object.setZ(value); 21989 } 21990 21991 @Override 21992 public Float get(View object) { 21993 return object.getZ(); 21994 } 21995 }; 21996 21997 /** 21998 * A Property wrapper around the <code>rotation</code> functionality handled by the 21999 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 22000 */ 22001 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 22002 @Override 22003 public void setValue(View object, float value) { 22004 object.setRotation(value); 22005 } 22006 22007 @Override 22008 public Float get(View object) { 22009 return object.getRotation(); 22010 } 22011 }; 22012 22013 /** 22014 * A Property wrapper around the <code>rotationX</code> functionality handled by the 22015 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 22016 */ 22017 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 22018 @Override 22019 public void setValue(View object, float value) { 22020 object.setRotationX(value); 22021 } 22022 22023 @Override 22024 public Float get(View object) { 22025 return object.getRotationX(); 22026 } 22027 }; 22028 22029 /** 22030 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22031 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22032 */ 22033 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22034 @Override 22035 public void setValue(View object, float value) { 22036 object.setRotationY(value); 22037 } 22038 22039 @Override 22040 public Float get(View object) { 22041 return object.getRotationY(); 22042 } 22043 }; 22044 22045 /** 22046 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22047 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22048 */ 22049 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22050 @Override 22051 public void setValue(View object, float value) { 22052 object.setScaleX(value); 22053 } 22054 22055 @Override 22056 public Float get(View object) { 22057 return object.getScaleX(); 22058 } 22059 }; 22060 22061 /** 22062 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22063 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22064 */ 22065 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22066 @Override 22067 public void setValue(View object, float value) { 22068 object.setScaleY(value); 22069 } 22070 22071 @Override 22072 public Float get(View object) { 22073 return object.getScaleY(); 22074 } 22075 }; 22076 22077 /** 22078 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22079 * Each MeasureSpec represents a requirement for either the width or the height. 22080 * A MeasureSpec is comprised of a size and a mode. There are three possible 22081 * modes: 22082 * <dl> 22083 * <dt>UNSPECIFIED</dt> 22084 * <dd> 22085 * The parent has not imposed any constraint on the child. It can be whatever size 22086 * it wants. 22087 * </dd> 22088 * 22089 * <dt>EXACTLY</dt> 22090 * <dd> 22091 * The parent has determined an exact size for the child. The child is going to be 22092 * given those bounds regardless of how big it wants to be. 22093 * </dd> 22094 * 22095 * <dt>AT_MOST</dt> 22096 * <dd> 22097 * The child can be as large as it wants up to the specified size. 22098 * </dd> 22099 * </dl> 22100 * 22101 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22102 * is provided to pack and unpack the <size, mode> tuple into the int. 22103 */ 22104 public static class MeasureSpec { 22105 private static final int MODE_SHIFT = 30; 22106 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22107 22108 /** @hide */ 22109 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22110 @Retention(RetentionPolicy.SOURCE) 22111 public @interface MeasureSpecMode {} 22112 22113 /** 22114 * Measure specification mode: The parent has not imposed any constraint 22115 * on the child. It can be whatever size it wants. 22116 */ 22117 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22118 22119 /** 22120 * Measure specification mode: The parent has determined an exact size 22121 * for the child. The child is going to be given those bounds regardless 22122 * of how big it wants to be. 22123 */ 22124 public static final int EXACTLY = 1 << MODE_SHIFT; 22125 22126 /** 22127 * Measure specification mode: The child can be as large as it wants up 22128 * to the specified size. 22129 */ 22130 public static final int AT_MOST = 2 << MODE_SHIFT; 22131 22132 /** 22133 * Creates a measure specification based on the supplied size and mode. 22134 * 22135 * The mode must always be one of the following: 22136 * <ul> 22137 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22138 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22139 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22140 * </ul> 22141 * 22142 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22143 * implementation was such that the order of arguments did not matter 22144 * and overflow in either value could impact the resulting MeasureSpec. 22145 * {@link android.widget.RelativeLayout} was affected by this bug. 22146 * Apps targeting API levels greater than 17 will get the fixed, more strict 22147 * behavior.</p> 22148 * 22149 * @param size the size of the measure specification 22150 * @param mode the mode of the measure specification 22151 * @return the measure specification based on size and mode 22152 */ 22153 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22154 @MeasureSpecMode int mode) { 22155 if (sUseBrokenMakeMeasureSpec) { 22156 return size + mode; 22157 } else { 22158 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22159 } 22160 } 22161 22162 /** 22163 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22164 * will automatically get a size of 0. Older apps expect this. 22165 * 22166 * @hide internal use only for compatibility with system widgets and older apps 22167 */ 22168 public static int makeSafeMeasureSpec(int size, int mode) { 22169 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22170 return 0; 22171 } 22172 return makeMeasureSpec(size, mode); 22173 } 22174 22175 /** 22176 * Extracts the mode from the supplied measure specification. 22177 * 22178 * @param measureSpec the measure specification to extract the mode from 22179 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22180 * {@link android.view.View.MeasureSpec#AT_MOST} or 22181 * {@link android.view.View.MeasureSpec#EXACTLY} 22182 */ 22183 @MeasureSpecMode 22184 public static int getMode(int measureSpec) { 22185 //noinspection ResourceType 22186 return (measureSpec & MODE_MASK); 22187 } 22188 22189 /** 22190 * Extracts the size from the supplied measure specification. 22191 * 22192 * @param measureSpec the measure specification to extract the size from 22193 * @return the size in pixels defined in the supplied measure specification 22194 */ 22195 public static int getSize(int measureSpec) { 22196 return (measureSpec & ~MODE_MASK); 22197 } 22198 22199 static int adjust(int measureSpec, int delta) { 22200 final int mode = getMode(measureSpec); 22201 int size = getSize(measureSpec); 22202 if (mode == UNSPECIFIED) { 22203 // No need to adjust size for UNSPECIFIED mode. 22204 return makeMeasureSpec(size, UNSPECIFIED); 22205 } 22206 size += delta; 22207 if (size < 0) { 22208 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22209 ") spec: " + toString(measureSpec) + " delta: " + delta); 22210 size = 0; 22211 } 22212 return makeMeasureSpec(size, mode); 22213 } 22214 22215 /** 22216 * Returns a String representation of the specified measure 22217 * specification. 22218 * 22219 * @param measureSpec the measure specification to convert to a String 22220 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22221 */ 22222 public static String toString(int measureSpec) { 22223 int mode = getMode(measureSpec); 22224 int size = getSize(measureSpec); 22225 22226 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22227 22228 if (mode == UNSPECIFIED) 22229 sb.append("UNSPECIFIED "); 22230 else if (mode == EXACTLY) 22231 sb.append("EXACTLY "); 22232 else if (mode == AT_MOST) 22233 sb.append("AT_MOST "); 22234 else 22235 sb.append(mode).append(" "); 22236 22237 sb.append(size); 22238 return sb.toString(); 22239 } 22240 } 22241 22242 private final class CheckForLongPress implements Runnable { 22243 private int mOriginalWindowAttachCount; 22244 private float mX; 22245 private float mY; 22246 22247 @Override 22248 public void run() { 22249 if (isPressed() && (mParent != null) 22250 && mOriginalWindowAttachCount == mWindowAttachCount) { 22251 if (performLongClick(mX, mY)) { 22252 mHasPerformedLongPress = true; 22253 } 22254 } 22255 } 22256 22257 public void setAnchor(float x, float y) { 22258 mX = x; 22259 mY = y; 22260 } 22261 22262 public void rememberWindowAttachCount() { 22263 mOriginalWindowAttachCount = mWindowAttachCount; 22264 } 22265 } 22266 22267 private final class CheckForTap implements Runnable { 22268 public float x; 22269 public float y; 22270 22271 @Override 22272 public void run() { 22273 mPrivateFlags &= ~PFLAG_PREPRESSED; 22274 setPressed(true, x, y); 22275 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22276 } 22277 } 22278 22279 private final class PerformClick implements Runnable { 22280 @Override 22281 public void run() { 22282 performClick(); 22283 } 22284 } 22285 22286 /** 22287 * This method returns a ViewPropertyAnimator object, which can be used to animate 22288 * specific properties on this View. 22289 * 22290 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22291 */ 22292 public ViewPropertyAnimator animate() { 22293 if (mAnimator == null) { 22294 mAnimator = new ViewPropertyAnimator(this); 22295 } 22296 return mAnimator; 22297 } 22298 22299 /** 22300 * Sets the name of the View to be used to identify Views in Transitions. 22301 * Names should be unique in the View hierarchy. 22302 * 22303 * @param transitionName The name of the View to uniquely identify it for Transitions. 22304 */ 22305 public final void setTransitionName(String transitionName) { 22306 mTransitionName = transitionName; 22307 } 22308 22309 /** 22310 * Returns the name of the View to be used to identify Views in Transitions. 22311 * Names should be unique in the View hierarchy. 22312 * 22313 * <p>This returns null if the View has not been given a name.</p> 22314 * 22315 * @return The name used of the View to be used to identify Views in Transitions or null 22316 * if no name has been given. 22317 */ 22318 @ViewDebug.ExportedProperty 22319 public String getTransitionName() { 22320 return mTransitionName; 22321 } 22322 22323 /** 22324 * @hide 22325 */ 22326 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22327 // Do nothing. 22328 } 22329 22330 /** 22331 * Interface definition for a callback to be invoked when a hardware key event is 22332 * dispatched to this view. The callback will be invoked before the key event is 22333 * given to the view. This is only useful for hardware keyboards; a software input 22334 * method has no obligation to trigger this listener. 22335 */ 22336 public interface OnKeyListener { 22337 /** 22338 * Called when a hardware key is dispatched to a view. This allows listeners to 22339 * get a chance to respond before the target view. 22340 * <p>Key presses in software keyboards will generally NOT trigger this method, 22341 * although some may elect to do so in some situations. Do not assume a 22342 * software input method has to be key-based; even if it is, it may use key presses 22343 * in a different way than you expect, so there is no way to reliably catch soft 22344 * input key presses. 22345 * 22346 * @param v The view the key has been dispatched to. 22347 * @param keyCode The code for the physical key that was pressed 22348 * @param event The KeyEvent object containing full information about 22349 * the event. 22350 * @return True if the listener has consumed the event, false otherwise. 22351 */ 22352 boolean onKey(View v, int keyCode, KeyEvent event); 22353 } 22354 22355 /** 22356 * Interface definition for a callback to be invoked when a touch event is 22357 * dispatched to this view. The callback will be invoked before the touch 22358 * event is given to the view. 22359 */ 22360 public interface OnTouchListener { 22361 /** 22362 * Called when a touch event is dispatched to a view. This allows listeners to 22363 * get a chance to respond before the target view. 22364 * 22365 * @param v The view the touch event has been dispatched to. 22366 * @param event The MotionEvent object containing full information about 22367 * the event. 22368 * @return True if the listener has consumed the event, false otherwise. 22369 */ 22370 boolean onTouch(View v, MotionEvent event); 22371 } 22372 22373 /** 22374 * Interface definition for a callback to be invoked when a hover event is 22375 * dispatched to this view. The callback will be invoked before the hover 22376 * event is given to the view. 22377 */ 22378 public interface OnHoverListener { 22379 /** 22380 * Called when a hover event is dispatched to a view. This allows listeners to 22381 * get a chance to respond before the target view. 22382 * 22383 * @param v The view the hover event has been dispatched to. 22384 * @param event The MotionEvent object containing full information about 22385 * the event. 22386 * @return True if the listener has consumed the event, false otherwise. 22387 */ 22388 boolean onHover(View v, MotionEvent event); 22389 } 22390 22391 /** 22392 * Interface definition for a callback to be invoked when a generic motion event is 22393 * dispatched to this view. The callback will be invoked before the generic motion 22394 * event is given to the view. 22395 */ 22396 public interface OnGenericMotionListener { 22397 /** 22398 * Called when a generic motion event is dispatched to a view. This allows listeners to 22399 * get a chance to respond before the target view. 22400 * 22401 * @param v The view the generic motion event has been dispatched to. 22402 * @param event The MotionEvent object containing full information about 22403 * the event. 22404 * @return True if the listener has consumed the event, false otherwise. 22405 */ 22406 boolean onGenericMotion(View v, MotionEvent event); 22407 } 22408 22409 /** 22410 * Interface definition for a callback to be invoked when a view has been clicked and held. 22411 */ 22412 public interface OnLongClickListener { 22413 /** 22414 * Called when a view has been clicked and held. 22415 * 22416 * @param v The view that was clicked and held. 22417 * 22418 * @return true if the callback consumed the long click, false otherwise. 22419 */ 22420 boolean onLongClick(View v); 22421 } 22422 22423 /** 22424 * Interface definition for a callback to be invoked when a drag is being dispatched 22425 * to this view. The callback will be invoked before the hosting view's own 22426 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22427 * onDrag(event) behavior, it should return 'false' from this callback. 22428 * 22429 * <div class="special reference"> 22430 * <h3>Developer Guides</h3> 22431 * <p>For a guide to implementing drag and drop features, read the 22432 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22433 * </div> 22434 */ 22435 public interface OnDragListener { 22436 /** 22437 * Called when a drag event is dispatched to a view. This allows listeners 22438 * to get a chance to override base View behavior. 22439 * 22440 * @param v The View that received the drag event. 22441 * @param event The {@link android.view.DragEvent} object for the drag event. 22442 * @return {@code true} if the drag event was handled successfully, or {@code false} 22443 * if the drag event was not handled. Note that {@code false} will trigger the View 22444 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22445 */ 22446 boolean onDrag(View v, DragEvent event); 22447 } 22448 22449 /** 22450 * Interface definition for a callback to be invoked when the focus state of 22451 * a view changed. 22452 */ 22453 public interface OnFocusChangeListener { 22454 /** 22455 * Called when the focus state of a view has changed. 22456 * 22457 * @param v The view whose state has changed. 22458 * @param hasFocus The new focus state of v. 22459 */ 22460 void onFocusChange(View v, boolean hasFocus); 22461 } 22462 22463 /** 22464 * Interface definition for a callback to be invoked when a view is clicked. 22465 */ 22466 public interface OnClickListener { 22467 /** 22468 * Called when a view has been clicked. 22469 * 22470 * @param v The view that was clicked. 22471 */ 22472 void onClick(View v); 22473 } 22474 22475 /** 22476 * Interface definition for a callback to be invoked when a view is context clicked. 22477 */ 22478 public interface OnContextClickListener { 22479 /** 22480 * Called when a view is context clicked. 22481 * 22482 * @param v The view that has been context clicked. 22483 * @return true if the callback consumed the context click, false otherwise. 22484 */ 22485 boolean onContextClick(View v); 22486 } 22487 22488 /** 22489 * Interface definition for a callback to be invoked when the context menu 22490 * for this view is being built. 22491 */ 22492 public interface OnCreateContextMenuListener { 22493 /** 22494 * Called when the context menu for this view is being built. It is not 22495 * safe to hold onto the menu after this method returns. 22496 * 22497 * @param menu The context menu that is being built 22498 * @param v The view for which the context menu is being built 22499 * @param menuInfo Extra information about the item for which the 22500 * context menu should be shown. This information will vary 22501 * depending on the class of v. 22502 */ 22503 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22504 } 22505 22506 /** 22507 * Interface definition for a callback to be invoked when the status bar changes 22508 * visibility. This reports <strong>global</strong> changes to the system UI 22509 * state, not what the application is requesting. 22510 * 22511 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22512 */ 22513 public interface OnSystemUiVisibilityChangeListener { 22514 /** 22515 * Called when the status bar changes visibility because of a call to 22516 * {@link View#setSystemUiVisibility(int)}. 22517 * 22518 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22519 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22520 * This tells you the <strong>global</strong> state of these UI visibility 22521 * flags, not what your app is currently applying. 22522 */ 22523 public void onSystemUiVisibilityChange(int visibility); 22524 } 22525 22526 /** 22527 * Interface definition for a callback to be invoked when this view is attached 22528 * or detached from its window. 22529 */ 22530 public interface OnAttachStateChangeListener { 22531 /** 22532 * Called when the view is attached to a window. 22533 * @param v The view that was attached 22534 */ 22535 public void onViewAttachedToWindow(View v); 22536 /** 22537 * Called when the view is detached from a window. 22538 * @param v The view that was detached 22539 */ 22540 public void onViewDetachedFromWindow(View v); 22541 } 22542 22543 /** 22544 * Listener for applying window insets on a view in a custom way. 22545 * 22546 * <p>Apps may choose to implement this interface if they want to apply custom policy 22547 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22548 * is set, its 22549 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22550 * method will be called instead of the View's own 22551 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22552 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22553 * the View's normal behavior as part of its own.</p> 22554 */ 22555 public interface OnApplyWindowInsetsListener { 22556 /** 22557 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22558 * on a View, this listener method will be called instead of the view's own 22559 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22560 * 22561 * @param v The view applying window insets 22562 * @param insets The insets to apply 22563 * @return The insets supplied, minus any insets that were consumed 22564 */ 22565 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22566 } 22567 22568 private final class UnsetPressedState implements Runnable { 22569 @Override 22570 public void run() { 22571 setPressed(false); 22572 } 22573 } 22574 22575 /** 22576 * Base class for derived classes that want to save and restore their own 22577 * state in {@link android.view.View#onSaveInstanceState()}. 22578 */ 22579 public static class BaseSavedState extends AbsSavedState { 22580 String mStartActivityRequestWhoSaved; 22581 22582 /** 22583 * Constructor used when reading from a parcel. Reads the state of the superclass. 22584 * 22585 * @param source parcel to read from 22586 */ 22587 public BaseSavedState(Parcel source) { 22588 this(source, null); 22589 } 22590 22591 /** 22592 * Constructor used when reading from a parcel using a given class loader. 22593 * Reads the state of the superclass. 22594 * 22595 * @param source parcel to read from 22596 * @param loader ClassLoader to use for reading 22597 */ 22598 public BaseSavedState(Parcel source, ClassLoader loader) { 22599 super(source, loader); 22600 mStartActivityRequestWhoSaved = source.readString(); 22601 } 22602 22603 /** 22604 * Constructor called by derived classes when creating their SavedState objects 22605 * 22606 * @param superState The state of the superclass of this view 22607 */ 22608 public BaseSavedState(Parcelable superState) { 22609 super(superState); 22610 } 22611 22612 @Override 22613 public void writeToParcel(Parcel out, int flags) { 22614 super.writeToParcel(out, flags); 22615 out.writeString(mStartActivityRequestWhoSaved); 22616 } 22617 22618 public static final Parcelable.Creator<BaseSavedState> CREATOR 22619 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 22620 @Override 22621 public BaseSavedState createFromParcel(Parcel in) { 22622 return new BaseSavedState(in); 22623 } 22624 22625 @Override 22626 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 22627 return new BaseSavedState(in, loader); 22628 } 22629 22630 @Override 22631 public BaseSavedState[] newArray(int size) { 22632 return new BaseSavedState[size]; 22633 } 22634 }; 22635 } 22636 22637 /** 22638 * A set of information given to a view when it is attached to its parent 22639 * window. 22640 */ 22641 final static class AttachInfo { 22642 interface Callbacks { 22643 void playSoundEffect(int effectId); 22644 boolean performHapticFeedback(int effectId, boolean always); 22645 } 22646 22647 /** 22648 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22649 * to a Handler. This class contains the target (View) to invalidate and 22650 * the coordinates of the dirty rectangle. 22651 * 22652 * For performance purposes, this class also implements a pool of up to 22653 * POOL_LIMIT objects that get reused. This reduces memory allocations 22654 * whenever possible. 22655 */ 22656 static class InvalidateInfo { 22657 private static final int POOL_LIMIT = 10; 22658 22659 private static final SynchronizedPool<InvalidateInfo> sPool = 22660 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22661 22662 View target; 22663 22664 int left; 22665 int top; 22666 int right; 22667 int bottom; 22668 22669 public static InvalidateInfo obtain() { 22670 InvalidateInfo instance = sPool.acquire(); 22671 return (instance != null) ? instance : new InvalidateInfo(); 22672 } 22673 22674 public void recycle() { 22675 target = null; 22676 sPool.release(this); 22677 } 22678 } 22679 22680 final IWindowSession mSession; 22681 22682 final IWindow mWindow; 22683 22684 final IBinder mWindowToken; 22685 22686 final Display mDisplay; 22687 22688 final Callbacks mRootCallbacks; 22689 22690 IWindowId mIWindowId; 22691 WindowId mWindowId; 22692 22693 /** 22694 * The top view of the hierarchy. 22695 */ 22696 View mRootView; 22697 22698 IBinder mPanelParentWindowToken; 22699 22700 boolean mHardwareAccelerated; 22701 boolean mHardwareAccelerationRequested; 22702 ThreadedRenderer mHardwareRenderer; 22703 List<RenderNode> mPendingAnimatingRenderNodes; 22704 22705 /** 22706 * The state of the display to which the window is attached, as reported 22707 * by {@link Display#getState()}. Note that the display state constants 22708 * declared by {@link Display} do not exactly line up with the screen state 22709 * constants declared by {@link View} (there are more display states than 22710 * screen states). 22711 */ 22712 int mDisplayState = Display.STATE_UNKNOWN; 22713 22714 /** 22715 * Scale factor used by the compatibility mode 22716 */ 22717 float mApplicationScale; 22718 22719 /** 22720 * Indicates whether the application is in compatibility mode 22721 */ 22722 boolean mScalingRequired; 22723 22724 /** 22725 * Left position of this view's window 22726 */ 22727 int mWindowLeft; 22728 22729 /** 22730 * Top position of this view's window 22731 */ 22732 int mWindowTop; 22733 22734 /** 22735 * Indicates whether views need to use 32-bit drawing caches 22736 */ 22737 boolean mUse32BitDrawingCache; 22738 22739 /** 22740 * For windows that are full-screen but using insets to layout inside 22741 * of the screen areas, these are the current insets to appear inside 22742 * the overscan area of the display. 22743 */ 22744 final Rect mOverscanInsets = new Rect(); 22745 22746 /** 22747 * For windows that are full-screen but using insets to layout inside 22748 * of the screen decorations, these are the current insets for the 22749 * content of the window. 22750 */ 22751 final Rect mContentInsets = new Rect(); 22752 22753 /** 22754 * For windows that are full-screen but using insets to layout inside 22755 * of the screen decorations, these are the current insets for the 22756 * actual visible parts of the window. 22757 */ 22758 final Rect mVisibleInsets = new Rect(); 22759 22760 /** 22761 * For windows that are full-screen but using insets to layout inside 22762 * of the screen decorations, these are the current insets for the 22763 * stable system windows. 22764 */ 22765 final Rect mStableInsets = new Rect(); 22766 22767 /** 22768 * For windows that include areas that are not covered by real surface these are the outsets 22769 * for real surface. 22770 */ 22771 final Rect mOutsets = new Rect(); 22772 22773 /** 22774 * In multi-window we force show the navigation bar. Because we don't want that the surface 22775 * size changes in this mode, we instead have a flag whether the navigation bar size should 22776 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22777 */ 22778 boolean mAlwaysConsumeNavBar; 22779 22780 /** 22781 * The internal insets given by this window. This value is 22782 * supplied by the client (through 22783 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22784 * be given to the window manager when changed to be used in laying 22785 * out windows behind it. 22786 */ 22787 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22788 = new ViewTreeObserver.InternalInsetsInfo(); 22789 22790 /** 22791 * Set to true when mGivenInternalInsets is non-empty. 22792 */ 22793 boolean mHasNonEmptyGivenInternalInsets; 22794 22795 /** 22796 * All views in the window's hierarchy that serve as scroll containers, 22797 * used to determine if the window can be resized or must be panned 22798 * to adjust for a soft input area. 22799 */ 22800 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22801 22802 final KeyEvent.DispatcherState mKeyDispatchState 22803 = new KeyEvent.DispatcherState(); 22804 22805 /** 22806 * Indicates whether the view's window currently has the focus. 22807 */ 22808 boolean mHasWindowFocus; 22809 22810 /** 22811 * The current visibility of the window. 22812 */ 22813 int mWindowVisibility; 22814 22815 /** 22816 * Indicates the time at which drawing started to occur. 22817 */ 22818 long mDrawingTime; 22819 22820 /** 22821 * Indicates whether or not ignoring the DIRTY_MASK flags. 22822 */ 22823 boolean mIgnoreDirtyState; 22824 22825 /** 22826 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22827 * to avoid clearing that flag prematurely. 22828 */ 22829 boolean mSetIgnoreDirtyState = false; 22830 22831 /** 22832 * Indicates whether the view's window is currently in touch mode. 22833 */ 22834 boolean mInTouchMode; 22835 22836 /** 22837 * Indicates whether the view has requested unbuffered input dispatching for the current 22838 * event stream. 22839 */ 22840 boolean mUnbufferedDispatchRequested; 22841 22842 /** 22843 * Indicates that ViewAncestor should trigger a global layout change 22844 * the next time it performs a traversal 22845 */ 22846 boolean mRecomputeGlobalAttributes; 22847 22848 /** 22849 * Always report new attributes at next traversal. 22850 */ 22851 boolean mForceReportNewAttributes; 22852 22853 /** 22854 * Set during a traveral if any views want to keep the screen on. 22855 */ 22856 boolean mKeepScreenOn; 22857 22858 /** 22859 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22860 */ 22861 int mSystemUiVisibility; 22862 22863 /** 22864 * Hack to force certain system UI visibility flags to be cleared. 22865 */ 22866 int mDisabledSystemUiVisibility; 22867 22868 /** 22869 * Last global system UI visibility reported by the window manager. 22870 */ 22871 int mGlobalSystemUiVisibility; 22872 22873 /** 22874 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 22875 * attached. 22876 */ 22877 boolean mHasSystemUiListeners; 22878 22879 /** 22880 * Set if the window has requested to extend into the overscan region 22881 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 22882 */ 22883 boolean mOverscanRequested; 22884 22885 /** 22886 * Set if the visibility of any views has changed. 22887 */ 22888 boolean mViewVisibilityChanged; 22889 22890 /** 22891 * Set to true if a view has been scrolled. 22892 */ 22893 boolean mViewScrollChanged; 22894 22895 /** 22896 * Set to true if high contrast mode enabled 22897 */ 22898 boolean mHighContrastText; 22899 22900 /** 22901 * Set to true if a pointer event is currently being handled. 22902 */ 22903 boolean mHandlingPointerEvent; 22904 22905 /** 22906 * Global to the view hierarchy used as a temporary for dealing with 22907 * x/y points in the transparent region computations. 22908 */ 22909 final int[] mTransparentLocation = new int[2]; 22910 22911 /** 22912 * Global to the view hierarchy used as a temporary for dealing with 22913 * x/y points in the ViewGroup.invalidateChild implementation. 22914 */ 22915 final int[] mInvalidateChildLocation = new int[2]; 22916 22917 /** 22918 * Global to the view hierarchy used as a temporary for dealng with 22919 * computing absolute on-screen location. 22920 */ 22921 final int[] mTmpLocation = new int[2]; 22922 22923 /** 22924 * Global to the view hierarchy used as a temporary for dealing with 22925 * x/y location when view is transformed. 22926 */ 22927 final float[] mTmpTransformLocation = new float[2]; 22928 22929 /** 22930 * The view tree observer used to dispatch global events like 22931 * layout, pre-draw, touch mode change, etc. 22932 */ 22933 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 22934 22935 /** 22936 * A Canvas used by the view hierarchy to perform bitmap caching. 22937 */ 22938 Canvas mCanvas; 22939 22940 /** 22941 * The view root impl. 22942 */ 22943 final ViewRootImpl mViewRootImpl; 22944 22945 /** 22946 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 22947 * handler can be used to pump events in the UI events queue. 22948 */ 22949 final Handler mHandler; 22950 22951 /** 22952 * Temporary for use in computing invalidate rectangles while 22953 * calling up the hierarchy. 22954 */ 22955 final Rect mTmpInvalRect = new Rect(); 22956 22957 /** 22958 * Temporary for use in computing hit areas with transformed views 22959 */ 22960 final RectF mTmpTransformRect = new RectF(); 22961 22962 /** 22963 * Temporary for use in computing hit areas with transformed views 22964 */ 22965 final RectF mTmpTransformRect1 = new RectF(); 22966 22967 /** 22968 * Temporary list of rectanges. 22969 */ 22970 final List<RectF> mTmpRectList = new ArrayList<>(); 22971 22972 /** 22973 * Temporary for use in transforming invalidation rect 22974 */ 22975 final Matrix mTmpMatrix = new Matrix(); 22976 22977 /** 22978 * Temporary for use in transforming invalidation rect 22979 */ 22980 final Transformation mTmpTransformation = new Transformation(); 22981 22982 /** 22983 * Temporary for use in querying outlines from OutlineProviders 22984 */ 22985 final Outline mTmpOutline = new Outline(); 22986 22987 /** 22988 * Temporary list for use in collecting focusable descendents of a view. 22989 */ 22990 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 22991 22992 /** 22993 * The id of the window for accessibility purposes. 22994 */ 22995 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 22996 22997 /** 22998 * Flags related to accessibility processing. 22999 * 23000 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 23001 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 23002 */ 23003 int mAccessibilityFetchFlags; 23004 23005 /** 23006 * The drawable for highlighting accessibility focus. 23007 */ 23008 Drawable mAccessibilityFocusDrawable; 23009 23010 /** 23011 * Show where the margins, bounds and layout bounds are for each view. 23012 */ 23013 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 23014 23015 /** 23016 * Point used to compute visible regions. 23017 */ 23018 final Point mPoint = new Point(); 23019 23020 /** 23021 * Used to track which View originated a requestLayout() call, used when 23022 * requestLayout() is called during layout. 23023 */ 23024 View mViewRequestingLayout; 23025 23026 /** 23027 * Used to track views that need (at least) a partial relayout at their current size 23028 * during the next traversal. 23029 */ 23030 List<View> mPartialLayoutViews = new ArrayList<>(); 23031 23032 /** 23033 * Swapped with mPartialLayoutViews during layout to avoid concurrent 23034 * modification. Lazily assigned during ViewRootImpl layout. 23035 */ 23036 List<View> mEmptyPartialLayoutViews; 23037 23038 /** 23039 * Used to track the identity of the current drag operation. 23040 */ 23041 IBinder mDragToken; 23042 23043 /** 23044 * The drag shadow surface for the current drag operation. 23045 */ 23046 public Surface mDragSurface; 23047 23048 /** 23049 * Creates a new set of attachment information with the specified 23050 * events handler and thread. 23051 * 23052 * @param handler the events handler the view must use 23053 */ 23054 AttachInfo(IWindowSession session, IWindow window, Display display, 23055 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 23056 mSession = session; 23057 mWindow = window; 23058 mWindowToken = window.asBinder(); 23059 mDisplay = display; 23060 mViewRootImpl = viewRootImpl; 23061 mHandler = handler; 23062 mRootCallbacks = effectPlayer; 23063 } 23064 } 23065 23066 /** 23067 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23068 * is supported. This avoids keeping too many unused fields in most 23069 * instances of View.</p> 23070 */ 23071 private static class ScrollabilityCache implements Runnable { 23072 23073 /** 23074 * Scrollbars are not visible 23075 */ 23076 public static final int OFF = 0; 23077 23078 /** 23079 * Scrollbars are visible 23080 */ 23081 public static final int ON = 1; 23082 23083 /** 23084 * Scrollbars are fading away 23085 */ 23086 public static final int FADING = 2; 23087 23088 public boolean fadeScrollBars; 23089 23090 public int fadingEdgeLength; 23091 public int scrollBarDefaultDelayBeforeFade; 23092 public int scrollBarFadeDuration; 23093 23094 public int scrollBarSize; 23095 public ScrollBarDrawable scrollBar; 23096 public float[] interpolatorValues; 23097 public View host; 23098 23099 public final Paint paint; 23100 public final Matrix matrix; 23101 public Shader shader; 23102 23103 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23104 23105 private static final float[] OPAQUE = { 255 }; 23106 private static final float[] TRANSPARENT = { 0.0f }; 23107 23108 /** 23109 * When fading should start. This time moves into the future every time 23110 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23111 */ 23112 public long fadeStartTime; 23113 23114 23115 /** 23116 * The current state of the scrollbars: ON, OFF, or FADING 23117 */ 23118 public int state = OFF; 23119 23120 private int mLastColor; 23121 23122 public final Rect mScrollBarBounds = new Rect(); 23123 23124 public static final int NOT_DRAGGING = 0; 23125 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23126 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23127 public int mScrollBarDraggingState = NOT_DRAGGING; 23128 23129 public float mScrollBarDraggingPos = 0; 23130 23131 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23132 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23133 scrollBarSize = configuration.getScaledScrollBarSize(); 23134 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23135 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23136 23137 paint = new Paint(); 23138 matrix = new Matrix(); 23139 // use use a height of 1, and then wack the matrix each time we 23140 // actually use it. 23141 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23142 paint.setShader(shader); 23143 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23144 23145 this.host = host; 23146 } 23147 23148 public void setFadeColor(int color) { 23149 if (color != mLastColor) { 23150 mLastColor = color; 23151 23152 if (color != 0) { 23153 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23154 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23155 paint.setShader(shader); 23156 // Restore the default transfer mode (src_over) 23157 paint.setXfermode(null); 23158 } else { 23159 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23160 paint.setShader(shader); 23161 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23162 } 23163 } 23164 } 23165 23166 public void run() { 23167 long now = AnimationUtils.currentAnimationTimeMillis(); 23168 if (now >= fadeStartTime) { 23169 23170 // the animation fades the scrollbars out by changing 23171 // the opacity (alpha) from fully opaque to fully 23172 // transparent 23173 int nextFrame = (int) now; 23174 int framesCount = 0; 23175 23176 Interpolator interpolator = scrollBarInterpolator; 23177 23178 // Start opaque 23179 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23180 23181 // End transparent 23182 nextFrame += scrollBarFadeDuration; 23183 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23184 23185 state = FADING; 23186 23187 // Kick off the fade animation 23188 host.invalidate(true); 23189 } 23190 } 23191 } 23192 23193 /** 23194 * Resuable callback for sending 23195 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23196 */ 23197 private class SendViewScrolledAccessibilityEvent implements Runnable { 23198 public volatile boolean mIsPending; 23199 23200 public void run() { 23201 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23202 mIsPending = false; 23203 } 23204 } 23205 23206 /** 23207 * <p> 23208 * This class represents a delegate that can be registered in a {@link View} 23209 * to enhance accessibility support via composition rather via inheritance. 23210 * It is specifically targeted to widget developers that extend basic View 23211 * classes i.e. classes in package android.view, that would like their 23212 * applications to be backwards compatible. 23213 * </p> 23214 * <div class="special reference"> 23215 * <h3>Developer Guides</h3> 23216 * <p>For more information about making applications accessible, read the 23217 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23218 * developer guide.</p> 23219 * </div> 23220 * <p> 23221 * A scenario in which a developer would like to use an accessibility delegate 23222 * is overriding a method introduced in a later API version then the minimal API 23223 * version supported by the application. For example, the method 23224 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23225 * in API version 4 when the accessibility APIs were first introduced. If a 23226 * developer would like his application to run on API version 4 devices (assuming 23227 * all other APIs used by the application are version 4 or lower) and take advantage 23228 * of this method, instead of overriding the method which would break the application's 23229 * backwards compatibility, he can override the corresponding method in this 23230 * delegate and register the delegate in the target View if the API version of 23231 * the system is high enough i.e. the API version is same or higher to the API 23232 * version that introduced 23233 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23234 * </p> 23235 * <p> 23236 * Here is an example implementation: 23237 * </p> 23238 * <code><pre><p> 23239 * if (Build.VERSION.SDK_INT >= 14) { 23240 * // If the API version is equal of higher than the version in 23241 * // which onInitializeAccessibilityNodeInfo was introduced we 23242 * // register a delegate with a customized implementation. 23243 * View view = findViewById(R.id.view_id); 23244 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23245 * public void onInitializeAccessibilityNodeInfo(View host, 23246 * AccessibilityNodeInfo info) { 23247 * // Let the default implementation populate the info. 23248 * super.onInitializeAccessibilityNodeInfo(host, info); 23249 * // Set some other information. 23250 * info.setEnabled(host.isEnabled()); 23251 * } 23252 * }); 23253 * } 23254 * </code></pre></p> 23255 * <p> 23256 * This delegate contains methods that correspond to the accessibility methods 23257 * in View. If a delegate has been specified the implementation in View hands 23258 * off handling to the corresponding method in this delegate. The default 23259 * implementation the delegate methods behaves exactly as the corresponding 23260 * method in View for the case of no accessibility delegate been set. Hence, 23261 * to customize the behavior of a View method, clients can override only the 23262 * corresponding delegate method without altering the behavior of the rest 23263 * accessibility related methods of the host view. 23264 * </p> 23265 * <p> 23266 * <strong>Note:</strong> On platform versions prior to 23267 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23268 * views in the {@code android.widget.*} package are called <i>before</i> 23269 * host methods. This prevents certain properties such as class name from 23270 * being modified by overriding 23271 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23272 * as any changes will be overwritten by the host class. 23273 * <p> 23274 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23275 * methods are called <i>after</i> host methods, which all properties to be 23276 * modified without being overwritten by the host class. 23277 */ 23278 public static class AccessibilityDelegate { 23279 23280 /** 23281 * Sends an accessibility event of the given type. If accessibility is not 23282 * enabled this method has no effect. 23283 * <p> 23284 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23285 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23286 * been set. 23287 * </p> 23288 * 23289 * @param host The View hosting the delegate. 23290 * @param eventType The type of the event to send. 23291 * 23292 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23293 */ 23294 public void sendAccessibilityEvent(View host, int eventType) { 23295 host.sendAccessibilityEventInternal(eventType); 23296 } 23297 23298 /** 23299 * Performs the specified accessibility action on the view. For 23300 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23301 * <p> 23302 * The default implementation behaves as 23303 * {@link View#performAccessibilityAction(int, Bundle) 23304 * View#performAccessibilityAction(int, Bundle)} for the case of 23305 * no accessibility delegate been set. 23306 * </p> 23307 * 23308 * @param action The action to perform. 23309 * @return Whether the action was performed. 23310 * 23311 * @see View#performAccessibilityAction(int, Bundle) 23312 * View#performAccessibilityAction(int, Bundle) 23313 */ 23314 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23315 return host.performAccessibilityActionInternal(action, args); 23316 } 23317 23318 /** 23319 * Sends an accessibility event. This method behaves exactly as 23320 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23321 * empty {@link AccessibilityEvent} and does not perform a check whether 23322 * accessibility is enabled. 23323 * <p> 23324 * The default implementation behaves as 23325 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23326 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23327 * the case of no accessibility delegate been set. 23328 * </p> 23329 * 23330 * @param host The View hosting the delegate. 23331 * @param event The event to send. 23332 * 23333 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23334 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23335 */ 23336 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23337 host.sendAccessibilityEventUncheckedInternal(event); 23338 } 23339 23340 /** 23341 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23342 * to its children for adding their text content to the event. 23343 * <p> 23344 * The default implementation behaves as 23345 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23346 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23347 * the case of no accessibility delegate been set. 23348 * </p> 23349 * 23350 * @param host The View hosting the delegate. 23351 * @param event The event. 23352 * @return True if the event population was completed. 23353 * 23354 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23355 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23356 */ 23357 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23358 return host.dispatchPopulateAccessibilityEventInternal(event); 23359 } 23360 23361 /** 23362 * Gives a chance to the host View to populate the accessibility event with its 23363 * text content. 23364 * <p> 23365 * The default implementation behaves as 23366 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23367 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23368 * the case of no accessibility delegate been set. 23369 * </p> 23370 * 23371 * @param host The View hosting the delegate. 23372 * @param event The accessibility event which to populate. 23373 * 23374 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23375 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23376 */ 23377 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23378 host.onPopulateAccessibilityEventInternal(event); 23379 } 23380 23381 /** 23382 * Initializes an {@link AccessibilityEvent} with information about the 23383 * the host View which is the event source. 23384 * <p> 23385 * The default implementation behaves as 23386 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23387 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23388 * the case of no accessibility delegate been set. 23389 * </p> 23390 * 23391 * @param host The View hosting the delegate. 23392 * @param event The event to initialize. 23393 * 23394 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23395 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23396 */ 23397 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23398 host.onInitializeAccessibilityEventInternal(event); 23399 } 23400 23401 /** 23402 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23403 * <p> 23404 * The default implementation behaves as 23405 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23406 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23407 * the case of no accessibility delegate been set. 23408 * </p> 23409 * 23410 * @param host The View hosting the delegate. 23411 * @param info The instance to initialize. 23412 * 23413 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23414 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23415 */ 23416 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23417 host.onInitializeAccessibilityNodeInfoInternal(info); 23418 } 23419 23420 /** 23421 * Called when a child of the host View has requested sending an 23422 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23423 * to augment the event. 23424 * <p> 23425 * The default implementation behaves as 23426 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23427 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23428 * the case of no accessibility delegate been set. 23429 * </p> 23430 * 23431 * @param host The View hosting the delegate. 23432 * @param child The child which requests sending the event. 23433 * @param event The event to be sent. 23434 * @return True if the event should be sent 23435 * 23436 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23437 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23438 */ 23439 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23440 AccessibilityEvent event) { 23441 return host.onRequestSendAccessibilityEventInternal(child, event); 23442 } 23443 23444 /** 23445 * Gets the provider for managing a virtual view hierarchy rooted at this View 23446 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23447 * that explore the window content. 23448 * <p> 23449 * The default implementation behaves as 23450 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23451 * the case of no accessibility delegate been set. 23452 * </p> 23453 * 23454 * @return The provider. 23455 * 23456 * @see AccessibilityNodeProvider 23457 */ 23458 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23459 return null; 23460 } 23461 23462 /** 23463 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23464 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23465 * This method is responsible for obtaining an accessibility node info from a 23466 * pool of reusable instances and calling 23467 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23468 * view to initialize the former. 23469 * <p> 23470 * <strong>Note:</strong> The client is responsible for recycling the obtained 23471 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23472 * creation. 23473 * </p> 23474 * <p> 23475 * The default implementation behaves as 23476 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23477 * the case of no accessibility delegate been set. 23478 * </p> 23479 * @return A populated {@link AccessibilityNodeInfo}. 23480 * 23481 * @see AccessibilityNodeInfo 23482 * 23483 * @hide 23484 */ 23485 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23486 return host.createAccessibilityNodeInfoInternal(); 23487 } 23488 } 23489 23490 private class MatchIdPredicate implements Predicate<View> { 23491 public int mId; 23492 23493 @Override 23494 public boolean apply(View view) { 23495 return (view.mID == mId); 23496 } 23497 } 23498 23499 private class MatchLabelForPredicate implements Predicate<View> { 23500 private int mLabeledId; 23501 23502 @Override 23503 public boolean apply(View view) { 23504 return (view.mLabelForId == mLabeledId); 23505 } 23506 } 23507 23508 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23509 private int mChangeTypes = 0; 23510 private boolean mPosted; 23511 private boolean mPostedWithDelay; 23512 private long mLastEventTimeMillis; 23513 23514 @Override 23515 public void run() { 23516 mPosted = false; 23517 mPostedWithDelay = false; 23518 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23519 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23520 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23521 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23522 event.setContentChangeTypes(mChangeTypes); 23523 sendAccessibilityEventUnchecked(event); 23524 } 23525 mChangeTypes = 0; 23526 } 23527 23528 public void runOrPost(int changeType) { 23529 mChangeTypes |= changeType; 23530 23531 // If this is a live region or the child of a live region, collect 23532 // all events from this frame and send them on the next frame. 23533 if (inLiveRegion()) { 23534 // If we're already posted with a delay, remove that. 23535 if (mPostedWithDelay) { 23536 removeCallbacks(this); 23537 mPostedWithDelay = false; 23538 } 23539 // Only post if we're not already posted. 23540 if (!mPosted) { 23541 post(this); 23542 mPosted = true; 23543 } 23544 return; 23545 } 23546 23547 if (mPosted) { 23548 return; 23549 } 23550 23551 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23552 final long minEventIntevalMillis = 23553 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23554 if (timeSinceLastMillis >= minEventIntevalMillis) { 23555 removeCallbacks(this); 23556 run(); 23557 } else { 23558 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23559 mPostedWithDelay = true; 23560 } 23561 } 23562 } 23563 23564 private boolean inLiveRegion() { 23565 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23566 return true; 23567 } 23568 23569 ViewParent parent = getParent(); 23570 while (parent instanceof View) { 23571 if (((View) parent).getAccessibilityLiveRegion() 23572 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23573 return true; 23574 } 23575 parent = parent.getParent(); 23576 } 23577 23578 return false; 23579 } 23580 23581 /** 23582 * Dump all private flags in readable format, useful for documentation and 23583 * sanity checking. 23584 */ 23585 private static void dumpFlags() { 23586 final HashMap<String, String> found = Maps.newHashMap(); 23587 try { 23588 for (Field field : View.class.getDeclaredFields()) { 23589 final int modifiers = field.getModifiers(); 23590 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23591 if (field.getType().equals(int.class)) { 23592 final int value = field.getInt(null); 23593 dumpFlag(found, field.getName(), value); 23594 } else if (field.getType().equals(int[].class)) { 23595 final int[] values = (int[]) field.get(null); 23596 for (int i = 0; i < values.length; i++) { 23597 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23598 } 23599 } 23600 } 23601 } 23602 } catch (IllegalAccessException e) { 23603 throw new RuntimeException(e); 23604 } 23605 23606 final ArrayList<String> keys = Lists.newArrayList(); 23607 keys.addAll(found.keySet()); 23608 Collections.sort(keys); 23609 for (String key : keys) { 23610 Log.d(VIEW_LOG_TAG, found.get(key)); 23611 } 23612 } 23613 23614 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23615 // Sort flags by prefix, then by bits, always keeping unique keys 23616 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23617 final int prefix = name.indexOf('_'); 23618 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23619 final String output = bits + " " + name; 23620 found.put(key, output); 23621 } 23622 23623 /** {@hide} */ 23624 public void encode(@NonNull ViewHierarchyEncoder stream) { 23625 stream.beginObject(this); 23626 encodeProperties(stream); 23627 stream.endObject(); 23628 } 23629 23630 /** {@hide} */ 23631 @CallSuper 23632 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23633 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23634 if (resolveId instanceof String) { 23635 stream.addProperty("id", (String) resolveId); 23636 } else { 23637 stream.addProperty("id", mID); 23638 } 23639 23640 stream.addProperty("misc:transformation.alpha", 23641 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23642 stream.addProperty("misc:transitionName", getTransitionName()); 23643 23644 // layout 23645 stream.addProperty("layout:left", mLeft); 23646 stream.addProperty("layout:right", mRight); 23647 stream.addProperty("layout:top", mTop); 23648 stream.addProperty("layout:bottom", mBottom); 23649 stream.addProperty("layout:width", getWidth()); 23650 stream.addProperty("layout:height", getHeight()); 23651 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23652 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23653 stream.addProperty("layout:hasTransientState", hasTransientState()); 23654 stream.addProperty("layout:baseline", getBaseline()); 23655 23656 // layout params 23657 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23658 if (layoutParams != null) { 23659 stream.addPropertyKey("layoutParams"); 23660 layoutParams.encode(stream); 23661 } 23662 23663 // scrolling 23664 stream.addProperty("scrolling:scrollX", mScrollX); 23665 stream.addProperty("scrolling:scrollY", mScrollY); 23666 23667 // padding 23668 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23669 stream.addProperty("padding:paddingRight", mPaddingRight); 23670 stream.addProperty("padding:paddingTop", mPaddingTop); 23671 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23672 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23673 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23674 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23675 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23676 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23677 23678 // measurement 23679 stream.addProperty("measurement:minHeight", mMinHeight); 23680 stream.addProperty("measurement:minWidth", mMinWidth); 23681 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23682 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23683 23684 // drawing 23685 stream.addProperty("drawing:elevation", getElevation()); 23686 stream.addProperty("drawing:translationX", getTranslationX()); 23687 stream.addProperty("drawing:translationY", getTranslationY()); 23688 stream.addProperty("drawing:translationZ", getTranslationZ()); 23689 stream.addProperty("drawing:rotation", getRotation()); 23690 stream.addProperty("drawing:rotationX", getRotationX()); 23691 stream.addProperty("drawing:rotationY", getRotationY()); 23692 stream.addProperty("drawing:scaleX", getScaleX()); 23693 stream.addProperty("drawing:scaleY", getScaleY()); 23694 stream.addProperty("drawing:pivotX", getPivotX()); 23695 stream.addProperty("drawing:pivotY", getPivotY()); 23696 stream.addProperty("drawing:opaque", isOpaque()); 23697 stream.addProperty("drawing:alpha", getAlpha()); 23698 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23699 stream.addProperty("drawing:shadow", hasShadow()); 23700 stream.addProperty("drawing:solidColor", getSolidColor()); 23701 stream.addProperty("drawing:layerType", mLayerType); 23702 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23703 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23704 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23705 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23706 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23707 23708 // focus 23709 stream.addProperty("focus:hasFocus", hasFocus()); 23710 stream.addProperty("focus:isFocused", isFocused()); 23711 stream.addProperty("focus:isFocusable", isFocusable()); 23712 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23713 23714 stream.addProperty("misc:clickable", isClickable()); 23715 stream.addProperty("misc:pressed", isPressed()); 23716 stream.addProperty("misc:selected", isSelected()); 23717 stream.addProperty("misc:touchMode", isInTouchMode()); 23718 stream.addProperty("misc:hovered", isHovered()); 23719 stream.addProperty("misc:activated", isActivated()); 23720 23721 stream.addProperty("misc:visibility", getVisibility()); 23722 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23723 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23724 23725 stream.addProperty("misc:enabled", isEnabled()); 23726 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23727 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23728 23729 // theme attributes 23730 Resources.Theme theme = getContext().getTheme(); 23731 if (theme != null) { 23732 stream.addPropertyKey("theme"); 23733 theme.encode(stream); 23734 } 23735 23736 // view attribute information 23737 int n = mAttributes != null ? mAttributes.length : 0; 23738 stream.addProperty("meta:__attrCount__", n/2); 23739 for (int i = 0; i < n; i += 2) { 23740 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23741 } 23742 23743 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23744 23745 // text 23746 stream.addProperty("text:textDirection", getTextDirection()); 23747 stream.addProperty("text:textAlignment", getTextAlignment()); 23748 23749 // accessibility 23750 CharSequence contentDescription = getContentDescription(); 23751 stream.addProperty("accessibility:contentDescription", 23752 contentDescription == null ? "" : contentDescription.toString()); 23753 stream.addProperty("accessibility:labelFor", getLabelFor()); 23754 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23755 } 23756} 23757