View.java revision 682c24e22811d4ee17ae1cd61bf255c3f7e722b7
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 * Makes navigation bar transparent (but not the status bar). 3075 */ 3076 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3077 3078 /** 3079 * @hide 3080 * 3081 * Makes status bar transparent (but not the navigation bar). 3082 */ 3083 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3084 3085 /** 3086 * @hide 3087 * 3088 * Makes both status bar and navigation bar transparent. 3089 */ 3090 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3091 | STATUS_BAR_TRANSPARENT; 3092 3093 /** 3094 * @hide 3095 */ 3096 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3097 3098 /** 3099 * These are the system UI flags that can be cleared by events outside 3100 * of an application. Currently this is just the ability to tap on the 3101 * screen while hiding the navigation bar to have it return. 3102 * @hide 3103 */ 3104 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3105 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3106 | SYSTEM_UI_FLAG_FULLSCREEN; 3107 3108 /** 3109 * Flags that can impact the layout in relation to system UI. 3110 */ 3111 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3112 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3113 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3114 3115 /** @hide */ 3116 @IntDef(flag = true, 3117 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3118 @Retention(RetentionPolicy.SOURCE) 3119 public @interface FindViewFlags {} 3120 3121 /** 3122 * Find views that render the specified text. 3123 * 3124 * @see #findViewsWithText(ArrayList, CharSequence, int) 3125 */ 3126 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3127 3128 /** 3129 * Find find views that contain the specified content description. 3130 * 3131 * @see #findViewsWithText(ArrayList, CharSequence, int) 3132 */ 3133 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3134 3135 /** 3136 * Find views that contain {@link AccessibilityNodeProvider}. Such 3137 * a View is a root of virtual view hierarchy and may contain the searched 3138 * text. If this flag is set Views with providers are automatically 3139 * added and it is a responsibility of the client to call the APIs of 3140 * the provider to determine whether the virtual tree rooted at this View 3141 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3142 * representing the virtual views with this text. 3143 * 3144 * @see #findViewsWithText(ArrayList, CharSequence, int) 3145 * 3146 * @hide 3147 */ 3148 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3149 3150 /** 3151 * The undefined cursor position. 3152 * 3153 * @hide 3154 */ 3155 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3156 3157 /** 3158 * Indicates that the screen has changed state and is now off. 3159 * 3160 * @see #onScreenStateChanged(int) 3161 */ 3162 public static final int SCREEN_STATE_OFF = 0x0; 3163 3164 /** 3165 * Indicates that the screen has changed state and is now on. 3166 * 3167 * @see #onScreenStateChanged(int) 3168 */ 3169 public static final int SCREEN_STATE_ON = 0x1; 3170 3171 /** 3172 * Indicates no axis of view scrolling. 3173 */ 3174 public static final int SCROLL_AXIS_NONE = 0; 3175 3176 /** 3177 * Indicates scrolling along the horizontal axis. 3178 */ 3179 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3180 3181 /** 3182 * Indicates scrolling along the vertical axis. 3183 */ 3184 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3185 3186 /** 3187 * Controls the over-scroll mode for this view. 3188 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3189 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3190 * and {@link #OVER_SCROLL_NEVER}. 3191 */ 3192 private int mOverScrollMode; 3193 3194 /** 3195 * The parent this view is attached to. 3196 * {@hide} 3197 * 3198 * @see #getParent() 3199 */ 3200 protected ViewParent mParent; 3201 3202 /** 3203 * {@hide} 3204 */ 3205 AttachInfo mAttachInfo; 3206 3207 /** 3208 * {@hide} 3209 */ 3210 @ViewDebug.ExportedProperty(flagMapping = { 3211 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3212 name = "FORCE_LAYOUT"), 3213 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3214 name = "LAYOUT_REQUIRED"), 3215 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3216 name = "DRAWING_CACHE_INVALID", outputIf = false), 3217 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3218 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3219 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3220 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3221 }, formatToHexString = true) 3222 int mPrivateFlags; 3223 int mPrivateFlags2; 3224 int mPrivateFlags3; 3225 3226 /** 3227 * This view's request for the visibility of the status bar. 3228 * @hide 3229 */ 3230 @ViewDebug.ExportedProperty(flagMapping = { 3231 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3232 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3233 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3234 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3235 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3236 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3237 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3238 equals = SYSTEM_UI_FLAG_VISIBLE, 3239 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3240 }, formatToHexString = true) 3241 int mSystemUiVisibility; 3242 3243 /** 3244 * Reference count for transient state. 3245 * @see #setHasTransientState(boolean) 3246 */ 3247 int mTransientStateCount = 0; 3248 3249 /** 3250 * Count of how many windows this view has been attached to. 3251 */ 3252 int mWindowAttachCount; 3253 3254 /** 3255 * The layout parameters associated with this view and used by the parent 3256 * {@link android.view.ViewGroup} to determine how this view should be 3257 * laid out. 3258 * {@hide} 3259 */ 3260 protected ViewGroup.LayoutParams mLayoutParams; 3261 3262 /** 3263 * The view flags hold various views states. 3264 * {@hide} 3265 */ 3266 @ViewDebug.ExportedProperty(formatToHexString = true) 3267 int mViewFlags; 3268 3269 static class TransformationInfo { 3270 /** 3271 * The transform matrix for the View. This transform is calculated internally 3272 * based on the translation, rotation, and scale properties. 3273 * 3274 * Do *not* use this variable directly; instead call getMatrix(), which will 3275 * load the value from the View's RenderNode. 3276 */ 3277 private final Matrix mMatrix = new Matrix(); 3278 3279 /** 3280 * The inverse transform matrix for the View. This transform is calculated 3281 * internally based on the translation, rotation, and scale properties. 3282 * 3283 * Do *not* use this variable directly; instead call getInverseMatrix(), 3284 * which will load the value from the View's RenderNode. 3285 */ 3286 private Matrix mInverseMatrix; 3287 3288 /** 3289 * The opacity of the View. This is a value from 0 to 1, where 0 means 3290 * completely transparent and 1 means completely opaque. 3291 */ 3292 @ViewDebug.ExportedProperty 3293 float mAlpha = 1f; 3294 3295 /** 3296 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3297 * property only used by transitions, which is composited with the other alpha 3298 * values to calculate the final visual alpha value. 3299 */ 3300 float mTransitionAlpha = 1f; 3301 } 3302 3303 TransformationInfo mTransformationInfo; 3304 3305 /** 3306 * Current clip bounds. to which all drawing of this view are constrained. 3307 */ 3308 Rect mClipBounds = null; 3309 3310 private boolean mLastIsOpaque; 3311 3312 /** 3313 * The distance in pixels from the left edge of this view's parent 3314 * to the left edge of this view. 3315 * {@hide} 3316 */ 3317 @ViewDebug.ExportedProperty(category = "layout") 3318 protected int mLeft; 3319 /** 3320 * The distance in pixels from the left edge of this view's parent 3321 * to the right edge of this view. 3322 * {@hide} 3323 */ 3324 @ViewDebug.ExportedProperty(category = "layout") 3325 protected int mRight; 3326 /** 3327 * The distance in pixels from the top edge of this view's parent 3328 * to the top edge of this view. 3329 * {@hide} 3330 */ 3331 @ViewDebug.ExportedProperty(category = "layout") 3332 protected int mTop; 3333 /** 3334 * The distance in pixels from the top edge of this view's parent 3335 * to the bottom edge of this view. 3336 * {@hide} 3337 */ 3338 @ViewDebug.ExportedProperty(category = "layout") 3339 protected int mBottom; 3340 3341 /** 3342 * The offset, in pixels, by which the content of this view is scrolled 3343 * horizontally. 3344 * {@hide} 3345 */ 3346 @ViewDebug.ExportedProperty(category = "scrolling") 3347 protected int mScrollX; 3348 /** 3349 * The offset, in pixels, by which the content of this view is scrolled 3350 * vertically. 3351 * {@hide} 3352 */ 3353 @ViewDebug.ExportedProperty(category = "scrolling") 3354 protected int mScrollY; 3355 3356 /** 3357 * The left padding in pixels, that is the distance in pixels between the 3358 * left edge of this view and the left edge of its content. 3359 * {@hide} 3360 */ 3361 @ViewDebug.ExportedProperty(category = "padding") 3362 protected int mPaddingLeft = 0; 3363 /** 3364 * The right padding in pixels, that is the distance in pixels between the 3365 * right edge of this view and the right edge of its content. 3366 * {@hide} 3367 */ 3368 @ViewDebug.ExportedProperty(category = "padding") 3369 protected int mPaddingRight = 0; 3370 /** 3371 * The top padding in pixels, that is the distance in pixels between the 3372 * top edge of this view and the top edge of its content. 3373 * {@hide} 3374 */ 3375 @ViewDebug.ExportedProperty(category = "padding") 3376 protected int mPaddingTop; 3377 /** 3378 * The bottom padding in pixels, that is the distance in pixels between the 3379 * bottom edge of this view and the bottom edge of its content. 3380 * {@hide} 3381 */ 3382 @ViewDebug.ExportedProperty(category = "padding") 3383 protected int mPaddingBottom; 3384 3385 /** 3386 * The layout insets in pixels, that is the distance in pixels between the 3387 * visible edges of this view its bounds. 3388 */ 3389 private Insets mLayoutInsets; 3390 3391 /** 3392 * Briefly describes the view and is primarily used for accessibility support. 3393 */ 3394 private CharSequence mContentDescription; 3395 3396 /** 3397 * Specifies the id of a view for which this view serves as a label for 3398 * accessibility purposes. 3399 */ 3400 private int mLabelForId = View.NO_ID; 3401 3402 /** 3403 * Predicate for matching labeled view id with its label for 3404 * accessibility purposes. 3405 */ 3406 private MatchLabelForPredicate mMatchLabelForPredicate; 3407 3408 /** 3409 * Specifies a view before which this one is visited in accessibility traversal. 3410 */ 3411 private int mAccessibilityTraversalBeforeId = NO_ID; 3412 3413 /** 3414 * Specifies a view after which this one is visited in accessibility traversal. 3415 */ 3416 private int mAccessibilityTraversalAfterId = NO_ID; 3417 3418 /** 3419 * Predicate for matching a view by its id. 3420 */ 3421 private MatchIdPredicate mMatchIdPredicate; 3422 3423 /** 3424 * Cache the paddingRight set by the user to append to the scrollbar's size. 3425 * 3426 * @hide 3427 */ 3428 @ViewDebug.ExportedProperty(category = "padding") 3429 protected int mUserPaddingRight; 3430 3431 /** 3432 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3433 * 3434 * @hide 3435 */ 3436 @ViewDebug.ExportedProperty(category = "padding") 3437 protected int mUserPaddingBottom; 3438 3439 /** 3440 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3441 * 3442 * @hide 3443 */ 3444 @ViewDebug.ExportedProperty(category = "padding") 3445 protected int mUserPaddingLeft; 3446 3447 /** 3448 * Cache the paddingStart set by the user to append to the scrollbar's size. 3449 * 3450 */ 3451 @ViewDebug.ExportedProperty(category = "padding") 3452 int mUserPaddingStart; 3453 3454 /** 3455 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3456 * 3457 */ 3458 @ViewDebug.ExportedProperty(category = "padding") 3459 int mUserPaddingEnd; 3460 3461 /** 3462 * Cache initial left padding. 3463 * 3464 * @hide 3465 */ 3466 int mUserPaddingLeftInitial; 3467 3468 /** 3469 * Cache initial right padding. 3470 * 3471 * @hide 3472 */ 3473 int mUserPaddingRightInitial; 3474 3475 /** 3476 * Default undefined padding 3477 */ 3478 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3479 3480 /** 3481 * Cache if a left padding has been defined 3482 */ 3483 private boolean mLeftPaddingDefined = false; 3484 3485 /** 3486 * Cache if a right padding has been defined 3487 */ 3488 private boolean mRightPaddingDefined = false; 3489 3490 /** 3491 * @hide 3492 */ 3493 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3494 /** 3495 * @hide 3496 */ 3497 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3498 3499 private LongSparseLongArray mMeasureCache; 3500 3501 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3502 private Drawable mBackground; 3503 private TintInfo mBackgroundTint; 3504 3505 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3506 private ForegroundInfo mForegroundInfo; 3507 3508 private Drawable mScrollIndicatorDrawable; 3509 3510 /** 3511 * RenderNode used for backgrounds. 3512 * <p> 3513 * When non-null and valid, this is expected to contain an up-to-date copy 3514 * of the background drawable. It is cleared on temporary detach, and reset 3515 * on cleanup. 3516 */ 3517 private RenderNode mBackgroundRenderNode; 3518 3519 private int mBackgroundResource; 3520 private boolean mBackgroundSizeChanged; 3521 3522 private String mTransitionName; 3523 3524 static class TintInfo { 3525 ColorStateList mTintList; 3526 PorterDuff.Mode mTintMode; 3527 boolean mHasTintMode; 3528 boolean mHasTintList; 3529 } 3530 3531 private static class ForegroundInfo { 3532 private Drawable mDrawable; 3533 private TintInfo mTintInfo; 3534 private int mGravity = Gravity.FILL; 3535 private boolean mInsidePadding = true; 3536 private boolean mBoundsChanged = true; 3537 private final Rect mSelfBounds = new Rect(); 3538 private final Rect mOverlayBounds = new Rect(); 3539 } 3540 3541 static class ListenerInfo { 3542 /** 3543 * Listener used to dispatch focus change events. 3544 * This field should be made private, so it is hidden from the SDK. 3545 * {@hide} 3546 */ 3547 protected OnFocusChangeListener mOnFocusChangeListener; 3548 3549 /** 3550 * Listeners for layout change events. 3551 */ 3552 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3553 3554 protected OnScrollChangeListener mOnScrollChangeListener; 3555 3556 /** 3557 * Listeners for attach events. 3558 */ 3559 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3560 3561 /** 3562 * Listener used to dispatch click events. 3563 * This field should be made private, so it is hidden from the SDK. 3564 * {@hide} 3565 */ 3566 public OnClickListener mOnClickListener; 3567 3568 /** 3569 * Listener used to dispatch long click events. 3570 * This field should be made private, so it is hidden from the SDK. 3571 * {@hide} 3572 */ 3573 protected OnLongClickListener mOnLongClickListener; 3574 3575 /** 3576 * Listener used to dispatch context click events. This field should be made private, so it 3577 * is hidden from the SDK. 3578 * {@hide} 3579 */ 3580 protected OnContextClickListener mOnContextClickListener; 3581 3582 /** 3583 * Listener used to build the context menu. 3584 * This field should be made private, so it is hidden from the SDK. 3585 * {@hide} 3586 */ 3587 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3588 3589 private OnKeyListener mOnKeyListener; 3590 3591 private OnTouchListener mOnTouchListener; 3592 3593 private OnHoverListener mOnHoverListener; 3594 3595 private OnGenericMotionListener mOnGenericMotionListener; 3596 3597 private OnDragListener mOnDragListener; 3598 3599 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3600 3601 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3602 } 3603 3604 ListenerInfo mListenerInfo; 3605 3606 // Temporary values used to hold (x,y) coordinates when delegating from the 3607 // two-arg performLongClick() method to the legacy no-arg version. 3608 private float mLongClickX = Float.NaN; 3609 private float mLongClickY = Float.NaN; 3610 3611 /** 3612 * The application environment this view lives in. 3613 * This field should be made private, so it is hidden from the SDK. 3614 * {@hide} 3615 */ 3616 @ViewDebug.ExportedProperty(deepExport = true) 3617 protected Context mContext; 3618 3619 private final Resources mResources; 3620 3621 private ScrollabilityCache mScrollCache; 3622 3623 private int[] mDrawableState = null; 3624 3625 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3626 3627 /** 3628 * Animator that automatically runs based on state changes. 3629 */ 3630 private StateListAnimator mStateListAnimator; 3631 3632 /** 3633 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3634 * the user may specify which view to go to next. 3635 */ 3636 private int mNextFocusLeftId = View.NO_ID; 3637 3638 /** 3639 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3640 * the user may specify which view to go to next. 3641 */ 3642 private int mNextFocusRightId = View.NO_ID; 3643 3644 /** 3645 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3646 * the user may specify which view to go to next. 3647 */ 3648 private int mNextFocusUpId = View.NO_ID; 3649 3650 /** 3651 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3652 * the user may specify which view to go to next. 3653 */ 3654 private int mNextFocusDownId = View.NO_ID; 3655 3656 /** 3657 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3658 * the user may specify which view to go to next. 3659 */ 3660 int mNextFocusForwardId = View.NO_ID; 3661 3662 private CheckForLongPress mPendingCheckForLongPress; 3663 private CheckForTap mPendingCheckForTap = null; 3664 private PerformClick mPerformClick; 3665 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3666 3667 private UnsetPressedState mUnsetPressedState; 3668 3669 /** 3670 * Whether the long press's action has been invoked. The tap's action is invoked on the 3671 * up event while a long press is invoked as soon as the long press duration is reached, so 3672 * a long press could be performed before the tap is checked, in which case the tap's action 3673 * should not be invoked. 3674 */ 3675 private boolean mHasPerformedLongPress; 3676 3677 /** 3678 * Whether a context click button is currently pressed down. This is true when the stylus is 3679 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3680 * pressed. This is false once the button is released or if the stylus has been lifted. 3681 */ 3682 private boolean mInContextButtonPress; 3683 3684 /** 3685 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3686 * true after a stylus button press has occured, when the next up event should not be recognized 3687 * as a tap. 3688 */ 3689 private boolean mIgnoreNextUpEvent; 3690 3691 /** 3692 * The minimum height of the view. We'll try our best to have the height 3693 * of this view to at least this amount. 3694 */ 3695 @ViewDebug.ExportedProperty(category = "measurement") 3696 private int mMinHeight; 3697 3698 /** 3699 * The minimum width of the view. We'll try our best to have the width 3700 * of this view to at least this amount. 3701 */ 3702 @ViewDebug.ExportedProperty(category = "measurement") 3703 private int mMinWidth; 3704 3705 /** 3706 * The delegate to handle touch events that are physically in this view 3707 * but should be handled by another view. 3708 */ 3709 private TouchDelegate mTouchDelegate = null; 3710 3711 /** 3712 * Solid color to use as a background when creating the drawing cache. Enables 3713 * the cache to use 16 bit bitmaps instead of 32 bit. 3714 */ 3715 private int mDrawingCacheBackgroundColor = 0; 3716 3717 /** 3718 * Special tree observer used when mAttachInfo is null. 3719 */ 3720 private ViewTreeObserver mFloatingTreeObserver; 3721 3722 /** 3723 * Cache the touch slop from the context that created the view. 3724 */ 3725 private int mTouchSlop; 3726 3727 /** 3728 * Object that handles automatic animation of view properties. 3729 */ 3730 private ViewPropertyAnimator mAnimator = null; 3731 3732 /** 3733 * List of registered FrameMetricsObservers. 3734 */ 3735 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3736 3737 /** 3738 * Flag indicating that a drag can cross window boundaries. When 3739 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3740 * with this flag set, all visible applications will be able to participate 3741 * in the drag operation and receive the dragged content. 3742 * 3743 * If this is the only flag set, then the drag recipient will only have access to text data 3744 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3745 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags. 3746 */ 3747 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3748 3749 /** 3750 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3751 * request read access to the content URI(s) contained in the {@link ClipData} object. 3752 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3753 */ 3754 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3755 3756 /** 3757 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3758 * request write access to the content URI(s) contained in the {@link ClipData} object. 3759 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3760 */ 3761 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3762 3763 /** 3764 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3765 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3766 * reboots until explicitly revoked with 3767 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3768 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3769 */ 3770 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3771 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3772 3773 /** 3774 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3775 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3776 * match against the original granted URI. 3777 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3778 */ 3779 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3780 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3781 3782 /** 3783 * Flag indicating that the drag shadow will be opaque. When 3784 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3785 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3786 */ 3787 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3788 3789 /** 3790 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3791 */ 3792 private float mVerticalScrollFactor; 3793 3794 /** 3795 * Position of the vertical scroll bar. 3796 */ 3797 private int mVerticalScrollbarPosition; 3798 3799 /** 3800 * Position the scroll bar at the default position as determined by the system. 3801 */ 3802 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3803 3804 /** 3805 * Position the scroll bar along the left edge. 3806 */ 3807 public static final int SCROLLBAR_POSITION_LEFT = 1; 3808 3809 /** 3810 * Position the scroll bar along the right edge. 3811 */ 3812 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3813 3814 /** 3815 * Indicates that the view does not have a layer. 3816 * 3817 * @see #getLayerType() 3818 * @see #setLayerType(int, android.graphics.Paint) 3819 * @see #LAYER_TYPE_SOFTWARE 3820 * @see #LAYER_TYPE_HARDWARE 3821 */ 3822 public static final int LAYER_TYPE_NONE = 0; 3823 3824 /** 3825 * <p>Indicates that the view has a software layer. A software layer is backed 3826 * by a bitmap and causes the view to be rendered using Android's software 3827 * rendering pipeline, even if hardware acceleration is enabled.</p> 3828 * 3829 * <p>Software layers have various usages:</p> 3830 * <p>When the application is not using hardware acceleration, a software layer 3831 * is useful to apply a specific color filter and/or blending mode and/or 3832 * translucency to a view and all its children.</p> 3833 * <p>When the application is using hardware acceleration, a software layer 3834 * is useful to render drawing primitives not supported by the hardware 3835 * accelerated pipeline. It can also be used to cache a complex view tree 3836 * into a texture and reduce the complexity of drawing operations. For instance, 3837 * when animating a complex view tree with a translation, a software layer can 3838 * be used to render the view tree only once.</p> 3839 * <p>Software layers should be avoided when the affected view tree updates 3840 * often. Every update will require to re-render the software layer, which can 3841 * potentially be slow (particularly when hardware acceleration is turned on 3842 * since the layer will have to be uploaded into a hardware texture after every 3843 * update.)</p> 3844 * 3845 * @see #getLayerType() 3846 * @see #setLayerType(int, android.graphics.Paint) 3847 * @see #LAYER_TYPE_NONE 3848 * @see #LAYER_TYPE_HARDWARE 3849 */ 3850 public static final int LAYER_TYPE_SOFTWARE = 1; 3851 3852 /** 3853 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3854 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3855 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3856 * rendering pipeline, but only if hardware acceleration is turned on for the 3857 * view hierarchy. When hardware acceleration is turned off, hardware layers 3858 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3859 * 3860 * <p>A hardware layer is useful to apply a specific color filter and/or 3861 * blending mode and/or translucency to a view and all its children.</p> 3862 * <p>A hardware layer can be used to cache a complex view tree into a 3863 * texture and reduce the complexity of drawing operations. For instance, 3864 * when animating a complex view tree with a translation, a hardware layer can 3865 * be used to render the view tree only once.</p> 3866 * <p>A hardware layer can also be used to increase the rendering quality when 3867 * rotation transformations are applied on a view. It can also be used to 3868 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3869 * 3870 * @see #getLayerType() 3871 * @see #setLayerType(int, android.graphics.Paint) 3872 * @see #LAYER_TYPE_NONE 3873 * @see #LAYER_TYPE_SOFTWARE 3874 */ 3875 public static final int LAYER_TYPE_HARDWARE = 2; 3876 3877 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3878 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3879 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3880 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3881 }) 3882 int mLayerType = LAYER_TYPE_NONE; 3883 Paint mLayerPaint; 3884 3885 /** 3886 * Set to true when drawing cache is enabled and cannot be created. 3887 * 3888 * @hide 3889 */ 3890 public boolean mCachingFailed; 3891 private Bitmap mDrawingCache; 3892 private Bitmap mUnscaledDrawingCache; 3893 3894 /** 3895 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3896 * <p> 3897 * When non-null and valid, this is expected to contain an up-to-date copy 3898 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3899 * cleanup. 3900 */ 3901 final RenderNode mRenderNode; 3902 private Runnable mRenderNodeDetachedCallback; 3903 3904 /** 3905 * Set to true when the view is sending hover accessibility events because it 3906 * is the innermost hovered view. 3907 */ 3908 private boolean mSendingHoverAccessibilityEvents; 3909 3910 /** 3911 * Delegate for injecting accessibility functionality. 3912 */ 3913 AccessibilityDelegate mAccessibilityDelegate; 3914 3915 /** 3916 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3917 * and add/remove objects to/from the overlay directly through the Overlay methods. 3918 */ 3919 ViewOverlay mOverlay; 3920 3921 /** 3922 * The currently active parent view for receiving delegated nested scrolling events. 3923 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3924 * by {@link #stopNestedScroll()} at the same point where we clear 3925 * requestDisallowInterceptTouchEvent. 3926 */ 3927 private ViewParent mNestedScrollingParent; 3928 3929 /** 3930 * Consistency verifier for debugging purposes. 3931 * @hide 3932 */ 3933 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3934 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3935 new InputEventConsistencyVerifier(this, 0) : null; 3936 3937 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3938 3939 private int[] mTempNestedScrollConsumed; 3940 3941 /** 3942 * An overlay is going to draw this View instead of being drawn as part of this 3943 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3944 * when this view is invalidated. 3945 */ 3946 GhostView mGhostView; 3947 3948 /** 3949 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3950 * @hide 3951 */ 3952 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3953 public String[] mAttributes; 3954 3955 /** 3956 * Maps a Resource id to its name. 3957 */ 3958 private static SparseArray<String> mAttributeMap; 3959 3960 /** 3961 * Queue of pending runnables. Used to postpone calls to post() until this 3962 * view is attached and has a handler. 3963 */ 3964 private HandlerActionQueue mRunQueue; 3965 3966 /** 3967 * The pointer icon when the mouse hovers on this view. The default is null. 3968 */ 3969 private PointerIcon mPointerIcon; 3970 3971 /** 3972 * @hide 3973 */ 3974 String mStartActivityRequestWho; 3975 3976 /** 3977 * Simple constructor to use when creating a view from code. 3978 * 3979 * @param context The Context the view is running in, through which it can 3980 * access the current theme, resources, etc. 3981 */ 3982 public View(Context context) { 3983 mContext = context; 3984 mResources = context != null ? context.getResources() : null; 3985 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3986 // Set some flags defaults 3987 mPrivateFlags2 = 3988 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3989 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3990 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3991 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3992 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3993 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3994 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3995 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3996 mUserPaddingStart = UNDEFINED_PADDING; 3997 mUserPaddingEnd = UNDEFINED_PADDING; 3998 mRenderNode = RenderNode.create(getClass().getName(), this); 3999 4000 if (!sCompatibilityDone && context != null) { 4001 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4002 4003 // Older apps may need this compatibility hack for measurement. 4004 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 4005 4006 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4007 // of whether a layout was requested on that View. 4008 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 4009 4010 Canvas.sCompatibilityRestore = targetSdkVersion < M; 4011 4012 // In M and newer, our widgets can pass a "hint" value in the size 4013 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4014 // know what the expected parent size is going to be, so e.g. list items can size 4015 // themselves at 1/3 the size of their container. It breaks older apps though, 4016 // specifically apps that use some popular open source libraries. 4017 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 4018 4019 // Old versions of the platform would give different results from 4020 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4021 // modes, so we always need to run an additional EXACTLY pass. 4022 sAlwaysRemeasureExactly = targetSdkVersion <= M; 4023 4024 // Prior to N, layout params could change without requiring a 4025 // subsequent call to setLayoutParams() and they would usually 4026 // work. Partial layout breaks this assumption. 4027 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4028 4029 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4030 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4031 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4032 4033 sCompatibilityDone = true; 4034 } 4035 } 4036 4037 /** 4038 * Constructor that is called when inflating a view from XML. This is called 4039 * when a view is being constructed from an XML file, supplying attributes 4040 * that were specified in the XML file. This version uses a default style of 4041 * 0, so the only attribute values applied are those in the Context's Theme 4042 * and the given AttributeSet. 4043 * 4044 * <p> 4045 * The method onFinishInflate() will be called after all children have been 4046 * added. 4047 * 4048 * @param context The Context the view is running in, through which it can 4049 * access the current theme, resources, etc. 4050 * @param attrs The attributes of the XML tag that is inflating the view. 4051 * @see #View(Context, AttributeSet, int) 4052 */ 4053 public View(Context context, @Nullable AttributeSet attrs) { 4054 this(context, attrs, 0); 4055 } 4056 4057 /** 4058 * Perform inflation from XML and apply a class-specific base style from a 4059 * theme attribute. This constructor of View allows subclasses to use their 4060 * own base style when they are inflating. For example, a Button class's 4061 * constructor would call this version of the super class constructor and 4062 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4063 * allows the theme's button style to modify all of the base view attributes 4064 * (in particular its background) as well as the Button class's attributes. 4065 * 4066 * @param context The Context the view is running in, through which it can 4067 * access the current theme, resources, etc. 4068 * @param attrs The attributes of the XML tag that is inflating the view. 4069 * @param defStyleAttr An attribute in the current theme that contains a 4070 * reference to a style resource that supplies default values for 4071 * the view. Can be 0 to not look for defaults. 4072 * @see #View(Context, AttributeSet) 4073 */ 4074 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4075 this(context, attrs, defStyleAttr, 0); 4076 } 4077 4078 /** 4079 * Perform inflation from XML and apply a class-specific base style from a 4080 * theme attribute or style resource. This constructor of View allows 4081 * subclasses to use their own base style when they are inflating. 4082 * <p> 4083 * When determining the final value of a particular attribute, there are 4084 * four inputs that come into play: 4085 * <ol> 4086 * <li>Any attribute values in the given AttributeSet. 4087 * <li>The style resource specified in the AttributeSet (named "style"). 4088 * <li>The default style specified by <var>defStyleAttr</var>. 4089 * <li>The default style specified by <var>defStyleRes</var>. 4090 * <li>The base values in this theme. 4091 * </ol> 4092 * <p> 4093 * Each of these inputs is considered in-order, with the first listed taking 4094 * precedence over the following ones. In other words, if in the 4095 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4096 * , then the button's text will <em>always</em> be black, regardless of 4097 * what is specified in any of the styles. 4098 * 4099 * @param context The Context the view is running in, through which it can 4100 * access the current theme, resources, etc. 4101 * @param attrs The attributes of the XML tag that is inflating the view. 4102 * @param defStyleAttr An attribute in the current theme that contains a 4103 * reference to a style resource that supplies default values for 4104 * the view. Can be 0 to not look for defaults. 4105 * @param defStyleRes A resource identifier of a style resource that 4106 * supplies default values for the view, used only if 4107 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4108 * to not look for defaults. 4109 * @see #View(Context, AttributeSet, int) 4110 */ 4111 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4112 this(context); 4113 4114 final TypedArray a = context.obtainStyledAttributes( 4115 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4116 4117 if (mDebugViewAttributes) { 4118 saveAttributeData(attrs, a); 4119 } 4120 4121 Drawable background = null; 4122 4123 int leftPadding = -1; 4124 int topPadding = -1; 4125 int rightPadding = -1; 4126 int bottomPadding = -1; 4127 int startPadding = UNDEFINED_PADDING; 4128 int endPadding = UNDEFINED_PADDING; 4129 4130 int padding = -1; 4131 4132 int viewFlagValues = 0; 4133 int viewFlagMasks = 0; 4134 4135 boolean setScrollContainer = false; 4136 4137 int x = 0; 4138 int y = 0; 4139 4140 float tx = 0; 4141 float ty = 0; 4142 float tz = 0; 4143 float elevation = 0; 4144 float rotation = 0; 4145 float rotationX = 0; 4146 float rotationY = 0; 4147 float sx = 1f; 4148 float sy = 1f; 4149 boolean transformSet = false; 4150 4151 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4152 int overScrollMode = mOverScrollMode; 4153 boolean initializeScrollbars = false; 4154 boolean initializeScrollIndicators = false; 4155 4156 boolean startPaddingDefined = false; 4157 boolean endPaddingDefined = false; 4158 boolean leftPaddingDefined = false; 4159 boolean rightPaddingDefined = false; 4160 4161 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4162 4163 final int N = a.getIndexCount(); 4164 for (int i = 0; i < N; i++) { 4165 int attr = a.getIndex(i); 4166 switch (attr) { 4167 case com.android.internal.R.styleable.View_background: 4168 background = a.getDrawable(attr); 4169 break; 4170 case com.android.internal.R.styleable.View_padding: 4171 padding = a.getDimensionPixelSize(attr, -1); 4172 mUserPaddingLeftInitial = padding; 4173 mUserPaddingRightInitial = padding; 4174 leftPaddingDefined = true; 4175 rightPaddingDefined = true; 4176 break; 4177 case com.android.internal.R.styleable.View_paddingLeft: 4178 leftPadding = a.getDimensionPixelSize(attr, -1); 4179 mUserPaddingLeftInitial = leftPadding; 4180 leftPaddingDefined = true; 4181 break; 4182 case com.android.internal.R.styleable.View_paddingTop: 4183 topPadding = a.getDimensionPixelSize(attr, -1); 4184 break; 4185 case com.android.internal.R.styleable.View_paddingRight: 4186 rightPadding = a.getDimensionPixelSize(attr, -1); 4187 mUserPaddingRightInitial = rightPadding; 4188 rightPaddingDefined = true; 4189 break; 4190 case com.android.internal.R.styleable.View_paddingBottom: 4191 bottomPadding = a.getDimensionPixelSize(attr, -1); 4192 break; 4193 case com.android.internal.R.styleable.View_paddingStart: 4194 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4195 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4196 break; 4197 case com.android.internal.R.styleable.View_paddingEnd: 4198 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4199 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4200 break; 4201 case com.android.internal.R.styleable.View_scrollX: 4202 x = a.getDimensionPixelOffset(attr, 0); 4203 break; 4204 case com.android.internal.R.styleable.View_scrollY: 4205 y = a.getDimensionPixelOffset(attr, 0); 4206 break; 4207 case com.android.internal.R.styleable.View_alpha: 4208 setAlpha(a.getFloat(attr, 1f)); 4209 break; 4210 case com.android.internal.R.styleable.View_transformPivotX: 4211 setPivotX(a.getDimensionPixelOffset(attr, 0)); 4212 break; 4213 case com.android.internal.R.styleable.View_transformPivotY: 4214 setPivotY(a.getDimensionPixelOffset(attr, 0)); 4215 break; 4216 case com.android.internal.R.styleable.View_translationX: 4217 tx = a.getDimensionPixelOffset(attr, 0); 4218 transformSet = true; 4219 break; 4220 case com.android.internal.R.styleable.View_translationY: 4221 ty = a.getDimensionPixelOffset(attr, 0); 4222 transformSet = true; 4223 break; 4224 case com.android.internal.R.styleable.View_translationZ: 4225 tz = a.getDimensionPixelOffset(attr, 0); 4226 transformSet = true; 4227 break; 4228 case com.android.internal.R.styleable.View_elevation: 4229 elevation = a.getDimensionPixelOffset(attr, 0); 4230 transformSet = true; 4231 break; 4232 case com.android.internal.R.styleable.View_rotation: 4233 rotation = a.getFloat(attr, 0); 4234 transformSet = true; 4235 break; 4236 case com.android.internal.R.styleable.View_rotationX: 4237 rotationX = a.getFloat(attr, 0); 4238 transformSet = true; 4239 break; 4240 case com.android.internal.R.styleable.View_rotationY: 4241 rotationY = a.getFloat(attr, 0); 4242 transformSet = true; 4243 break; 4244 case com.android.internal.R.styleable.View_scaleX: 4245 sx = a.getFloat(attr, 1f); 4246 transformSet = true; 4247 break; 4248 case com.android.internal.R.styleable.View_scaleY: 4249 sy = a.getFloat(attr, 1f); 4250 transformSet = true; 4251 break; 4252 case com.android.internal.R.styleable.View_id: 4253 mID = a.getResourceId(attr, NO_ID); 4254 break; 4255 case com.android.internal.R.styleable.View_tag: 4256 mTag = a.getText(attr); 4257 break; 4258 case com.android.internal.R.styleable.View_fitsSystemWindows: 4259 if (a.getBoolean(attr, false)) { 4260 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4261 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4262 } 4263 break; 4264 case com.android.internal.R.styleable.View_focusable: 4265 if (a.getBoolean(attr, false)) { 4266 viewFlagValues |= FOCUSABLE; 4267 viewFlagMasks |= FOCUSABLE_MASK; 4268 } 4269 break; 4270 case com.android.internal.R.styleable.View_focusableInTouchMode: 4271 if (a.getBoolean(attr, false)) { 4272 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4273 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4274 } 4275 break; 4276 case com.android.internal.R.styleable.View_clickable: 4277 if (a.getBoolean(attr, false)) { 4278 viewFlagValues |= CLICKABLE; 4279 viewFlagMasks |= CLICKABLE; 4280 } 4281 break; 4282 case com.android.internal.R.styleable.View_longClickable: 4283 if (a.getBoolean(attr, false)) { 4284 viewFlagValues |= LONG_CLICKABLE; 4285 viewFlagMasks |= LONG_CLICKABLE; 4286 } 4287 break; 4288 case com.android.internal.R.styleable.View_contextClickable: 4289 if (a.getBoolean(attr, false)) { 4290 viewFlagValues |= CONTEXT_CLICKABLE; 4291 viewFlagMasks |= CONTEXT_CLICKABLE; 4292 } 4293 break; 4294 case com.android.internal.R.styleable.View_saveEnabled: 4295 if (!a.getBoolean(attr, true)) { 4296 viewFlagValues |= SAVE_DISABLED; 4297 viewFlagMasks |= SAVE_DISABLED_MASK; 4298 } 4299 break; 4300 case com.android.internal.R.styleable.View_duplicateParentState: 4301 if (a.getBoolean(attr, false)) { 4302 viewFlagValues |= DUPLICATE_PARENT_STATE; 4303 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4304 } 4305 break; 4306 case com.android.internal.R.styleable.View_visibility: 4307 final int visibility = a.getInt(attr, 0); 4308 if (visibility != 0) { 4309 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4310 viewFlagMasks |= VISIBILITY_MASK; 4311 } 4312 break; 4313 case com.android.internal.R.styleable.View_layoutDirection: 4314 // Clear any layout direction flags (included resolved bits) already set 4315 mPrivateFlags2 &= 4316 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4317 // Set the layout direction flags depending on the value of the attribute 4318 final int layoutDirection = a.getInt(attr, -1); 4319 final int value = (layoutDirection != -1) ? 4320 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4321 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4322 break; 4323 case com.android.internal.R.styleable.View_drawingCacheQuality: 4324 final int cacheQuality = a.getInt(attr, 0); 4325 if (cacheQuality != 0) { 4326 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4327 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4328 } 4329 break; 4330 case com.android.internal.R.styleable.View_contentDescription: 4331 setContentDescription(a.getString(attr)); 4332 break; 4333 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4334 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4335 break; 4336 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4337 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4338 break; 4339 case com.android.internal.R.styleable.View_labelFor: 4340 setLabelFor(a.getResourceId(attr, NO_ID)); 4341 break; 4342 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4343 if (!a.getBoolean(attr, true)) { 4344 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4345 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4346 } 4347 break; 4348 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4349 if (!a.getBoolean(attr, true)) { 4350 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4351 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4352 } 4353 break; 4354 case R.styleable.View_scrollbars: 4355 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4356 if (scrollbars != SCROLLBARS_NONE) { 4357 viewFlagValues |= scrollbars; 4358 viewFlagMasks |= SCROLLBARS_MASK; 4359 initializeScrollbars = true; 4360 } 4361 break; 4362 //noinspection deprecation 4363 case R.styleable.View_fadingEdge: 4364 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4365 // Ignore the attribute starting with ICS 4366 break; 4367 } 4368 // With builds < ICS, fall through and apply fading edges 4369 case R.styleable.View_requiresFadingEdge: 4370 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4371 if (fadingEdge != FADING_EDGE_NONE) { 4372 viewFlagValues |= fadingEdge; 4373 viewFlagMasks |= FADING_EDGE_MASK; 4374 initializeFadingEdgeInternal(a); 4375 } 4376 break; 4377 case R.styleable.View_scrollbarStyle: 4378 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4379 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4380 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4381 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4382 } 4383 break; 4384 case R.styleable.View_isScrollContainer: 4385 setScrollContainer = true; 4386 if (a.getBoolean(attr, false)) { 4387 setScrollContainer(true); 4388 } 4389 break; 4390 case com.android.internal.R.styleable.View_keepScreenOn: 4391 if (a.getBoolean(attr, false)) { 4392 viewFlagValues |= KEEP_SCREEN_ON; 4393 viewFlagMasks |= KEEP_SCREEN_ON; 4394 } 4395 break; 4396 case R.styleable.View_filterTouchesWhenObscured: 4397 if (a.getBoolean(attr, false)) { 4398 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4399 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4400 } 4401 break; 4402 case R.styleable.View_nextFocusLeft: 4403 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4404 break; 4405 case R.styleable.View_nextFocusRight: 4406 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4407 break; 4408 case R.styleable.View_nextFocusUp: 4409 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4410 break; 4411 case R.styleable.View_nextFocusDown: 4412 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4413 break; 4414 case R.styleable.View_nextFocusForward: 4415 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4416 break; 4417 case R.styleable.View_minWidth: 4418 mMinWidth = a.getDimensionPixelSize(attr, 0); 4419 break; 4420 case R.styleable.View_minHeight: 4421 mMinHeight = a.getDimensionPixelSize(attr, 0); 4422 break; 4423 case R.styleable.View_onClick: 4424 if (context.isRestricted()) { 4425 throw new IllegalStateException("The android:onClick attribute cannot " 4426 + "be used within a restricted context"); 4427 } 4428 4429 final String handlerName = a.getString(attr); 4430 if (handlerName != null) { 4431 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4432 } 4433 break; 4434 case R.styleable.View_overScrollMode: 4435 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4436 break; 4437 case R.styleable.View_verticalScrollbarPosition: 4438 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4439 break; 4440 case R.styleable.View_layerType: 4441 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4442 break; 4443 case R.styleable.View_textDirection: 4444 // Clear any text direction flag already set 4445 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4446 // Set the text direction flags depending on the value of the attribute 4447 final int textDirection = a.getInt(attr, -1); 4448 if (textDirection != -1) { 4449 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4450 } 4451 break; 4452 case R.styleable.View_textAlignment: 4453 // Clear any text alignment flag already set 4454 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4455 // Set the text alignment flag depending on the value of the attribute 4456 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4457 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4458 break; 4459 case R.styleable.View_importantForAccessibility: 4460 setImportantForAccessibility(a.getInt(attr, 4461 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4462 break; 4463 case R.styleable.View_accessibilityLiveRegion: 4464 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4465 break; 4466 case R.styleable.View_transitionName: 4467 setTransitionName(a.getString(attr)); 4468 break; 4469 case R.styleable.View_nestedScrollingEnabled: 4470 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4471 break; 4472 case R.styleable.View_stateListAnimator: 4473 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4474 a.getResourceId(attr, 0))); 4475 break; 4476 case R.styleable.View_backgroundTint: 4477 // This will get applied later during setBackground(). 4478 if (mBackgroundTint == null) { 4479 mBackgroundTint = new TintInfo(); 4480 } 4481 mBackgroundTint.mTintList = a.getColorStateList( 4482 R.styleable.View_backgroundTint); 4483 mBackgroundTint.mHasTintList = true; 4484 break; 4485 case R.styleable.View_backgroundTintMode: 4486 // This will get applied later during setBackground(). 4487 if (mBackgroundTint == null) { 4488 mBackgroundTint = new TintInfo(); 4489 } 4490 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4491 R.styleable.View_backgroundTintMode, -1), null); 4492 mBackgroundTint.mHasTintMode = true; 4493 break; 4494 case R.styleable.View_outlineProvider: 4495 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4496 PROVIDER_BACKGROUND)); 4497 break; 4498 case R.styleable.View_foreground: 4499 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4500 setForeground(a.getDrawable(attr)); 4501 } 4502 break; 4503 case R.styleable.View_foregroundGravity: 4504 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4505 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4506 } 4507 break; 4508 case R.styleable.View_foregroundTintMode: 4509 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4510 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4511 } 4512 break; 4513 case R.styleable.View_foregroundTint: 4514 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4515 setForegroundTintList(a.getColorStateList(attr)); 4516 } 4517 break; 4518 case R.styleable.View_foregroundInsidePadding: 4519 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4520 if (mForegroundInfo == null) { 4521 mForegroundInfo = new ForegroundInfo(); 4522 } 4523 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4524 mForegroundInfo.mInsidePadding); 4525 } 4526 break; 4527 case R.styleable.View_scrollIndicators: 4528 final int scrollIndicators = 4529 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4530 & SCROLL_INDICATORS_PFLAG3_MASK; 4531 if (scrollIndicators != 0) { 4532 mPrivateFlags3 |= scrollIndicators; 4533 initializeScrollIndicators = true; 4534 } 4535 break; 4536 case R.styleable.View_pointerShape: 4537 final int resourceId = a.getResourceId(attr, 0); 4538 if (resourceId != 0) { 4539 setPointerIcon(PointerIcon.loadCustomIcon( 4540 context.getResources(), resourceId)); 4541 } else { 4542 final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED); 4543 if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) { 4544 setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape)); 4545 } 4546 } 4547 break; 4548 case R.styleable.View_forceHasOverlappingRendering: 4549 if (a.peekValue(attr) != null) { 4550 forceHasOverlappingRendering(a.getBoolean(attr, true)); 4551 } 4552 break; 4553 4554 } 4555 } 4556 4557 setOverScrollMode(overScrollMode); 4558 4559 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4560 // the resolved layout direction). Those cached values will be used later during padding 4561 // resolution. 4562 mUserPaddingStart = startPadding; 4563 mUserPaddingEnd = endPadding; 4564 4565 if (background != null) { 4566 setBackground(background); 4567 } 4568 4569 // setBackground above will record that padding is currently provided by the background. 4570 // If we have padding specified via xml, record that here instead and use it. 4571 mLeftPaddingDefined = leftPaddingDefined; 4572 mRightPaddingDefined = rightPaddingDefined; 4573 4574 if (padding >= 0) { 4575 leftPadding = padding; 4576 topPadding = padding; 4577 rightPadding = padding; 4578 bottomPadding = padding; 4579 mUserPaddingLeftInitial = padding; 4580 mUserPaddingRightInitial = padding; 4581 } 4582 4583 if (isRtlCompatibilityMode()) { 4584 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4585 // left / right padding are used if defined (meaning here nothing to do). If they are not 4586 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4587 // start / end and resolve them as left / right (layout direction is not taken into account). 4588 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4589 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4590 // defined. 4591 if (!mLeftPaddingDefined && startPaddingDefined) { 4592 leftPadding = startPadding; 4593 } 4594 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4595 if (!mRightPaddingDefined && endPaddingDefined) { 4596 rightPadding = endPadding; 4597 } 4598 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4599 } else { 4600 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4601 // values defined. Otherwise, left /right values are used. 4602 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4603 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4604 // defined. 4605 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4606 4607 if (mLeftPaddingDefined && !hasRelativePadding) { 4608 mUserPaddingLeftInitial = leftPadding; 4609 } 4610 if (mRightPaddingDefined && !hasRelativePadding) { 4611 mUserPaddingRightInitial = rightPadding; 4612 } 4613 } 4614 4615 internalSetPadding( 4616 mUserPaddingLeftInitial, 4617 topPadding >= 0 ? topPadding : mPaddingTop, 4618 mUserPaddingRightInitial, 4619 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4620 4621 if (viewFlagMasks != 0) { 4622 setFlags(viewFlagValues, viewFlagMasks); 4623 } 4624 4625 if (initializeScrollbars) { 4626 initializeScrollbarsInternal(a); 4627 } 4628 4629 if (initializeScrollIndicators) { 4630 initializeScrollIndicatorsInternal(); 4631 } 4632 4633 a.recycle(); 4634 4635 // Needs to be called after mViewFlags is set 4636 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4637 recomputePadding(); 4638 } 4639 4640 if (x != 0 || y != 0) { 4641 scrollTo(x, y); 4642 } 4643 4644 if (transformSet) { 4645 setTranslationX(tx); 4646 setTranslationY(ty); 4647 setTranslationZ(tz); 4648 setElevation(elevation); 4649 setRotation(rotation); 4650 setRotationX(rotationX); 4651 setRotationY(rotationY); 4652 setScaleX(sx); 4653 setScaleY(sy); 4654 } 4655 4656 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4657 setScrollContainer(true); 4658 } 4659 4660 computeOpaqueFlags(); 4661 } 4662 4663 /** 4664 * An implementation of OnClickListener that attempts to lazily load a 4665 * named click handling method from a parent or ancestor context. 4666 */ 4667 private static class DeclaredOnClickListener implements OnClickListener { 4668 private final View mHostView; 4669 private final String mMethodName; 4670 4671 private Method mResolvedMethod; 4672 private Context mResolvedContext; 4673 4674 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4675 mHostView = hostView; 4676 mMethodName = methodName; 4677 } 4678 4679 @Override 4680 public void onClick(@NonNull View v) { 4681 if (mResolvedMethod == null) { 4682 resolveMethod(mHostView.getContext(), mMethodName); 4683 } 4684 4685 try { 4686 mResolvedMethod.invoke(mResolvedContext, v); 4687 } catch (IllegalAccessException e) { 4688 throw new IllegalStateException( 4689 "Could not execute non-public method for android:onClick", e); 4690 } catch (InvocationTargetException e) { 4691 throw new IllegalStateException( 4692 "Could not execute method for android:onClick", e); 4693 } 4694 } 4695 4696 @NonNull 4697 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4698 while (context != null) { 4699 try { 4700 if (!context.isRestricted()) { 4701 final Method method = context.getClass().getMethod(mMethodName, View.class); 4702 if (method != null) { 4703 mResolvedMethod = method; 4704 mResolvedContext = context; 4705 return; 4706 } 4707 } 4708 } catch (NoSuchMethodException e) { 4709 // Failed to find method, keep searching up the hierarchy. 4710 } 4711 4712 if (context instanceof ContextWrapper) { 4713 context = ((ContextWrapper) context).getBaseContext(); 4714 } else { 4715 // Can't search up the hierarchy, null out and fail. 4716 context = null; 4717 } 4718 } 4719 4720 final int id = mHostView.getId(); 4721 final String idText = id == NO_ID ? "" : " with id '" 4722 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4723 throw new IllegalStateException("Could not find method " + mMethodName 4724 + "(View) in a parent or ancestor Context for android:onClick " 4725 + "attribute defined on view " + mHostView.getClass() + idText); 4726 } 4727 } 4728 4729 /** 4730 * Non-public constructor for use in testing 4731 */ 4732 View() { 4733 mResources = null; 4734 mRenderNode = RenderNode.create(getClass().getName(), this); 4735 } 4736 4737 private static SparseArray<String> getAttributeMap() { 4738 if (mAttributeMap == null) { 4739 mAttributeMap = new SparseArray<>(); 4740 } 4741 return mAttributeMap; 4742 } 4743 4744 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4745 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4746 final int indexCount = t.getIndexCount(); 4747 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4748 4749 int i = 0; 4750 4751 // Store raw XML attributes. 4752 for (int j = 0; j < attrsCount; ++j) { 4753 attributes[i] = attrs.getAttributeName(j); 4754 attributes[i + 1] = attrs.getAttributeValue(j); 4755 i += 2; 4756 } 4757 4758 // Store resolved styleable attributes. 4759 final Resources res = t.getResources(); 4760 final SparseArray<String> attributeMap = getAttributeMap(); 4761 for (int j = 0; j < indexCount; ++j) { 4762 final int index = t.getIndex(j); 4763 if (!t.hasValueOrEmpty(index)) { 4764 // Value is undefined. Skip it. 4765 continue; 4766 } 4767 4768 final int resourceId = t.getResourceId(index, 0); 4769 if (resourceId == 0) { 4770 // Value is not a reference. Skip it. 4771 continue; 4772 } 4773 4774 String resourceName = attributeMap.get(resourceId); 4775 if (resourceName == null) { 4776 try { 4777 resourceName = res.getResourceName(resourceId); 4778 } catch (Resources.NotFoundException e) { 4779 resourceName = "0x" + Integer.toHexString(resourceId); 4780 } 4781 attributeMap.put(resourceId, resourceName); 4782 } 4783 4784 attributes[i] = resourceName; 4785 attributes[i + 1] = t.getString(index); 4786 i += 2; 4787 } 4788 4789 // Trim to fit contents. 4790 final String[] trimmed = new String[i]; 4791 System.arraycopy(attributes, 0, trimmed, 0, i); 4792 mAttributes = trimmed; 4793 } 4794 4795 public String toString() { 4796 StringBuilder out = new StringBuilder(128); 4797 out.append(getClass().getName()); 4798 out.append('{'); 4799 out.append(Integer.toHexString(System.identityHashCode(this))); 4800 out.append(' '); 4801 switch (mViewFlags&VISIBILITY_MASK) { 4802 case VISIBLE: out.append('V'); break; 4803 case INVISIBLE: out.append('I'); break; 4804 case GONE: out.append('G'); break; 4805 default: out.append('.'); break; 4806 } 4807 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4808 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4809 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4810 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4811 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4812 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4813 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4814 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4815 out.append(' '); 4816 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4817 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4818 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4819 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4820 out.append('p'); 4821 } else { 4822 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4823 } 4824 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4825 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4826 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4827 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4828 out.append(' '); 4829 out.append(mLeft); 4830 out.append(','); 4831 out.append(mTop); 4832 out.append('-'); 4833 out.append(mRight); 4834 out.append(','); 4835 out.append(mBottom); 4836 final int id = getId(); 4837 if (id != NO_ID) { 4838 out.append(" #"); 4839 out.append(Integer.toHexString(id)); 4840 final Resources r = mResources; 4841 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4842 try { 4843 String pkgname; 4844 switch (id&0xff000000) { 4845 case 0x7f000000: 4846 pkgname="app"; 4847 break; 4848 case 0x01000000: 4849 pkgname="android"; 4850 break; 4851 default: 4852 pkgname = r.getResourcePackageName(id); 4853 break; 4854 } 4855 String typename = r.getResourceTypeName(id); 4856 String entryname = r.getResourceEntryName(id); 4857 out.append(" "); 4858 out.append(pkgname); 4859 out.append(":"); 4860 out.append(typename); 4861 out.append("/"); 4862 out.append(entryname); 4863 } catch (Resources.NotFoundException e) { 4864 } 4865 } 4866 } 4867 out.append("}"); 4868 return out.toString(); 4869 } 4870 4871 /** 4872 * <p> 4873 * Initializes the fading edges from a given set of styled attributes. This 4874 * method should be called by subclasses that need fading edges and when an 4875 * instance of these subclasses is created programmatically rather than 4876 * being inflated from XML. This method is automatically called when the XML 4877 * is inflated. 4878 * </p> 4879 * 4880 * @param a the styled attributes set to initialize the fading edges from 4881 * 4882 * @removed 4883 */ 4884 protected void initializeFadingEdge(TypedArray a) { 4885 // This method probably shouldn't have been included in the SDK to begin with. 4886 // It relies on 'a' having been initialized using an attribute filter array that is 4887 // not publicly available to the SDK. The old method has been renamed 4888 // to initializeFadingEdgeInternal and hidden for framework use only; 4889 // this one initializes using defaults to make it safe to call for apps. 4890 4891 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4892 4893 initializeFadingEdgeInternal(arr); 4894 4895 arr.recycle(); 4896 } 4897 4898 /** 4899 * <p> 4900 * Initializes the fading edges from a given set of styled attributes. This 4901 * method should be called by subclasses that need fading edges and when an 4902 * instance of these subclasses is created programmatically rather than 4903 * being inflated from XML. This method is automatically called when the XML 4904 * is inflated. 4905 * </p> 4906 * 4907 * @param a the styled attributes set to initialize the fading edges from 4908 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4909 */ 4910 protected void initializeFadingEdgeInternal(TypedArray a) { 4911 initScrollCache(); 4912 4913 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4914 R.styleable.View_fadingEdgeLength, 4915 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4916 } 4917 4918 /** 4919 * Returns the size of the vertical faded edges used to indicate that more 4920 * content in this view is visible. 4921 * 4922 * @return The size in pixels of the vertical faded edge or 0 if vertical 4923 * faded edges are not enabled for this view. 4924 * @attr ref android.R.styleable#View_fadingEdgeLength 4925 */ 4926 public int getVerticalFadingEdgeLength() { 4927 if (isVerticalFadingEdgeEnabled()) { 4928 ScrollabilityCache cache = mScrollCache; 4929 if (cache != null) { 4930 return cache.fadingEdgeLength; 4931 } 4932 } 4933 return 0; 4934 } 4935 4936 /** 4937 * Set the size of the faded edge used to indicate that more content in this 4938 * view is available. Will not change whether the fading edge is enabled; use 4939 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4940 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4941 * for the vertical or horizontal fading edges. 4942 * 4943 * @param length The size in pixels of the faded edge used to indicate that more 4944 * content in this view is visible. 4945 */ 4946 public void setFadingEdgeLength(int length) { 4947 initScrollCache(); 4948 mScrollCache.fadingEdgeLength = length; 4949 } 4950 4951 /** 4952 * Returns the size of the horizontal faded edges used to indicate that more 4953 * content in this view is visible. 4954 * 4955 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4956 * faded edges are not enabled for this view. 4957 * @attr ref android.R.styleable#View_fadingEdgeLength 4958 */ 4959 public int getHorizontalFadingEdgeLength() { 4960 if (isHorizontalFadingEdgeEnabled()) { 4961 ScrollabilityCache cache = mScrollCache; 4962 if (cache != null) { 4963 return cache.fadingEdgeLength; 4964 } 4965 } 4966 return 0; 4967 } 4968 4969 /** 4970 * Returns the width of the vertical scrollbar. 4971 * 4972 * @return The width in pixels of the vertical scrollbar or 0 if there 4973 * is no vertical scrollbar. 4974 */ 4975 public int getVerticalScrollbarWidth() { 4976 ScrollabilityCache cache = mScrollCache; 4977 if (cache != null) { 4978 ScrollBarDrawable scrollBar = cache.scrollBar; 4979 if (scrollBar != null) { 4980 int size = scrollBar.getSize(true); 4981 if (size <= 0) { 4982 size = cache.scrollBarSize; 4983 } 4984 return size; 4985 } 4986 return 0; 4987 } 4988 return 0; 4989 } 4990 4991 /** 4992 * Returns the height of the horizontal scrollbar. 4993 * 4994 * @return The height in pixels of the horizontal scrollbar or 0 if 4995 * there is no horizontal scrollbar. 4996 */ 4997 protected int getHorizontalScrollbarHeight() { 4998 ScrollabilityCache cache = mScrollCache; 4999 if (cache != null) { 5000 ScrollBarDrawable scrollBar = cache.scrollBar; 5001 if (scrollBar != null) { 5002 int size = scrollBar.getSize(false); 5003 if (size <= 0) { 5004 size = cache.scrollBarSize; 5005 } 5006 return size; 5007 } 5008 return 0; 5009 } 5010 return 0; 5011 } 5012 5013 /** 5014 * <p> 5015 * Initializes the scrollbars from a given set of styled attributes. This 5016 * method should be called by subclasses that need scrollbars and when an 5017 * instance of these subclasses is created programmatically rather than 5018 * being inflated from XML. This method is automatically called when the XML 5019 * is inflated. 5020 * </p> 5021 * 5022 * @param a the styled attributes set to initialize the scrollbars from 5023 * 5024 * @removed 5025 */ 5026 protected void initializeScrollbars(TypedArray a) { 5027 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5028 // using the View filter array which is not available to the SDK. As such, internal 5029 // framework usage now uses initializeScrollbarsInternal and we grab a default 5030 // TypedArray with the right filter instead here. 5031 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5032 5033 initializeScrollbarsInternal(arr); 5034 5035 // We ignored the method parameter. Recycle the one we actually did use. 5036 arr.recycle(); 5037 } 5038 5039 /** 5040 * <p> 5041 * Initializes the scrollbars from a given set of styled attributes. This 5042 * method should be called by subclasses that need scrollbars and when an 5043 * instance of these subclasses is created programmatically rather than 5044 * being inflated from XML. This method is automatically called when the XML 5045 * is inflated. 5046 * </p> 5047 * 5048 * @param a the styled attributes set to initialize the scrollbars from 5049 * @hide 5050 */ 5051 protected void initializeScrollbarsInternal(TypedArray a) { 5052 initScrollCache(); 5053 5054 final ScrollabilityCache scrollabilityCache = mScrollCache; 5055 5056 if (scrollabilityCache.scrollBar == null) { 5057 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5058 scrollabilityCache.scrollBar.setState(getDrawableState()); 5059 scrollabilityCache.scrollBar.setCallback(this); 5060 } 5061 5062 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5063 5064 if (!fadeScrollbars) { 5065 scrollabilityCache.state = ScrollabilityCache.ON; 5066 } 5067 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5068 5069 5070 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5071 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5072 .getScrollBarFadeDuration()); 5073 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5074 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5075 ViewConfiguration.getScrollDefaultDelay()); 5076 5077 5078 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5079 com.android.internal.R.styleable.View_scrollbarSize, 5080 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5081 5082 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5083 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5084 5085 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5086 if (thumb != null) { 5087 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5088 } 5089 5090 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5091 false); 5092 if (alwaysDraw) { 5093 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5094 } 5095 5096 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5097 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5098 5099 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5100 if (thumb != null) { 5101 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5102 } 5103 5104 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5105 false); 5106 if (alwaysDraw) { 5107 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5108 } 5109 5110 // Apply layout direction to the new Drawables if needed 5111 final int layoutDirection = getLayoutDirection(); 5112 if (track != null) { 5113 track.setLayoutDirection(layoutDirection); 5114 } 5115 if (thumb != null) { 5116 thumb.setLayoutDirection(layoutDirection); 5117 } 5118 5119 // Re-apply user/background padding so that scrollbar(s) get added 5120 resolvePadding(); 5121 } 5122 5123 private void initializeScrollIndicatorsInternal() { 5124 // Some day maybe we'll break this into top/left/start/etc. and let the 5125 // client control it. Until then, you can have any scroll indicator you 5126 // want as long as it's a 1dp foreground-colored rectangle. 5127 if (mScrollIndicatorDrawable == null) { 5128 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5129 } 5130 } 5131 5132 /** 5133 * <p> 5134 * Initalizes the scrollability cache if necessary. 5135 * </p> 5136 */ 5137 private void initScrollCache() { 5138 if (mScrollCache == null) { 5139 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5140 } 5141 } 5142 5143 private ScrollabilityCache getScrollCache() { 5144 initScrollCache(); 5145 return mScrollCache; 5146 } 5147 5148 /** 5149 * Set the position of the vertical scroll bar. Should be one of 5150 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5151 * {@link #SCROLLBAR_POSITION_RIGHT}. 5152 * 5153 * @param position Where the vertical scroll bar should be positioned. 5154 */ 5155 public void setVerticalScrollbarPosition(int position) { 5156 if (mVerticalScrollbarPosition != position) { 5157 mVerticalScrollbarPosition = position; 5158 computeOpaqueFlags(); 5159 resolvePadding(); 5160 } 5161 } 5162 5163 /** 5164 * @return The position where the vertical scroll bar will show, if applicable. 5165 * @see #setVerticalScrollbarPosition(int) 5166 */ 5167 public int getVerticalScrollbarPosition() { 5168 return mVerticalScrollbarPosition; 5169 } 5170 5171 boolean isOnScrollbar(float x, float y) { 5172 if (mScrollCache == null) { 5173 return false; 5174 } 5175 x += getScrollX(); 5176 y += getScrollY(); 5177 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5178 final Rect bounds = mScrollCache.mScrollBarBounds; 5179 getVerticalScrollBarBounds(bounds); 5180 if (bounds.contains((int)x, (int)y)) { 5181 return true; 5182 } 5183 } 5184 if (isHorizontalScrollBarEnabled()) { 5185 final Rect bounds = mScrollCache.mScrollBarBounds; 5186 getHorizontalScrollBarBounds(bounds); 5187 if (bounds.contains((int)x, (int)y)) { 5188 return true; 5189 } 5190 } 5191 return false; 5192 } 5193 5194 boolean isOnScrollbarThumb(float x, float y) { 5195 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5196 } 5197 5198 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5199 if (mScrollCache == null) { 5200 return false; 5201 } 5202 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5203 x += getScrollX(); 5204 y += getScrollY(); 5205 final Rect bounds = mScrollCache.mScrollBarBounds; 5206 getVerticalScrollBarBounds(bounds); 5207 final int range = computeVerticalScrollRange(); 5208 final int offset = computeVerticalScrollOffset(); 5209 final int extent = computeVerticalScrollExtent(); 5210 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5211 extent, range); 5212 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5213 extent, range, offset); 5214 final int thumbTop = bounds.top + thumbOffset; 5215 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5216 && y <= thumbTop + thumbLength) { 5217 return true; 5218 } 5219 } 5220 return false; 5221 } 5222 5223 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5224 if (mScrollCache == null) { 5225 return false; 5226 } 5227 if (isHorizontalScrollBarEnabled()) { 5228 x += getScrollX(); 5229 y += getScrollY(); 5230 final Rect bounds = mScrollCache.mScrollBarBounds; 5231 getHorizontalScrollBarBounds(bounds); 5232 final int range = computeHorizontalScrollRange(); 5233 final int offset = computeHorizontalScrollOffset(); 5234 final int extent = computeHorizontalScrollExtent(); 5235 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5236 extent, range); 5237 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5238 extent, range, offset); 5239 final int thumbLeft = bounds.left + thumbOffset; 5240 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5241 && y <= bounds.bottom) { 5242 return true; 5243 } 5244 } 5245 return false; 5246 } 5247 5248 boolean isDraggingScrollBar() { 5249 return mScrollCache != null 5250 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5251 } 5252 5253 /** 5254 * Sets the state of all scroll indicators. 5255 * <p> 5256 * See {@link #setScrollIndicators(int, int)} for usage information. 5257 * 5258 * @param indicators a bitmask of indicators that should be enabled, or 5259 * {@code 0} to disable all indicators 5260 * @see #setScrollIndicators(int, int) 5261 * @see #getScrollIndicators() 5262 * @attr ref android.R.styleable#View_scrollIndicators 5263 */ 5264 public void setScrollIndicators(@ScrollIndicators int indicators) { 5265 setScrollIndicators(indicators, 5266 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5267 } 5268 5269 /** 5270 * Sets the state of the scroll indicators specified by the mask. To change 5271 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5272 * <p> 5273 * When a scroll indicator is enabled, it will be displayed if the view 5274 * can scroll in the direction of the indicator. 5275 * <p> 5276 * Multiple indicator types may be enabled or disabled by passing the 5277 * logical OR of the desired types. If multiple types are specified, they 5278 * will all be set to the same enabled state. 5279 * <p> 5280 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5281 * 5282 * @param indicators the indicator direction, or the logical OR of multiple 5283 * indicator directions. One or more of: 5284 * <ul> 5285 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5286 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5287 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5288 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5289 * <li>{@link #SCROLL_INDICATOR_START}</li> 5290 * <li>{@link #SCROLL_INDICATOR_END}</li> 5291 * </ul> 5292 * @see #setScrollIndicators(int) 5293 * @see #getScrollIndicators() 5294 * @attr ref android.R.styleable#View_scrollIndicators 5295 */ 5296 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5297 // Shift and sanitize mask. 5298 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5299 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5300 5301 // Shift and mask indicators. 5302 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5303 indicators &= mask; 5304 5305 // Merge with non-masked flags. 5306 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5307 5308 if (mPrivateFlags3 != updatedFlags) { 5309 mPrivateFlags3 = updatedFlags; 5310 5311 if (indicators != 0) { 5312 initializeScrollIndicatorsInternal(); 5313 } 5314 invalidate(); 5315 } 5316 } 5317 5318 /** 5319 * Returns a bitmask representing the enabled scroll indicators. 5320 * <p> 5321 * For example, if the top and left scroll indicators are enabled and all 5322 * other indicators are disabled, the return value will be 5323 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5324 * <p> 5325 * To check whether the bottom scroll indicator is enabled, use the value 5326 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5327 * 5328 * @return a bitmask representing the enabled scroll indicators 5329 */ 5330 @ScrollIndicators 5331 public int getScrollIndicators() { 5332 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5333 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5334 } 5335 5336 ListenerInfo getListenerInfo() { 5337 if (mListenerInfo != null) { 5338 return mListenerInfo; 5339 } 5340 mListenerInfo = new ListenerInfo(); 5341 return mListenerInfo; 5342 } 5343 5344 /** 5345 * Register a callback to be invoked when the scroll X or Y positions of 5346 * this view change. 5347 * <p> 5348 * <b>Note:</b> Some views handle scrolling independently from View and may 5349 * have their own separate listeners for scroll-type events. For example, 5350 * {@link android.widget.ListView ListView} allows clients to register an 5351 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5352 * to listen for changes in list scroll position. 5353 * 5354 * @param l The listener to notify when the scroll X or Y position changes. 5355 * @see android.view.View#getScrollX() 5356 * @see android.view.View#getScrollY() 5357 */ 5358 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5359 getListenerInfo().mOnScrollChangeListener = l; 5360 } 5361 5362 /** 5363 * Register a callback to be invoked when focus of this view changed. 5364 * 5365 * @param l The callback that will run. 5366 */ 5367 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5368 getListenerInfo().mOnFocusChangeListener = l; 5369 } 5370 5371 /** 5372 * Add a listener that will be called when the bounds of the view change due to 5373 * layout processing. 5374 * 5375 * @param listener The listener that will be called when layout bounds change. 5376 */ 5377 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5378 ListenerInfo li = getListenerInfo(); 5379 if (li.mOnLayoutChangeListeners == null) { 5380 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5381 } 5382 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5383 li.mOnLayoutChangeListeners.add(listener); 5384 } 5385 } 5386 5387 /** 5388 * Remove a listener for layout changes. 5389 * 5390 * @param listener The listener for layout bounds change. 5391 */ 5392 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5393 ListenerInfo li = mListenerInfo; 5394 if (li == null || li.mOnLayoutChangeListeners == null) { 5395 return; 5396 } 5397 li.mOnLayoutChangeListeners.remove(listener); 5398 } 5399 5400 /** 5401 * Add a listener for attach state changes. 5402 * 5403 * This listener will be called whenever this view is attached or detached 5404 * from a window. Remove the listener using 5405 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5406 * 5407 * @param listener Listener to attach 5408 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5409 */ 5410 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5411 ListenerInfo li = getListenerInfo(); 5412 if (li.mOnAttachStateChangeListeners == null) { 5413 li.mOnAttachStateChangeListeners 5414 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5415 } 5416 li.mOnAttachStateChangeListeners.add(listener); 5417 } 5418 5419 /** 5420 * Remove a listener for attach state changes. The listener will receive no further 5421 * notification of window attach/detach events. 5422 * 5423 * @param listener Listener to remove 5424 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5425 */ 5426 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5427 ListenerInfo li = mListenerInfo; 5428 if (li == null || li.mOnAttachStateChangeListeners == null) { 5429 return; 5430 } 5431 li.mOnAttachStateChangeListeners.remove(listener); 5432 } 5433 5434 /** 5435 * Returns the focus-change callback registered for this view. 5436 * 5437 * @return The callback, or null if one is not registered. 5438 */ 5439 public OnFocusChangeListener getOnFocusChangeListener() { 5440 ListenerInfo li = mListenerInfo; 5441 return li != null ? li.mOnFocusChangeListener : null; 5442 } 5443 5444 /** 5445 * Register a callback to be invoked when this view is clicked. If this view is not 5446 * clickable, it becomes clickable. 5447 * 5448 * @param l The callback that will run 5449 * 5450 * @see #setClickable(boolean) 5451 */ 5452 public void setOnClickListener(@Nullable OnClickListener l) { 5453 if (!isClickable()) { 5454 setClickable(true); 5455 } 5456 getListenerInfo().mOnClickListener = l; 5457 } 5458 5459 /** 5460 * Return whether this view has an attached OnClickListener. Returns 5461 * true if there is a listener, false if there is none. 5462 */ 5463 public boolean hasOnClickListeners() { 5464 ListenerInfo li = mListenerInfo; 5465 return (li != null && li.mOnClickListener != null); 5466 } 5467 5468 /** 5469 * Register a callback to be invoked when this view is clicked and held. If this view is not 5470 * long clickable, it becomes long clickable. 5471 * 5472 * @param l The callback that will run 5473 * 5474 * @see #setLongClickable(boolean) 5475 */ 5476 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5477 if (!isLongClickable()) { 5478 setLongClickable(true); 5479 } 5480 getListenerInfo().mOnLongClickListener = l; 5481 } 5482 5483 /** 5484 * Register a callback to be invoked when this view is context clicked. If the view is not 5485 * context clickable, it becomes context clickable. 5486 * 5487 * @param l The callback that will run 5488 * @see #setContextClickable(boolean) 5489 */ 5490 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5491 if (!isContextClickable()) { 5492 setContextClickable(true); 5493 } 5494 getListenerInfo().mOnContextClickListener = l; 5495 } 5496 5497 /** 5498 * Register a callback to be invoked when the context menu for this view is 5499 * being built. If this view is not long clickable, it becomes long clickable. 5500 * 5501 * @param l The callback that will run 5502 * 5503 */ 5504 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5505 if (!isLongClickable()) { 5506 setLongClickable(true); 5507 } 5508 getListenerInfo().mOnCreateContextMenuListener = l; 5509 } 5510 5511 /** 5512 * Set an observer to collect stats for each frame rendered for this view. 5513 * 5514 * @hide 5515 */ 5516 public void addFrameMetricsListener(Window window, Window.FrameMetricsListener listener, 5517 Handler handler) { 5518 if (mAttachInfo != null) { 5519 if (mAttachInfo.mHardwareRenderer != null) { 5520 if (mFrameMetricsObservers == null) { 5521 mFrameMetricsObservers = new ArrayList<>(); 5522 } 5523 5524 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5525 handler.getLooper(), listener); 5526 mFrameMetricsObservers.add(fmo); 5527 mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo); 5528 } else { 5529 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5530 } 5531 } else { 5532 if (mFrameMetricsObservers == null) { 5533 mFrameMetricsObservers = new ArrayList<>(); 5534 } 5535 5536 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5537 handler.getLooper(), listener); 5538 mFrameMetricsObservers.add(fmo); 5539 } 5540 } 5541 5542 /** 5543 * Remove observer configured to collect frame stats for this view. 5544 * 5545 * @hide 5546 */ 5547 public void removeFrameMetricsListener(Window.FrameMetricsListener listener) { 5548 ThreadedRenderer renderer = getHardwareRenderer(); 5549 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5550 if (fmo == null) { 5551 throw new IllegalArgumentException("attempt to remove FrameMetricsListener that was never added"); 5552 } 5553 5554 if (mFrameMetricsObservers != null) { 5555 mFrameMetricsObservers.remove(fmo); 5556 if (renderer != null) { 5557 renderer.removeFrameMetricsObserver(fmo); 5558 } 5559 } 5560 } 5561 5562 private void registerPendingFrameMetricsObservers() { 5563 if (mFrameMetricsObservers != null) { 5564 ThreadedRenderer renderer = getHardwareRenderer(); 5565 if (renderer != null) { 5566 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5567 renderer.addFrameMetricsObserver(fmo); 5568 } 5569 } else { 5570 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5571 } 5572 } 5573 } 5574 5575 private FrameMetricsObserver findFrameMetricsObserver(Window.FrameMetricsListener listener) { 5576 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5577 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5578 if (observer.mListener == listener) { 5579 return observer; 5580 } 5581 } 5582 5583 return null; 5584 } 5585 5586 /** 5587 * Call this view's OnClickListener, if it is defined. Performs all normal 5588 * actions associated with clicking: reporting accessibility event, playing 5589 * a sound, etc. 5590 * 5591 * @return True there was an assigned OnClickListener that was called, false 5592 * otherwise is returned. 5593 */ 5594 public boolean performClick() { 5595 final boolean result; 5596 final ListenerInfo li = mListenerInfo; 5597 if (li != null && li.mOnClickListener != null) { 5598 playSoundEffect(SoundEffectConstants.CLICK); 5599 li.mOnClickListener.onClick(this); 5600 result = true; 5601 } else { 5602 result = false; 5603 } 5604 5605 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5606 return result; 5607 } 5608 5609 /** 5610 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5611 * this only calls the listener, and does not do any associated clicking 5612 * actions like reporting an accessibility event. 5613 * 5614 * @return True there was an assigned OnClickListener that was called, false 5615 * otherwise is returned. 5616 */ 5617 public boolean callOnClick() { 5618 ListenerInfo li = mListenerInfo; 5619 if (li != null && li.mOnClickListener != null) { 5620 li.mOnClickListener.onClick(this); 5621 return true; 5622 } 5623 return false; 5624 } 5625 5626 /** 5627 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5628 * context menu if the OnLongClickListener did not consume the event. 5629 * 5630 * @return {@code true} if one of the above receivers consumed the event, 5631 * {@code false} otherwise 5632 */ 5633 public boolean performLongClick() { 5634 return performLongClickInternal(mLongClickX, mLongClickY); 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 * anchoring it to an (x,y) coordinate. 5641 * 5642 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5643 * to disable anchoring 5644 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5645 * to disable anchoring 5646 * @return {@code true} if one of the above receivers consumed the event, 5647 * {@code false} otherwise 5648 */ 5649 public boolean performLongClick(float x, float y) { 5650 mLongClickX = x; 5651 mLongClickY = y; 5652 final boolean handled = performLongClick(); 5653 mLongClickX = Float.NaN; 5654 mLongClickY = Float.NaN; 5655 return handled; 5656 } 5657 5658 /** 5659 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5660 * context menu if the OnLongClickListener did not consume the event, 5661 * optionally anchoring it to an (x,y) coordinate. 5662 * 5663 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5664 * to disable anchoring 5665 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5666 * to disable anchoring 5667 * @return {@code true} if one of the above receivers consumed the event, 5668 * {@code false} otherwise 5669 */ 5670 private boolean performLongClickInternal(float x, float y) { 5671 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5672 5673 boolean handled = false; 5674 final ListenerInfo li = mListenerInfo; 5675 if (li != null && li.mOnLongClickListener != null) { 5676 handled = li.mOnLongClickListener.onLongClick(View.this); 5677 } 5678 if (!handled) { 5679 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5680 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5681 } 5682 if (handled) { 5683 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5684 } 5685 return handled; 5686 } 5687 5688 /** 5689 * Call this view's OnContextClickListener, if it is defined. 5690 * 5691 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5692 * otherwise. 5693 */ 5694 public boolean performContextClick() { 5695 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5696 5697 boolean handled = false; 5698 ListenerInfo li = mListenerInfo; 5699 if (li != null && li.mOnContextClickListener != null) { 5700 handled = li.mOnContextClickListener.onContextClick(View.this); 5701 } 5702 if (handled) { 5703 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5704 } 5705 return handled; 5706 } 5707 5708 /** 5709 * Performs button-related actions during a touch down event. 5710 * 5711 * @param event The event. 5712 * @return True if the down was consumed. 5713 * 5714 * @hide 5715 */ 5716 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5717 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5718 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5719 showContextMenu(event.getX(), event.getY()); 5720 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5721 return true; 5722 } 5723 return false; 5724 } 5725 5726 /** 5727 * Shows the context menu for this view. 5728 * 5729 * @return {@code true} if the context menu was shown, {@code false} 5730 * otherwise 5731 * @see #showContextMenu(float, float) 5732 */ 5733 public boolean showContextMenu() { 5734 return getParent().showContextMenuForChild(this); 5735 } 5736 5737 /** 5738 * Shows the context menu for this view anchored to the specified 5739 * view-relative coordinate. 5740 * 5741 * @param x the X coordinate in pixels relative to the view to which the 5742 * menu should be anchored 5743 * @param y the Y coordinate in pixels relative to the view to which the 5744 * menu should be anchored 5745 * @return {@code true} if the context menu was shown, {@code false} 5746 * otherwise 5747 */ 5748 public boolean showContextMenu(float x, float y) { 5749 return getParent().showContextMenuForChild(this, x, y); 5750 } 5751 5752 /** 5753 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5754 * 5755 * @param callback Callback that will control the lifecycle of the action mode 5756 * @return The new action mode if it is started, null otherwise 5757 * 5758 * @see ActionMode 5759 * @see #startActionMode(android.view.ActionMode.Callback, int) 5760 */ 5761 public ActionMode startActionMode(ActionMode.Callback callback) { 5762 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5763 } 5764 5765 /** 5766 * Start an action mode with the given type. 5767 * 5768 * @param callback Callback that will control the lifecycle of the action mode 5769 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5770 * @return The new action mode if it is started, null otherwise 5771 * 5772 * @see ActionMode 5773 */ 5774 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5775 ViewParent parent = getParent(); 5776 if (parent == null) return null; 5777 try { 5778 return parent.startActionModeForChild(this, callback, type); 5779 } catch (AbstractMethodError ame) { 5780 // Older implementations of custom views might not implement this. 5781 return parent.startActionModeForChild(this, callback); 5782 } 5783 } 5784 5785 /** 5786 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5787 * Context, creating a unique View identifier to retrieve the result. 5788 * 5789 * @param intent The Intent to be started. 5790 * @param requestCode The request code to use. 5791 * @hide 5792 */ 5793 public void startActivityForResult(Intent intent, int requestCode) { 5794 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5795 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5796 } 5797 5798 /** 5799 * If this View corresponds to the calling who, dispatches the activity result. 5800 * @param who The identifier for the targeted View to receive the result. 5801 * @param requestCode The integer request code originally supplied to 5802 * startActivityForResult(), allowing you to identify who this 5803 * result came from. 5804 * @param resultCode The integer result code returned by the child activity 5805 * through its setResult(). 5806 * @param data An Intent, which can return result data to the caller 5807 * (various data can be attached to Intent "extras"). 5808 * @return {@code true} if the activity result was dispatched. 5809 * @hide 5810 */ 5811 public boolean dispatchActivityResult( 5812 String who, int requestCode, int resultCode, Intent data) { 5813 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5814 onActivityResult(requestCode, resultCode, data); 5815 mStartActivityRequestWho = null; 5816 return true; 5817 } 5818 return false; 5819 } 5820 5821 /** 5822 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5823 * 5824 * @param requestCode The integer request code originally supplied to 5825 * startActivityForResult(), allowing you to identify who this 5826 * result came from. 5827 * @param resultCode The integer result code returned by the child activity 5828 * through its setResult(). 5829 * @param data An Intent, which can return result data to the caller 5830 * (various data can be attached to Intent "extras"). 5831 * @hide 5832 */ 5833 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5834 // Do nothing. 5835 } 5836 5837 /** 5838 * Register a callback to be invoked when a hardware key is pressed in this view. 5839 * Key presses in software input methods will generally not trigger the methods of 5840 * this listener. 5841 * @param l the key listener to attach to this view 5842 */ 5843 public void setOnKeyListener(OnKeyListener l) { 5844 getListenerInfo().mOnKeyListener = l; 5845 } 5846 5847 /** 5848 * Register a callback to be invoked when a touch event is sent to this view. 5849 * @param l the touch listener to attach to this view 5850 */ 5851 public void setOnTouchListener(OnTouchListener l) { 5852 getListenerInfo().mOnTouchListener = l; 5853 } 5854 5855 /** 5856 * Register a callback to be invoked when a generic motion event is sent to this view. 5857 * @param l the generic motion listener to attach to this view 5858 */ 5859 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5860 getListenerInfo().mOnGenericMotionListener = l; 5861 } 5862 5863 /** 5864 * Register a callback to be invoked when a hover event is sent to this view. 5865 * @param l the hover listener to attach to this view 5866 */ 5867 public void setOnHoverListener(OnHoverListener l) { 5868 getListenerInfo().mOnHoverListener = l; 5869 } 5870 5871 /** 5872 * Register a drag event listener callback object for this View. The parameter is 5873 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5874 * View, the system calls the 5875 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5876 * @param l An implementation of {@link android.view.View.OnDragListener}. 5877 */ 5878 public void setOnDragListener(OnDragListener l) { 5879 getListenerInfo().mOnDragListener = l; 5880 } 5881 5882 /** 5883 * Give this view focus. This will cause 5884 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5885 * 5886 * Note: this does not check whether this {@link View} should get focus, it just 5887 * gives it focus no matter what. It should only be called internally by framework 5888 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5889 * 5890 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5891 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5892 * focus moved when requestFocus() is called. It may not always 5893 * apply, in which case use the default View.FOCUS_DOWN. 5894 * @param previouslyFocusedRect The rectangle of the view that had focus 5895 * prior in this View's coordinate system. 5896 */ 5897 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5898 if (DBG) { 5899 System.out.println(this + " requestFocus()"); 5900 } 5901 5902 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5903 mPrivateFlags |= PFLAG_FOCUSED; 5904 5905 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5906 5907 if (mParent != null) { 5908 mParent.requestChildFocus(this, this); 5909 } 5910 5911 if (mAttachInfo != null) { 5912 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5913 } 5914 5915 onFocusChanged(true, direction, previouslyFocusedRect); 5916 refreshDrawableState(); 5917 } 5918 } 5919 5920 /** 5921 * Populates <code>outRect</code> with the hotspot bounds. By default, 5922 * the hotspot bounds are identical to the screen bounds. 5923 * 5924 * @param outRect rect to populate with hotspot bounds 5925 * @hide Only for internal use by views and widgets. 5926 */ 5927 public void getHotspotBounds(Rect outRect) { 5928 final Drawable background = getBackground(); 5929 if (background != null) { 5930 background.getHotspotBounds(outRect); 5931 } else { 5932 getBoundsOnScreen(outRect); 5933 } 5934 } 5935 5936 /** 5937 * Request that a rectangle of this view be visible on the screen, 5938 * scrolling if necessary just enough. 5939 * 5940 * <p>A View should call this if it maintains some notion of which part 5941 * of its content is interesting. For example, a text editing view 5942 * should call this when its cursor moves. 5943 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5944 * It should not be affected by which part of the View is currently visible or its scroll 5945 * position. 5946 * 5947 * @param rectangle The rectangle in the View's content coordinate space 5948 * @return Whether any parent scrolled. 5949 */ 5950 public boolean requestRectangleOnScreen(Rect rectangle) { 5951 return requestRectangleOnScreen(rectangle, false); 5952 } 5953 5954 /** 5955 * Request that a rectangle of this view be visible on the screen, 5956 * scrolling if necessary just enough. 5957 * 5958 * <p>A View should call this if it maintains some notion of which part 5959 * of its content is interesting. For example, a text editing view 5960 * should call this when its cursor moves. 5961 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5962 * It should not be affected by which part of the View is currently visible or its scroll 5963 * position. 5964 * <p>When <code>immediate</code> is set to true, scrolling will not be 5965 * animated. 5966 * 5967 * @param rectangle The rectangle in the View's content coordinate space 5968 * @param immediate True to forbid animated scrolling, false otherwise 5969 * @return Whether any parent scrolled. 5970 */ 5971 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5972 if (mParent == null) { 5973 return false; 5974 } 5975 5976 View child = this; 5977 5978 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5979 position.set(rectangle); 5980 5981 ViewParent parent = mParent; 5982 boolean scrolled = false; 5983 while (parent != null) { 5984 rectangle.set((int) position.left, (int) position.top, 5985 (int) position.right, (int) position.bottom); 5986 5987 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 5988 5989 if (!(parent instanceof View)) { 5990 break; 5991 } 5992 5993 // move it from child's content coordinate space to parent's content coordinate space 5994 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 5995 5996 child = (View) parent; 5997 parent = child.getParent(); 5998 } 5999 6000 return scrolled; 6001 } 6002 6003 /** 6004 * Called when this view wants to give up focus. If focus is cleared 6005 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6006 * <p> 6007 * <strong>Note:</strong> When a View clears focus the framework is trying 6008 * to give focus to the first focusable View from the top. Hence, if this 6009 * View is the first from the top that can take focus, then all callbacks 6010 * related to clearing focus will be invoked after which the framework will 6011 * give focus to this view. 6012 * </p> 6013 */ 6014 public void clearFocus() { 6015 if (DBG) { 6016 System.out.println(this + " clearFocus()"); 6017 } 6018 6019 clearFocusInternal(null, true, true); 6020 } 6021 6022 /** 6023 * Clears focus from the view, optionally propagating the change up through 6024 * the parent hierarchy and requesting that the root view place new focus. 6025 * 6026 * @param propagate whether to propagate the change up through the parent 6027 * hierarchy 6028 * @param refocus when propagate is true, specifies whether to request the 6029 * root view place new focus 6030 */ 6031 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6032 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6033 mPrivateFlags &= ~PFLAG_FOCUSED; 6034 6035 if (propagate && mParent != null) { 6036 mParent.clearChildFocus(this); 6037 } 6038 6039 onFocusChanged(false, 0, null); 6040 refreshDrawableState(); 6041 6042 if (propagate && (!refocus || !rootViewRequestFocus())) { 6043 notifyGlobalFocusCleared(this); 6044 } 6045 } 6046 } 6047 6048 void notifyGlobalFocusCleared(View oldFocus) { 6049 if (oldFocus != null && mAttachInfo != null) { 6050 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6051 } 6052 } 6053 6054 boolean rootViewRequestFocus() { 6055 final View root = getRootView(); 6056 return root != null && root.requestFocus(); 6057 } 6058 6059 /** 6060 * Called internally by the view system when a new view is getting focus. 6061 * This is what clears the old focus. 6062 * <p> 6063 * <b>NOTE:</b> The parent view's focused child must be updated manually 6064 * after calling this method. Otherwise, the view hierarchy may be left in 6065 * an inconstent state. 6066 */ 6067 void unFocus(View focused) { 6068 if (DBG) { 6069 System.out.println(this + " unFocus()"); 6070 } 6071 6072 clearFocusInternal(focused, false, false); 6073 } 6074 6075 /** 6076 * Returns true if this view has focus itself, or is the ancestor of the 6077 * view that has focus. 6078 * 6079 * @return True if this view has or contains focus, false otherwise. 6080 */ 6081 @ViewDebug.ExportedProperty(category = "focus") 6082 public boolean hasFocus() { 6083 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6084 } 6085 6086 /** 6087 * Returns true if this view is focusable or if it contains a reachable View 6088 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6089 * is a View whose parents do not block descendants focus. 6090 * 6091 * Only {@link #VISIBLE} views are considered focusable. 6092 * 6093 * @return True if the view is focusable or if the view contains a focusable 6094 * View, false otherwise. 6095 * 6096 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6097 * @see ViewGroup#getTouchscreenBlocksFocus() 6098 */ 6099 public boolean hasFocusable() { 6100 if (!isFocusableInTouchMode()) { 6101 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6102 final ViewGroup g = (ViewGroup) p; 6103 if (g.shouldBlockFocusForTouchscreen()) { 6104 return false; 6105 } 6106 } 6107 } 6108 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6109 } 6110 6111 /** 6112 * Called by the view system when the focus state of this view changes. 6113 * When the focus change event is caused by directional navigation, direction 6114 * and previouslyFocusedRect provide insight into where the focus is coming from. 6115 * When overriding, be sure to call up through to the super class so that 6116 * the standard focus handling will occur. 6117 * 6118 * @param gainFocus True if the View has focus; false otherwise. 6119 * @param direction The direction focus has moved when requestFocus() 6120 * is called to give this view focus. Values are 6121 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6122 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6123 * It may not always apply, in which case use the default. 6124 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6125 * system, of the previously focused view. If applicable, this will be 6126 * passed in as finer grained information about where the focus is coming 6127 * from (in addition to direction). Will be <code>null</code> otherwise. 6128 */ 6129 @CallSuper 6130 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6131 @Nullable Rect previouslyFocusedRect) { 6132 if (gainFocus) { 6133 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6134 } else { 6135 notifyViewAccessibilityStateChangedIfNeeded( 6136 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6137 } 6138 6139 InputMethodManager imm = InputMethodManager.peekInstance(); 6140 if (!gainFocus) { 6141 if (isPressed()) { 6142 setPressed(false); 6143 } 6144 if (imm != null && mAttachInfo != null 6145 && mAttachInfo.mHasWindowFocus) { 6146 imm.focusOut(this); 6147 } 6148 onFocusLost(); 6149 } else if (imm != null && mAttachInfo != null 6150 && mAttachInfo.mHasWindowFocus) { 6151 imm.focusIn(this); 6152 } 6153 6154 invalidate(true); 6155 ListenerInfo li = mListenerInfo; 6156 if (li != null && li.mOnFocusChangeListener != null) { 6157 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6158 } 6159 6160 if (mAttachInfo != null) { 6161 mAttachInfo.mKeyDispatchState.reset(this); 6162 } 6163 } 6164 6165 /** 6166 * Sends an accessibility event of the given type. If accessibility is 6167 * not enabled this method has no effect. The default implementation calls 6168 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6169 * to populate information about the event source (this View), then calls 6170 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6171 * populate the text content of the event source including its descendants, 6172 * and last calls 6173 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6174 * on its parent to request sending of the event to interested parties. 6175 * <p> 6176 * If an {@link AccessibilityDelegate} has been specified via calling 6177 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6178 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6179 * responsible for handling this call. 6180 * </p> 6181 * 6182 * @param eventType The type of the event to send, as defined by several types from 6183 * {@link android.view.accessibility.AccessibilityEvent}, such as 6184 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6185 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6186 * 6187 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6188 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6189 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6190 * @see AccessibilityDelegate 6191 */ 6192 public void sendAccessibilityEvent(int eventType) { 6193 if (mAccessibilityDelegate != null) { 6194 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6195 } else { 6196 sendAccessibilityEventInternal(eventType); 6197 } 6198 } 6199 6200 /** 6201 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6202 * {@link AccessibilityEvent} to make an announcement which is related to some 6203 * sort of a context change for which none of the events representing UI transitions 6204 * is a good fit. For example, announcing a new page in a book. If accessibility 6205 * is not enabled this method does nothing. 6206 * 6207 * @param text The announcement text. 6208 */ 6209 public void announceForAccessibility(CharSequence text) { 6210 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6211 AccessibilityEvent event = AccessibilityEvent.obtain( 6212 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6213 onInitializeAccessibilityEvent(event); 6214 event.getText().add(text); 6215 event.setContentDescription(null); 6216 mParent.requestSendAccessibilityEvent(this, event); 6217 } 6218 } 6219 6220 /** 6221 * @see #sendAccessibilityEvent(int) 6222 * 6223 * Note: Called from the default {@link AccessibilityDelegate}. 6224 * 6225 * @hide 6226 */ 6227 public void sendAccessibilityEventInternal(int eventType) { 6228 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6229 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6230 } 6231 } 6232 6233 /** 6234 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6235 * takes as an argument an empty {@link AccessibilityEvent} and does not 6236 * perform a check whether accessibility is enabled. 6237 * <p> 6238 * If an {@link AccessibilityDelegate} has been specified via calling 6239 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6240 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6241 * is responsible for handling this call. 6242 * </p> 6243 * 6244 * @param event The event to send. 6245 * 6246 * @see #sendAccessibilityEvent(int) 6247 */ 6248 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6249 if (mAccessibilityDelegate != null) { 6250 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6251 } else { 6252 sendAccessibilityEventUncheckedInternal(event); 6253 } 6254 } 6255 6256 /** 6257 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6258 * 6259 * Note: Called from the default {@link AccessibilityDelegate}. 6260 * 6261 * @hide 6262 */ 6263 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6264 if (!isShown()) { 6265 return; 6266 } 6267 onInitializeAccessibilityEvent(event); 6268 // Only a subset of accessibility events populates text content. 6269 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6270 dispatchPopulateAccessibilityEvent(event); 6271 } 6272 // In the beginning we called #isShown(), so we know that getParent() is not null. 6273 getParent().requestSendAccessibilityEvent(this, event); 6274 } 6275 6276 /** 6277 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6278 * to its children for adding their text content to the event. Note that the 6279 * event text is populated in a separate dispatch path since we add to the 6280 * event not only the text of the source but also the text of all its descendants. 6281 * A typical implementation will call 6282 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6283 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6284 * on each child. Override this method if custom population of the event text 6285 * content is required. 6286 * <p> 6287 * If an {@link AccessibilityDelegate} has been specified via calling 6288 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6289 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6290 * is responsible for handling this call. 6291 * </p> 6292 * <p> 6293 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6294 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6295 * </p> 6296 * 6297 * @param event The event. 6298 * 6299 * @return True if the event population was completed. 6300 */ 6301 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6302 if (mAccessibilityDelegate != null) { 6303 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6304 } else { 6305 return dispatchPopulateAccessibilityEventInternal(event); 6306 } 6307 } 6308 6309 /** 6310 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6311 * 6312 * Note: Called from the default {@link AccessibilityDelegate}. 6313 * 6314 * @hide 6315 */ 6316 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6317 onPopulateAccessibilityEvent(event); 6318 return false; 6319 } 6320 6321 /** 6322 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6323 * giving a chance to this View to populate the accessibility event with its 6324 * text content. While this method is free to modify event 6325 * attributes other than text content, doing so should normally be performed in 6326 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6327 * <p> 6328 * Example: Adding formatted date string to an accessibility event in addition 6329 * to the text added by the super implementation: 6330 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6331 * super.onPopulateAccessibilityEvent(event); 6332 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6333 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6334 * mCurrentDate.getTimeInMillis(), flags); 6335 * event.getText().add(selectedDateUtterance); 6336 * }</pre> 6337 * <p> 6338 * If an {@link AccessibilityDelegate} has been specified via calling 6339 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6340 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6341 * is responsible for handling this call. 6342 * </p> 6343 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6344 * information to the event, in case the default implementation has basic information to add. 6345 * </p> 6346 * 6347 * @param event The accessibility event which to populate. 6348 * 6349 * @see #sendAccessibilityEvent(int) 6350 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6351 */ 6352 @CallSuper 6353 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6354 if (mAccessibilityDelegate != null) { 6355 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6356 } else { 6357 onPopulateAccessibilityEventInternal(event); 6358 } 6359 } 6360 6361 /** 6362 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6363 * 6364 * Note: Called from the default {@link AccessibilityDelegate}. 6365 * 6366 * @hide 6367 */ 6368 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6369 } 6370 6371 /** 6372 * Initializes an {@link AccessibilityEvent} with information about 6373 * this View which is the event source. In other words, the source of 6374 * an accessibility event is the view whose state change triggered firing 6375 * the event. 6376 * <p> 6377 * Example: Setting the password property of an event in addition 6378 * to properties set by the super implementation: 6379 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6380 * super.onInitializeAccessibilityEvent(event); 6381 * event.setPassword(true); 6382 * }</pre> 6383 * <p> 6384 * If an {@link AccessibilityDelegate} has been specified via calling 6385 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6386 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6387 * is responsible for handling this call. 6388 * </p> 6389 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6390 * information to the event, in case the default implementation has basic information to add. 6391 * </p> 6392 * @param event The event to initialize. 6393 * 6394 * @see #sendAccessibilityEvent(int) 6395 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6396 */ 6397 @CallSuper 6398 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6399 if (mAccessibilityDelegate != null) { 6400 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6401 } else { 6402 onInitializeAccessibilityEventInternal(event); 6403 } 6404 } 6405 6406 /** 6407 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6408 * 6409 * Note: Called from the default {@link AccessibilityDelegate}. 6410 * 6411 * @hide 6412 */ 6413 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6414 event.setSource(this); 6415 event.setClassName(getAccessibilityClassName()); 6416 event.setPackageName(getContext().getPackageName()); 6417 event.setEnabled(isEnabled()); 6418 event.setContentDescription(mContentDescription); 6419 6420 switch (event.getEventType()) { 6421 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6422 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6423 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6424 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6425 event.setItemCount(focusablesTempList.size()); 6426 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6427 if (mAttachInfo != null) { 6428 focusablesTempList.clear(); 6429 } 6430 } break; 6431 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6432 CharSequence text = getIterableTextForAccessibility(); 6433 if (text != null && text.length() > 0) { 6434 event.setFromIndex(getAccessibilitySelectionStart()); 6435 event.setToIndex(getAccessibilitySelectionEnd()); 6436 event.setItemCount(text.length()); 6437 } 6438 } break; 6439 } 6440 } 6441 6442 /** 6443 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6444 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6445 * This method is responsible for obtaining an accessibility node info from a 6446 * pool of reusable instances and calling 6447 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6448 * initialize the former. 6449 * <p> 6450 * Note: The client is responsible for recycling the obtained instance by calling 6451 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6452 * </p> 6453 * 6454 * @return A populated {@link AccessibilityNodeInfo}. 6455 * 6456 * @see AccessibilityNodeInfo 6457 */ 6458 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6459 if (mAccessibilityDelegate != null) { 6460 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6461 } else { 6462 return createAccessibilityNodeInfoInternal(); 6463 } 6464 } 6465 6466 /** 6467 * @see #createAccessibilityNodeInfo() 6468 * 6469 * @hide 6470 */ 6471 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6472 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6473 if (provider != null) { 6474 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6475 } else { 6476 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6477 onInitializeAccessibilityNodeInfo(info); 6478 return info; 6479 } 6480 } 6481 6482 /** 6483 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6484 * The base implementation sets: 6485 * <ul> 6486 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6487 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6488 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6489 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6490 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6491 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6492 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6493 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6494 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6495 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6496 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6497 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6498 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6499 * </ul> 6500 * <p> 6501 * Subclasses should override this method, call the super implementation, 6502 * and set additional attributes. 6503 * </p> 6504 * <p> 6505 * If an {@link AccessibilityDelegate} has been specified via calling 6506 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6507 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6508 * is responsible for handling this call. 6509 * </p> 6510 * 6511 * @param info The instance to initialize. 6512 */ 6513 @CallSuper 6514 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6515 if (mAccessibilityDelegate != null) { 6516 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6517 } else { 6518 onInitializeAccessibilityNodeInfoInternal(info); 6519 } 6520 } 6521 6522 /** 6523 * Gets the location of this view in screen coordinates. 6524 * 6525 * @param outRect The output location 6526 * @hide 6527 */ 6528 public void getBoundsOnScreen(Rect outRect) { 6529 getBoundsOnScreen(outRect, false); 6530 } 6531 6532 /** 6533 * Gets the location of this view in screen coordinates. 6534 * 6535 * @param outRect The output location 6536 * @param clipToParent Whether to clip child bounds to the parent ones. 6537 * @hide 6538 */ 6539 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6540 if (mAttachInfo == null) { 6541 return; 6542 } 6543 6544 RectF position = mAttachInfo.mTmpTransformRect; 6545 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6546 6547 if (!hasIdentityMatrix()) { 6548 getMatrix().mapRect(position); 6549 } 6550 6551 position.offset(mLeft, mTop); 6552 6553 ViewParent parent = mParent; 6554 while (parent instanceof View) { 6555 View parentView = (View) parent; 6556 6557 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6558 6559 if (clipToParent) { 6560 position.left = Math.max(position.left, 0); 6561 position.top = Math.max(position.top, 0); 6562 position.right = Math.min(position.right, parentView.getWidth()); 6563 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6564 } 6565 6566 if (!parentView.hasIdentityMatrix()) { 6567 parentView.getMatrix().mapRect(position); 6568 } 6569 6570 position.offset(parentView.mLeft, parentView.mTop); 6571 6572 parent = parentView.mParent; 6573 } 6574 6575 if (parent instanceof ViewRootImpl) { 6576 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6577 position.offset(0, -viewRootImpl.mCurScrollY); 6578 } 6579 6580 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6581 6582 outRect.set(Math.round(position.left), Math.round(position.top), 6583 Math.round(position.right), Math.round(position.bottom)); 6584 } 6585 6586 /** 6587 * Return the class name of this object to be used for accessibility purposes. 6588 * Subclasses should only override this if they are implementing something that 6589 * should be seen as a completely new class of view when used by accessibility, 6590 * unrelated to the class it is deriving from. This is used to fill in 6591 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6592 */ 6593 public CharSequence getAccessibilityClassName() { 6594 return View.class.getName(); 6595 } 6596 6597 /** 6598 * Called when assist structure is being retrieved from a view as part of 6599 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6600 * @param structure Fill in with structured view data. The default implementation 6601 * fills in all data that can be inferred from the view itself. 6602 */ 6603 public void onProvideStructure(ViewStructure structure) { 6604 final int id = mID; 6605 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6606 && (id&0x0000ffff) != 0) { 6607 String pkg, type, entry; 6608 try { 6609 final Resources res = getResources(); 6610 entry = res.getResourceEntryName(id); 6611 type = res.getResourceTypeName(id); 6612 pkg = res.getResourcePackageName(id); 6613 } catch (Resources.NotFoundException e) { 6614 entry = type = pkg = null; 6615 } 6616 structure.setId(id, pkg, type, entry); 6617 } else { 6618 structure.setId(id, null, null, null); 6619 } 6620 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6621 if (!hasIdentityMatrix()) { 6622 structure.setTransformation(getMatrix()); 6623 } 6624 structure.setElevation(getZ()); 6625 structure.setVisibility(getVisibility()); 6626 structure.setEnabled(isEnabled()); 6627 if (isClickable()) { 6628 structure.setClickable(true); 6629 } 6630 if (isFocusable()) { 6631 structure.setFocusable(true); 6632 } 6633 if (isFocused()) { 6634 structure.setFocused(true); 6635 } 6636 if (isAccessibilityFocused()) { 6637 structure.setAccessibilityFocused(true); 6638 } 6639 if (isSelected()) { 6640 structure.setSelected(true); 6641 } 6642 if (isActivated()) { 6643 structure.setActivated(true); 6644 } 6645 if (isLongClickable()) { 6646 structure.setLongClickable(true); 6647 } 6648 if (this instanceof Checkable) { 6649 structure.setCheckable(true); 6650 if (((Checkable)this).isChecked()) { 6651 structure.setChecked(true); 6652 } 6653 } 6654 if (isContextClickable()) { 6655 structure.setContextClickable(true); 6656 } 6657 structure.setClassName(getAccessibilityClassName().toString()); 6658 structure.setContentDescription(getContentDescription()); 6659 } 6660 6661 /** 6662 * Called when assist structure is being retrieved from a view as part of 6663 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6664 * generate additional virtual structure under this view. The defaullt implementation 6665 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6666 * view's virtual accessibility nodes, if any. You can override this for a more 6667 * optimal implementation providing this data. 6668 */ 6669 public void onProvideVirtualStructure(ViewStructure structure) { 6670 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6671 if (provider != null) { 6672 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6673 structure.setChildCount(1); 6674 ViewStructure root = structure.newChild(0); 6675 populateVirtualStructure(root, provider, info); 6676 info.recycle(); 6677 } 6678 } 6679 6680 private void populateVirtualStructure(ViewStructure structure, 6681 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6682 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6683 null, null, null); 6684 Rect rect = structure.getTempRect(); 6685 info.getBoundsInParent(rect); 6686 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6687 structure.setVisibility(VISIBLE); 6688 structure.setEnabled(info.isEnabled()); 6689 if (info.isClickable()) { 6690 structure.setClickable(true); 6691 } 6692 if (info.isFocusable()) { 6693 structure.setFocusable(true); 6694 } 6695 if (info.isFocused()) { 6696 structure.setFocused(true); 6697 } 6698 if (info.isAccessibilityFocused()) { 6699 structure.setAccessibilityFocused(true); 6700 } 6701 if (info.isSelected()) { 6702 structure.setSelected(true); 6703 } 6704 if (info.isLongClickable()) { 6705 structure.setLongClickable(true); 6706 } 6707 if (info.isCheckable()) { 6708 structure.setCheckable(true); 6709 if (info.isChecked()) { 6710 structure.setChecked(true); 6711 } 6712 } 6713 if (info.isContextClickable()) { 6714 structure.setContextClickable(true); 6715 } 6716 CharSequence cname = info.getClassName(); 6717 structure.setClassName(cname != null ? cname.toString() : null); 6718 structure.setContentDescription(info.getContentDescription()); 6719 if (info.getText() != null || info.getError() != null) { 6720 structure.setText(info.getText(), info.getTextSelectionStart(), 6721 info.getTextSelectionEnd()); 6722 } 6723 final int NCHILDREN = info.getChildCount(); 6724 if (NCHILDREN > 0) { 6725 structure.setChildCount(NCHILDREN); 6726 for (int i=0; i<NCHILDREN; i++) { 6727 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6728 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6729 ViewStructure child = structure.newChild(i); 6730 populateVirtualStructure(child, provider, cinfo); 6731 cinfo.recycle(); 6732 } 6733 } 6734 } 6735 6736 /** 6737 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6738 * implementation calls {@link #onProvideStructure} and 6739 * {@link #onProvideVirtualStructure}. 6740 */ 6741 public void dispatchProvideStructure(ViewStructure structure) { 6742 if (!isAssistBlocked()) { 6743 onProvideStructure(structure); 6744 onProvideVirtualStructure(structure); 6745 } else { 6746 structure.setClassName(getAccessibilityClassName().toString()); 6747 structure.setAssistBlocked(true); 6748 } 6749 } 6750 6751 /** 6752 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6753 * 6754 * Note: Called from the default {@link AccessibilityDelegate}. 6755 * 6756 * @hide 6757 */ 6758 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6759 if (mAttachInfo == null) { 6760 return; 6761 } 6762 6763 Rect bounds = mAttachInfo.mTmpInvalRect; 6764 6765 getDrawingRect(bounds); 6766 info.setBoundsInParent(bounds); 6767 6768 getBoundsOnScreen(bounds, true); 6769 info.setBoundsInScreen(bounds); 6770 6771 ViewParent parent = getParentForAccessibility(); 6772 if (parent instanceof View) { 6773 info.setParent((View) parent); 6774 } 6775 6776 if (mID != View.NO_ID) { 6777 View rootView = getRootView(); 6778 if (rootView == null) { 6779 rootView = this; 6780 } 6781 6782 View label = rootView.findLabelForView(this, mID); 6783 if (label != null) { 6784 info.setLabeledBy(label); 6785 } 6786 6787 if ((mAttachInfo.mAccessibilityFetchFlags 6788 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6789 && Resources.resourceHasPackage(mID)) { 6790 try { 6791 String viewId = getResources().getResourceName(mID); 6792 info.setViewIdResourceName(viewId); 6793 } catch (Resources.NotFoundException nfe) { 6794 /* ignore */ 6795 } 6796 } 6797 } 6798 6799 if (mLabelForId != View.NO_ID) { 6800 View rootView = getRootView(); 6801 if (rootView == null) { 6802 rootView = this; 6803 } 6804 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6805 if (labeled != null) { 6806 info.setLabelFor(labeled); 6807 } 6808 } 6809 6810 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6811 View rootView = getRootView(); 6812 if (rootView == null) { 6813 rootView = this; 6814 } 6815 View next = rootView.findViewInsideOutShouldExist(this, 6816 mAccessibilityTraversalBeforeId); 6817 if (next != null && next.includeForAccessibility()) { 6818 info.setTraversalBefore(next); 6819 } 6820 } 6821 6822 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6823 View rootView = getRootView(); 6824 if (rootView == null) { 6825 rootView = this; 6826 } 6827 View next = rootView.findViewInsideOutShouldExist(this, 6828 mAccessibilityTraversalAfterId); 6829 if (next != null && next.includeForAccessibility()) { 6830 info.setTraversalAfter(next); 6831 } 6832 } 6833 6834 info.setVisibleToUser(isVisibleToUser()); 6835 6836 if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags 6837 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) { 6838 info.setImportantForAccessibility(isImportantForAccessibility()); 6839 } else { 6840 info.setImportantForAccessibility(true); 6841 } 6842 6843 info.setPackageName(mContext.getPackageName()); 6844 info.setClassName(getAccessibilityClassName()); 6845 info.setContentDescription(getContentDescription()); 6846 6847 info.setEnabled(isEnabled()); 6848 info.setClickable(isClickable()); 6849 info.setFocusable(isFocusable()); 6850 info.setFocused(isFocused()); 6851 info.setAccessibilityFocused(isAccessibilityFocused()); 6852 info.setSelected(isSelected()); 6853 info.setLongClickable(isLongClickable()); 6854 info.setContextClickable(isContextClickable()); 6855 info.setLiveRegion(getAccessibilityLiveRegion()); 6856 6857 // TODO: These make sense only if we are in an AdapterView but all 6858 // views can be selected. Maybe from accessibility perspective 6859 // we should report as selectable view in an AdapterView. 6860 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6861 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6862 6863 if (isFocusable()) { 6864 if (isFocused()) { 6865 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6866 } else { 6867 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6868 } 6869 } 6870 6871 if (!isAccessibilityFocused()) { 6872 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6873 } else { 6874 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6875 } 6876 6877 if (isClickable() && isEnabled()) { 6878 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6879 } 6880 6881 if (isLongClickable() && isEnabled()) { 6882 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6883 } 6884 6885 if (isContextClickable() && isEnabled()) { 6886 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6887 } 6888 6889 CharSequence text = getIterableTextForAccessibility(); 6890 if (text != null && text.length() > 0) { 6891 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6892 6893 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6894 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6895 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6896 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6897 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6898 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6899 } 6900 6901 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6902 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6903 } 6904 6905 /** 6906 * Determine the order in which this view will be drawn relative to its siblings for a11y 6907 * 6908 * @param info The info whose drawing order should be populated 6909 */ 6910 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6911 /* 6912 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6913 * drawing order may not be well-defined, and some Views with custom drawing order may 6914 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6915 */ 6916 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6917 info.setDrawingOrder(0); 6918 return; 6919 } 6920 int drawingOrderInParent = 1; 6921 // Iterate up the hierarchy if parents are not important for a11y 6922 View viewAtDrawingLevel = this; 6923 final ViewParent parent = getParentForAccessibility(); 6924 while (viewAtDrawingLevel != parent) { 6925 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6926 if (!(currentParent instanceof ViewGroup)) { 6927 // Should only happen for the Decor 6928 drawingOrderInParent = 0; 6929 break; 6930 } else { 6931 final ViewGroup parentGroup = (ViewGroup) currentParent; 6932 final int childCount = parentGroup.getChildCount(); 6933 if (childCount > 1) { 6934 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6935 if (preorderedList != null) { 6936 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6937 for (int i = 0; i < childDrawIndex; i++) { 6938 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6939 } 6940 } else { 6941 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 6942 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 6943 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 6944 .getChildDrawingOrder(childCount, childIndex) : childIndex; 6945 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 6946 if (childDrawIndex != 0) { 6947 for (int i = 0; i < numChildrenToIterate; i++) { 6948 final int otherDrawIndex = (customOrder ? 6949 parentGroup.getChildDrawingOrder(childCount, i) : i); 6950 if (otherDrawIndex < childDrawIndex) { 6951 drawingOrderInParent += 6952 numViewsForAccessibility(parentGroup.getChildAt(i)); 6953 } 6954 } 6955 } 6956 } 6957 } 6958 } 6959 viewAtDrawingLevel = (View) currentParent; 6960 } 6961 info.setDrawingOrder(drawingOrderInParent); 6962 } 6963 6964 private static int numViewsForAccessibility(View view) { 6965 if (view != null) { 6966 if (view.includeForAccessibility()) { 6967 return 1; 6968 } else if (view instanceof ViewGroup) { 6969 return ((ViewGroup) view).getNumChildrenForAccessibility(); 6970 } 6971 } 6972 return 0; 6973 } 6974 6975 private View findLabelForView(View view, int labeledId) { 6976 if (mMatchLabelForPredicate == null) { 6977 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6978 } 6979 mMatchLabelForPredicate.mLabeledId = labeledId; 6980 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6981 } 6982 6983 /** 6984 * Computes whether this view is visible to the user. Such a view is 6985 * attached, visible, all its predecessors are visible, it is not clipped 6986 * entirely by its predecessors, and has an alpha greater than zero. 6987 * 6988 * @return Whether the view is visible on the screen. 6989 * 6990 * @hide 6991 */ 6992 protected boolean isVisibleToUser() { 6993 return isVisibleToUser(null); 6994 } 6995 6996 /** 6997 * Computes whether the given portion of this view is visible to the user. 6998 * Such a view is attached, visible, all its predecessors are visible, 6999 * has an alpha greater than zero, and the specified portion is not 7000 * clipped entirely by its predecessors. 7001 * 7002 * @param boundInView the portion of the view to test; coordinates should be relative; may be 7003 * <code>null</code>, and the entire view will be tested in this case. 7004 * When <code>true</code> is returned by the function, the actual visible 7005 * region will be stored in this parameter; that is, if boundInView is fully 7006 * contained within the view, no modification will be made, otherwise regions 7007 * outside of the visible area of the view will be clipped. 7008 * 7009 * @return Whether the specified portion of the view is visible on the screen. 7010 * 7011 * @hide 7012 */ 7013 protected boolean isVisibleToUser(Rect boundInView) { 7014 if (mAttachInfo != null) { 7015 // Attached to invisible window means this view is not visible. 7016 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 7017 return false; 7018 } 7019 // An invisible predecessor or one with alpha zero means 7020 // that this view is not visible to the user. 7021 Object current = this; 7022 while (current instanceof View) { 7023 View view = (View) current; 7024 // We have attach info so this view is attached and there is no 7025 // need to check whether we reach to ViewRootImpl on the way up. 7026 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 7027 view.getVisibility() != VISIBLE) { 7028 return false; 7029 } 7030 current = view.mParent; 7031 } 7032 // Check if the view is entirely covered by its predecessors. 7033 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7034 Point offset = mAttachInfo.mPoint; 7035 if (!getGlobalVisibleRect(visibleRect, offset)) { 7036 return false; 7037 } 7038 // Check if the visible portion intersects the rectangle of interest. 7039 if (boundInView != null) { 7040 visibleRect.offset(-offset.x, -offset.y); 7041 return boundInView.intersect(visibleRect); 7042 } 7043 return true; 7044 } 7045 return false; 7046 } 7047 7048 /** 7049 * Returns the delegate for implementing accessibility support via 7050 * composition. For more details see {@link AccessibilityDelegate}. 7051 * 7052 * @return The delegate, or null if none set. 7053 * 7054 * @hide 7055 */ 7056 public AccessibilityDelegate getAccessibilityDelegate() { 7057 return mAccessibilityDelegate; 7058 } 7059 7060 /** 7061 * Sets a delegate for implementing accessibility support via composition 7062 * (as opposed to inheritance). For more details, see 7063 * {@link AccessibilityDelegate}. 7064 * <p> 7065 * <strong>Note:</strong> On platform versions prior to 7066 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7067 * views in the {@code android.widget.*} package are called <i>before</i> 7068 * host methods. This prevents certain properties such as class name from 7069 * being modified by overriding 7070 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7071 * as any changes will be overwritten by the host class. 7072 * <p> 7073 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7074 * methods are called <i>after</i> host methods, which all properties to be 7075 * modified without being overwritten by the host class. 7076 * 7077 * @param delegate the object to which accessibility method calls should be 7078 * delegated 7079 * @see AccessibilityDelegate 7080 */ 7081 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7082 mAccessibilityDelegate = delegate; 7083 } 7084 7085 /** 7086 * Gets the provider for managing a virtual view hierarchy rooted at this View 7087 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7088 * that explore the window content. 7089 * <p> 7090 * If this method returns an instance, this instance is responsible for managing 7091 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7092 * View including the one representing the View itself. Similarly the returned 7093 * instance is responsible for performing accessibility actions on any virtual 7094 * view or the root view itself. 7095 * </p> 7096 * <p> 7097 * If an {@link AccessibilityDelegate} has been specified via calling 7098 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7099 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7100 * is responsible for handling this call. 7101 * </p> 7102 * 7103 * @return The provider. 7104 * 7105 * @see AccessibilityNodeProvider 7106 */ 7107 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7108 if (mAccessibilityDelegate != null) { 7109 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7110 } else { 7111 return null; 7112 } 7113 } 7114 7115 /** 7116 * Gets the unique identifier of this view on the screen for accessibility purposes. 7117 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7118 * 7119 * @return The view accessibility id. 7120 * 7121 * @hide 7122 */ 7123 public int getAccessibilityViewId() { 7124 if (mAccessibilityViewId == NO_ID) { 7125 mAccessibilityViewId = sNextAccessibilityViewId++; 7126 } 7127 return mAccessibilityViewId; 7128 } 7129 7130 /** 7131 * Gets the unique identifier of the window in which this View reseides. 7132 * 7133 * @return The window accessibility id. 7134 * 7135 * @hide 7136 */ 7137 public int getAccessibilityWindowId() { 7138 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7139 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7140 } 7141 7142 /** 7143 * Returns the {@link View}'s content description. 7144 * <p> 7145 * <strong>Note:</strong> Do not override this method, as it will have no 7146 * effect on the content description presented to accessibility services. 7147 * You must call {@link #setContentDescription(CharSequence)} to modify the 7148 * content description. 7149 * 7150 * @return the content description 7151 * @see #setContentDescription(CharSequence) 7152 * @attr ref android.R.styleable#View_contentDescription 7153 */ 7154 @ViewDebug.ExportedProperty(category = "accessibility") 7155 public CharSequence getContentDescription() { 7156 return mContentDescription; 7157 } 7158 7159 /** 7160 * Sets the {@link View}'s content description. 7161 * <p> 7162 * A content description briefly describes the view and is primarily used 7163 * for accessibility support to determine how a view should be presented to 7164 * the user. In the case of a view with no textual representation, such as 7165 * {@link android.widget.ImageButton}, a useful content description 7166 * explains what the view does. For example, an image button with a phone 7167 * icon that is used to place a call may use "Call" as its content 7168 * description. An image of a floppy disk that is used to save a file may 7169 * use "Save". 7170 * 7171 * @param contentDescription The content description. 7172 * @see #getContentDescription() 7173 * @attr ref android.R.styleable#View_contentDescription 7174 */ 7175 @RemotableViewMethod 7176 public void setContentDescription(CharSequence contentDescription) { 7177 if (mContentDescription == null) { 7178 if (contentDescription == null) { 7179 return; 7180 } 7181 } else if (mContentDescription.equals(contentDescription)) { 7182 return; 7183 } 7184 mContentDescription = contentDescription; 7185 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7186 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7187 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7188 notifySubtreeAccessibilityStateChangedIfNeeded(); 7189 } else { 7190 notifyViewAccessibilityStateChangedIfNeeded( 7191 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7192 } 7193 } 7194 7195 /** 7196 * Sets the id of a view before which this one is visited in accessibility traversal. 7197 * A screen-reader must visit the content of this view before the content of the one 7198 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7199 * will traverse the entire content of B before traversing the entire content of A, 7200 * regardles of what traversal strategy it is using. 7201 * <p> 7202 * Views that do not have specified before/after relationships are traversed in order 7203 * determined by the screen-reader. 7204 * </p> 7205 * <p> 7206 * Setting that this view is before a view that is not important for accessibility 7207 * or if this view is not important for accessibility will have no effect as the 7208 * screen-reader is not aware of unimportant views. 7209 * </p> 7210 * 7211 * @param beforeId The id of a view this one precedes in accessibility traversal. 7212 * 7213 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7214 * 7215 * @see #setImportantForAccessibility(int) 7216 */ 7217 @RemotableViewMethod 7218 public void setAccessibilityTraversalBefore(int beforeId) { 7219 if (mAccessibilityTraversalBeforeId == beforeId) { 7220 return; 7221 } 7222 mAccessibilityTraversalBeforeId = beforeId; 7223 notifyViewAccessibilityStateChangedIfNeeded( 7224 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7225 } 7226 7227 /** 7228 * Gets the id of a view before which this one is visited in accessibility traversal. 7229 * 7230 * @return The id of a view this one precedes in accessibility traversal if 7231 * specified, otherwise {@link #NO_ID}. 7232 * 7233 * @see #setAccessibilityTraversalBefore(int) 7234 */ 7235 public int getAccessibilityTraversalBefore() { 7236 return mAccessibilityTraversalBeforeId; 7237 } 7238 7239 /** 7240 * Sets the id of a view after which this one is visited in accessibility traversal. 7241 * A screen-reader must visit the content of the other view before the content of this 7242 * one. For example, if view B is set to be after view A, then a screen-reader 7243 * will traverse the entire content of A before traversing the entire content of B, 7244 * regardles of what traversal strategy it is using. 7245 * <p> 7246 * Views that do not have specified before/after relationships are traversed in order 7247 * determined by the screen-reader. 7248 * </p> 7249 * <p> 7250 * Setting that this view is after a view that is not important for accessibility 7251 * or if this view is not important for accessibility will have no effect as the 7252 * screen-reader is not aware of unimportant views. 7253 * </p> 7254 * 7255 * @param afterId The id of a view this one succedees in accessibility traversal. 7256 * 7257 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7258 * 7259 * @see #setImportantForAccessibility(int) 7260 */ 7261 @RemotableViewMethod 7262 public void setAccessibilityTraversalAfter(int afterId) { 7263 if (mAccessibilityTraversalAfterId == afterId) { 7264 return; 7265 } 7266 mAccessibilityTraversalAfterId = afterId; 7267 notifyViewAccessibilityStateChangedIfNeeded( 7268 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7269 } 7270 7271 /** 7272 * Gets the id of a view after which this one is visited in accessibility traversal. 7273 * 7274 * @return The id of a view this one succeedes in accessibility traversal if 7275 * specified, otherwise {@link #NO_ID}. 7276 * 7277 * @see #setAccessibilityTraversalAfter(int) 7278 */ 7279 public int getAccessibilityTraversalAfter() { 7280 return mAccessibilityTraversalAfterId; 7281 } 7282 7283 /** 7284 * Gets the id of a view for which this view serves as a label for 7285 * accessibility purposes. 7286 * 7287 * @return The labeled view id. 7288 */ 7289 @ViewDebug.ExportedProperty(category = "accessibility") 7290 public int getLabelFor() { 7291 return mLabelForId; 7292 } 7293 7294 /** 7295 * Sets the id of a view for which this view serves as a label for 7296 * accessibility purposes. 7297 * 7298 * @param id The labeled view id. 7299 */ 7300 @RemotableViewMethod 7301 public void setLabelFor(@IdRes int id) { 7302 if (mLabelForId == id) { 7303 return; 7304 } 7305 mLabelForId = id; 7306 if (mLabelForId != View.NO_ID 7307 && mID == View.NO_ID) { 7308 mID = generateViewId(); 7309 } 7310 notifyViewAccessibilityStateChangedIfNeeded( 7311 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7312 } 7313 7314 /** 7315 * Invoked whenever this view loses focus, either by losing window focus or by losing 7316 * focus within its window. This method can be used to clear any state tied to the 7317 * focus. For instance, if a button is held pressed with the trackball and the window 7318 * loses focus, this method can be used to cancel the press. 7319 * 7320 * Subclasses of View overriding this method should always call super.onFocusLost(). 7321 * 7322 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7323 * @see #onWindowFocusChanged(boolean) 7324 * 7325 * @hide pending API council approval 7326 */ 7327 @CallSuper 7328 protected void onFocusLost() { 7329 resetPressedState(); 7330 } 7331 7332 private void resetPressedState() { 7333 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7334 return; 7335 } 7336 7337 if (isPressed()) { 7338 setPressed(false); 7339 7340 if (!mHasPerformedLongPress) { 7341 removeLongPressCallback(); 7342 } 7343 } 7344 } 7345 7346 /** 7347 * Returns true if this view has focus 7348 * 7349 * @return True if this view has focus, false otherwise. 7350 */ 7351 @ViewDebug.ExportedProperty(category = "focus") 7352 public boolean isFocused() { 7353 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7354 } 7355 7356 /** 7357 * Find the view in the hierarchy rooted at this view that currently has 7358 * focus. 7359 * 7360 * @return The view that currently has focus, or null if no focused view can 7361 * be found. 7362 */ 7363 public View findFocus() { 7364 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7365 } 7366 7367 /** 7368 * Indicates whether this view is one of the set of scrollable containers in 7369 * its window. 7370 * 7371 * @return whether this view is one of the set of scrollable containers in 7372 * its window 7373 * 7374 * @attr ref android.R.styleable#View_isScrollContainer 7375 */ 7376 public boolean isScrollContainer() { 7377 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7378 } 7379 7380 /** 7381 * Change whether this view is one of the set of scrollable containers in 7382 * its window. This will be used to determine whether the window can 7383 * resize or must pan when a soft input area is open -- scrollable 7384 * containers allow the window to use resize mode since the container 7385 * will appropriately shrink. 7386 * 7387 * @attr ref android.R.styleable#View_isScrollContainer 7388 */ 7389 public void setScrollContainer(boolean isScrollContainer) { 7390 if (isScrollContainer) { 7391 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7392 mAttachInfo.mScrollContainers.add(this); 7393 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7394 } 7395 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7396 } else { 7397 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7398 mAttachInfo.mScrollContainers.remove(this); 7399 } 7400 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7401 } 7402 } 7403 7404 /** 7405 * Returns the quality of the drawing cache. 7406 * 7407 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7408 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7409 * 7410 * @see #setDrawingCacheQuality(int) 7411 * @see #setDrawingCacheEnabled(boolean) 7412 * @see #isDrawingCacheEnabled() 7413 * 7414 * @attr ref android.R.styleable#View_drawingCacheQuality 7415 */ 7416 @DrawingCacheQuality 7417 public int getDrawingCacheQuality() { 7418 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7419 } 7420 7421 /** 7422 * Set the drawing cache quality of this view. This value is used only when the 7423 * drawing cache is enabled 7424 * 7425 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7426 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7427 * 7428 * @see #getDrawingCacheQuality() 7429 * @see #setDrawingCacheEnabled(boolean) 7430 * @see #isDrawingCacheEnabled() 7431 * 7432 * @attr ref android.R.styleable#View_drawingCacheQuality 7433 */ 7434 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7435 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7436 } 7437 7438 /** 7439 * Returns whether the screen should remain on, corresponding to the current 7440 * value of {@link #KEEP_SCREEN_ON}. 7441 * 7442 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7443 * 7444 * @see #setKeepScreenOn(boolean) 7445 * 7446 * @attr ref android.R.styleable#View_keepScreenOn 7447 */ 7448 public boolean getKeepScreenOn() { 7449 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7450 } 7451 7452 /** 7453 * Controls whether the screen should remain on, modifying the 7454 * value of {@link #KEEP_SCREEN_ON}. 7455 * 7456 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7457 * 7458 * @see #getKeepScreenOn() 7459 * 7460 * @attr ref android.R.styleable#View_keepScreenOn 7461 */ 7462 public void setKeepScreenOn(boolean keepScreenOn) { 7463 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7464 } 7465 7466 /** 7467 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7468 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7469 * 7470 * @attr ref android.R.styleable#View_nextFocusLeft 7471 */ 7472 public int getNextFocusLeftId() { 7473 return mNextFocusLeftId; 7474 } 7475 7476 /** 7477 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7478 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7479 * decide automatically. 7480 * 7481 * @attr ref android.R.styleable#View_nextFocusLeft 7482 */ 7483 public void setNextFocusLeftId(int nextFocusLeftId) { 7484 mNextFocusLeftId = nextFocusLeftId; 7485 } 7486 7487 /** 7488 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7489 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7490 * 7491 * @attr ref android.R.styleable#View_nextFocusRight 7492 */ 7493 public int getNextFocusRightId() { 7494 return mNextFocusRightId; 7495 } 7496 7497 /** 7498 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7499 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7500 * decide automatically. 7501 * 7502 * @attr ref android.R.styleable#View_nextFocusRight 7503 */ 7504 public void setNextFocusRightId(int nextFocusRightId) { 7505 mNextFocusRightId = nextFocusRightId; 7506 } 7507 7508 /** 7509 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7510 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7511 * 7512 * @attr ref android.R.styleable#View_nextFocusUp 7513 */ 7514 public int getNextFocusUpId() { 7515 return mNextFocusUpId; 7516 } 7517 7518 /** 7519 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7520 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7521 * decide automatically. 7522 * 7523 * @attr ref android.R.styleable#View_nextFocusUp 7524 */ 7525 public void setNextFocusUpId(int nextFocusUpId) { 7526 mNextFocusUpId = nextFocusUpId; 7527 } 7528 7529 /** 7530 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7531 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7532 * 7533 * @attr ref android.R.styleable#View_nextFocusDown 7534 */ 7535 public int getNextFocusDownId() { 7536 return mNextFocusDownId; 7537 } 7538 7539 /** 7540 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7541 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7542 * decide automatically. 7543 * 7544 * @attr ref android.R.styleable#View_nextFocusDown 7545 */ 7546 public void setNextFocusDownId(int nextFocusDownId) { 7547 mNextFocusDownId = nextFocusDownId; 7548 } 7549 7550 /** 7551 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7552 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7553 * 7554 * @attr ref android.R.styleable#View_nextFocusForward 7555 */ 7556 public int getNextFocusForwardId() { 7557 return mNextFocusForwardId; 7558 } 7559 7560 /** 7561 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7562 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7563 * decide automatically. 7564 * 7565 * @attr ref android.R.styleable#View_nextFocusForward 7566 */ 7567 public void setNextFocusForwardId(int nextFocusForwardId) { 7568 mNextFocusForwardId = nextFocusForwardId; 7569 } 7570 7571 /** 7572 * Returns the visibility of this view and all of its ancestors 7573 * 7574 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7575 */ 7576 public boolean isShown() { 7577 View current = this; 7578 //noinspection ConstantConditions 7579 do { 7580 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7581 return false; 7582 } 7583 ViewParent parent = current.mParent; 7584 if (parent == null) { 7585 return false; // We are not attached to the view root 7586 } 7587 if (!(parent instanceof View)) { 7588 return true; 7589 } 7590 current = (View) parent; 7591 } while (current != null); 7592 7593 return false; 7594 } 7595 7596 /** 7597 * Called by the view hierarchy when the content insets for a window have 7598 * changed, to allow it to adjust its content to fit within those windows. 7599 * The content insets tell you the space that the status bar, input method, 7600 * and other system windows infringe on the application's window. 7601 * 7602 * <p>You do not normally need to deal with this function, since the default 7603 * window decoration given to applications takes care of applying it to the 7604 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7605 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7606 * and your content can be placed under those system elements. You can then 7607 * use this method within your view hierarchy if you have parts of your UI 7608 * which you would like to ensure are not being covered. 7609 * 7610 * <p>The default implementation of this method simply applies the content 7611 * insets to the view's padding, consuming that content (modifying the 7612 * insets to be 0), and returning true. This behavior is off by default, but can 7613 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7614 * 7615 * <p>This function's traversal down the hierarchy is depth-first. The same content 7616 * insets object is propagated down the hierarchy, so any changes made to it will 7617 * be seen by all following views (including potentially ones above in 7618 * the hierarchy since this is a depth-first traversal). The first view 7619 * that returns true will abort the entire traversal. 7620 * 7621 * <p>The default implementation works well for a situation where it is 7622 * used with a container that covers the entire window, allowing it to 7623 * apply the appropriate insets to its content on all edges. If you need 7624 * a more complicated layout (such as two different views fitting system 7625 * windows, one on the top of the window, and one on the bottom), 7626 * you can override the method and handle the insets however you would like. 7627 * Note that the insets provided by the framework are always relative to the 7628 * far edges of the window, not accounting for the location of the called view 7629 * within that window. (In fact when this method is called you do not yet know 7630 * where the layout will place the view, as it is done before layout happens.) 7631 * 7632 * <p>Note: unlike many View methods, there is no dispatch phase to this 7633 * call. If you are overriding it in a ViewGroup and want to allow the 7634 * call to continue to your children, you must be sure to call the super 7635 * implementation. 7636 * 7637 * <p>Here is a sample layout that makes use of fitting system windows 7638 * to have controls for a video view placed inside of the window decorations 7639 * that it hides and shows. This can be used with code like the second 7640 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7641 * 7642 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7643 * 7644 * @param insets Current content insets of the window. Prior to 7645 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7646 * the insets or else you and Android will be unhappy. 7647 * 7648 * @return {@code true} if this view applied the insets and it should not 7649 * continue propagating further down the hierarchy, {@code false} otherwise. 7650 * @see #getFitsSystemWindows() 7651 * @see #setFitsSystemWindows(boolean) 7652 * @see #setSystemUiVisibility(int) 7653 * 7654 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7655 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7656 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7657 * to implement handling their own insets. 7658 */ 7659 protected boolean fitSystemWindows(Rect insets) { 7660 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7661 if (insets == null) { 7662 // Null insets by definition have already been consumed. 7663 // This call cannot apply insets since there are none to apply, 7664 // so return false. 7665 return false; 7666 } 7667 // If we're not in the process of dispatching the newer apply insets call, 7668 // that means we're not in the compatibility path. Dispatch into the newer 7669 // apply insets path and take things from there. 7670 try { 7671 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7672 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7673 } finally { 7674 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7675 } 7676 } else { 7677 // We're being called from the newer apply insets path. 7678 // Perform the standard fallback behavior. 7679 return fitSystemWindowsInt(insets); 7680 } 7681 } 7682 7683 private boolean fitSystemWindowsInt(Rect insets) { 7684 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7685 mUserPaddingStart = UNDEFINED_PADDING; 7686 mUserPaddingEnd = UNDEFINED_PADDING; 7687 Rect localInsets = sThreadLocal.get(); 7688 if (localInsets == null) { 7689 localInsets = new Rect(); 7690 sThreadLocal.set(localInsets); 7691 } 7692 boolean res = computeFitSystemWindows(insets, localInsets); 7693 mUserPaddingLeftInitial = localInsets.left; 7694 mUserPaddingRightInitial = localInsets.right; 7695 internalSetPadding(localInsets.left, localInsets.top, 7696 localInsets.right, localInsets.bottom); 7697 return res; 7698 } 7699 return false; 7700 } 7701 7702 /** 7703 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7704 * 7705 * <p>This method should be overridden by views that wish to apply a policy different from or 7706 * in addition to the default behavior. Clients that wish to force a view subtree 7707 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7708 * 7709 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7710 * it will be called during dispatch instead of this method. The listener may optionally 7711 * call this method from its own implementation if it wishes to apply the view's default 7712 * insets policy in addition to its own.</p> 7713 * 7714 * <p>Implementations of this method should either return the insets parameter unchanged 7715 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7716 * that this view applied itself. This allows new inset types added in future platform 7717 * versions to pass through existing implementations unchanged without being erroneously 7718 * consumed.</p> 7719 * 7720 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7721 * property is set then the view will consume the system window insets and apply them 7722 * as padding for the view.</p> 7723 * 7724 * @param insets Insets to apply 7725 * @return The supplied insets with any applied insets consumed 7726 */ 7727 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7728 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7729 // We weren't called from within a direct call to fitSystemWindows, 7730 // call into it as a fallback in case we're in a class that overrides it 7731 // and has logic to perform. 7732 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7733 return insets.consumeSystemWindowInsets(); 7734 } 7735 } else { 7736 // We were called from within a direct call to fitSystemWindows. 7737 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7738 return insets.consumeSystemWindowInsets(); 7739 } 7740 } 7741 return insets; 7742 } 7743 7744 /** 7745 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7746 * window insets to this view. The listener's 7747 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7748 * method will be called instead of the view's 7749 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7750 * 7751 * @param listener Listener to set 7752 * 7753 * @see #onApplyWindowInsets(WindowInsets) 7754 */ 7755 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7756 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7757 } 7758 7759 /** 7760 * Request to apply the given window insets to this view or another view in its subtree. 7761 * 7762 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7763 * obscured by window decorations or overlays. This can include the status and navigation bars, 7764 * action bars, input methods and more. New inset categories may be added in the future. 7765 * The method returns the insets provided minus any that were applied by this view or its 7766 * children.</p> 7767 * 7768 * <p>Clients wishing to provide custom behavior should override the 7769 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7770 * {@link OnApplyWindowInsetsListener} via the 7771 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7772 * method.</p> 7773 * 7774 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7775 * </p> 7776 * 7777 * @param insets Insets to apply 7778 * @return The provided insets minus the insets that were consumed 7779 */ 7780 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7781 try { 7782 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7783 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7784 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7785 } else { 7786 return onApplyWindowInsets(insets); 7787 } 7788 } finally { 7789 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7790 } 7791 } 7792 7793 /** 7794 * Compute the view's coordinate within the surface. 7795 * 7796 * <p>Computes the coordinates of this view in its surface. The argument 7797 * must be an array of two integers. After the method returns, the array 7798 * contains the x and y location in that order.</p> 7799 * @hide 7800 * @param location an array of two integers in which to hold the coordinates 7801 */ 7802 public void getLocationInSurface(@Size(2) int[] location) { 7803 getLocationInWindow(location); 7804 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7805 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7806 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7807 } 7808 } 7809 7810 /** 7811 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7812 * only available if the view is attached. 7813 * 7814 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7815 */ 7816 public WindowInsets getRootWindowInsets() { 7817 if (mAttachInfo != null) { 7818 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7819 } 7820 return null; 7821 } 7822 7823 /** 7824 * @hide Compute the insets that should be consumed by this view and the ones 7825 * that should propagate to those under it. 7826 */ 7827 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7828 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7829 || mAttachInfo == null 7830 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7831 && !mAttachInfo.mOverscanRequested)) { 7832 outLocalInsets.set(inoutInsets); 7833 inoutInsets.set(0, 0, 0, 0); 7834 return true; 7835 } else { 7836 // The application wants to take care of fitting system window for 7837 // the content... however we still need to take care of any overscan here. 7838 final Rect overscan = mAttachInfo.mOverscanInsets; 7839 outLocalInsets.set(overscan); 7840 inoutInsets.left -= overscan.left; 7841 inoutInsets.top -= overscan.top; 7842 inoutInsets.right -= overscan.right; 7843 inoutInsets.bottom -= overscan.bottom; 7844 return false; 7845 } 7846 } 7847 7848 /** 7849 * Compute insets that should be consumed by this view and the ones that should propagate 7850 * to those under it. 7851 * 7852 * @param in Insets currently being processed by this View, likely received as a parameter 7853 * to {@link #onApplyWindowInsets(WindowInsets)}. 7854 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7855 * by this view 7856 * @return Insets that should be passed along to views under this one 7857 */ 7858 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7859 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7860 || mAttachInfo == null 7861 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7862 outLocalInsets.set(in.getSystemWindowInsets()); 7863 return in.consumeSystemWindowInsets(); 7864 } else { 7865 outLocalInsets.set(0, 0, 0, 0); 7866 return in; 7867 } 7868 } 7869 7870 /** 7871 * Sets whether or not this view should account for system screen decorations 7872 * such as the status bar and inset its content; that is, controlling whether 7873 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7874 * executed. See that method for more details. 7875 * 7876 * <p>Note that if you are providing your own implementation of 7877 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7878 * flag to true -- your implementation will be overriding the default 7879 * implementation that checks this flag. 7880 * 7881 * @param fitSystemWindows If true, then the default implementation of 7882 * {@link #fitSystemWindows(Rect)} will be executed. 7883 * 7884 * @attr ref android.R.styleable#View_fitsSystemWindows 7885 * @see #getFitsSystemWindows() 7886 * @see #fitSystemWindows(Rect) 7887 * @see #setSystemUiVisibility(int) 7888 */ 7889 public void setFitsSystemWindows(boolean fitSystemWindows) { 7890 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7891 } 7892 7893 /** 7894 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7895 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7896 * will be executed. 7897 * 7898 * @return {@code true} if the default implementation of 7899 * {@link #fitSystemWindows(Rect)} will be executed. 7900 * 7901 * @attr ref android.R.styleable#View_fitsSystemWindows 7902 * @see #setFitsSystemWindows(boolean) 7903 * @see #fitSystemWindows(Rect) 7904 * @see #setSystemUiVisibility(int) 7905 */ 7906 @ViewDebug.ExportedProperty 7907 public boolean getFitsSystemWindows() { 7908 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7909 } 7910 7911 /** @hide */ 7912 public boolean fitsSystemWindows() { 7913 return getFitsSystemWindows(); 7914 } 7915 7916 /** 7917 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7918 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7919 */ 7920 public void requestFitSystemWindows() { 7921 if (mParent != null) { 7922 mParent.requestFitSystemWindows(); 7923 } 7924 } 7925 7926 /** 7927 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7928 */ 7929 public void requestApplyInsets() { 7930 requestFitSystemWindows(); 7931 } 7932 7933 /** 7934 * For use by PhoneWindow to make its own system window fitting optional. 7935 * @hide 7936 */ 7937 public void makeOptionalFitsSystemWindows() { 7938 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7939 } 7940 7941 /** 7942 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7943 * treat them as such. 7944 * @hide 7945 */ 7946 public void getOutsets(Rect outOutsetRect) { 7947 if (mAttachInfo != null) { 7948 outOutsetRect.set(mAttachInfo.mOutsets); 7949 } else { 7950 outOutsetRect.setEmpty(); 7951 } 7952 } 7953 7954 /** 7955 * Returns the visibility status for this view. 7956 * 7957 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7958 * @attr ref android.R.styleable#View_visibility 7959 */ 7960 @ViewDebug.ExportedProperty(mapping = { 7961 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7962 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7963 @ViewDebug.IntToString(from = GONE, to = "GONE") 7964 }) 7965 @Visibility 7966 public int getVisibility() { 7967 return mViewFlags & VISIBILITY_MASK; 7968 } 7969 7970 /** 7971 * Set the enabled state of this view. 7972 * 7973 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7974 * @attr ref android.R.styleable#View_visibility 7975 */ 7976 @RemotableViewMethod 7977 public void setVisibility(@Visibility int visibility) { 7978 setFlags(visibility, VISIBILITY_MASK); 7979 } 7980 7981 /** 7982 * Returns the enabled status for this view. The interpretation of the 7983 * enabled state varies by subclass. 7984 * 7985 * @return True if this view is enabled, false otherwise. 7986 */ 7987 @ViewDebug.ExportedProperty 7988 public boolean isEnabled() { 7989 return (mViewFlags & ENABLED_MASK) == ENABLED; 7990 } 7991 7992 /** 7993 * Set the enabled state of this view. The interpretation of the enabled 7994 * state varies by subclass. 7995 * 7996 * @param enabled True if this view is enabled, false otherwise. 7997 */ 7998 @RemotableViewMethod 7999 public void setEnabled(boolean enabled) { 8000 if (enabled == isEnabled()) return; 8001 8002 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 8003 8004 /* 8005 * The View most likely has to change its appearance, so refresh 8006 * the drawable state. 8007 */ 8008 refreshDrawableState(); 8009 8010 // Invalidate too, since the default behavior for views is to be 8011 // be drawn at 50% alpha rather than to change the drawable. 8012 invalidate(true); 8013 8014 if (!enabled) { 8015 cancelPendingInputEvents(); 8016 } 8017 } 8018 8019 /** 8020 * Set whether this view can receive the focus. 8021 * 8022 * Setting this to false will also ensure that this view is not focusable 8023 * in touch mode. 8024 * 8025 * @param focusable If true, this view can receive the focus. 8026 * 8027 * @see #setFocusableInTouchMode(boolean) 8028 * @attr ref android.R.styleable#View_focusable 8029 */ 8030 public void setFocusable(boolean focusable) { 8031 if (!focusable) { 8032 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 8033 } 8034 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8035 } 8036 8037 /** 8038 * Set whether this view can receive focus while in touch mode. 8039 * 8040 * Setting this to true will also ensure that this view is focusable. 8041 * 8042 * @param focusableInTouchMode If true, this view can receive the focus while 8043 * in touch mode. 8044 * 8045 * @see #setFocusable(boolean) 8046 * @attr ref android.R.styleable#View_focusableInTouchMode 8047 */ 8048 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8049 // Focusable in touch mode should always be set before the focusable flag 8050 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8051 // which, in touch mode, will not successfully request focus on this view 8052 // because the focusable in touch mode flag is not set 8053 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8054 if (focusableInTouchMode) { 8055 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8056 } 8057 } 8058 8059 /** 8060 * Set whether this view should have sound effects enabled for events such as 8061 * clicking and touching. 8062 * 8063 * <p>You may wish to disable sound effects for a view if you already play sounds, 8064 * for instance, a dial key that plays dtmf tones. 8065 * 8066 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8067 * @see #isSoundEffectsEnabled() 8068 * @see #playSoundEffect(int) 8069 * @attr ref android.R.styleable#View_soundEffectsEnabled 8070 */ 8071 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8072 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8073 } 8074 8075 /** 8076 * @return whether this view should have sound effects enabled for events such as 8077 * clicking and touching. 8078 * 8079 * @see #setSoundEffectsEnabled(boolean) 8080 * @see #playSoundEffect(int) 8081 * @attr ref android.R.styleable#View_soundEffectsEnabled 8082 */ 8083 @ViewDebug.ExportedProperty 8084 public boolean isSoundEffectsEnabled() { 8085 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8086 } 8087 8088 /** 8089 * Set whether this view should have haptic feedback for events such as 8090 * long presses. 8091 * 8092 * <p>You may wish to disable haptic feedback if your view already controls 8093 * its own haptic feedback. 8094 * 8095 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8096 * @see #isHapticFeedbackEnabled() 8097 * @see #performHapticFeedback(int) 8098 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8099 */ 8100 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8101 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8102 } 8103 8104 /** 8105 * @return whether this view should have haptic feedback enabled for events 8106 * long presses. 8107 * 8108 * @see #setHapticFeedbackEnabled(boolean) 8109 * @see #performHapticFeedback(int) 8110 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8111 */ 8112 @ViewDebug.ExportedProperty 8113 public boolean isHapticFeedbackEnabled() { 8114 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8115 } 8116 8117 /** 8118 * Returns the layout direction for this view. 8119 * 8120 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8121 * {@link #LAYOUT_DIRECTION_RTL}, 8122 * {@link #LAYOUT_DIRECTION_INHERIT} or 8123 * {@link #LAYOUT_DIRECTION_LOCALE}. 8124 * 8125 * @attr ref android.R.styleable#View_layoutDirection 8126 * 8127 * @hide 8128 */ 8129 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8130 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8131 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8132 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8133 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8134 }) 8135 @LayoutDir 8136 public int getRawLayoutDirection() { 8137 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8138 } 8139 8140 /** 8141 * Set the layout direction for this view. This will propagate a reset of layout direction 8142 * resolution to the view's children and resolve layout direction for this view. 8143 * 8144 * @param layoutDirection the layout direction to set. Should be one of: 8145 * 8146 * {@link #LAYOUT_DIRECTION_LTR}, 8147 * {@link #LAYOUT_DIRECTION_RTL}, 8148 * {@link #LAYOUT_DIRECTION_INHERIT}, 8149 * {@link #LAYOUT_DIRECTION_LOCALE}. 8150 * 8151 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8152 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8153 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8154 * 8155 * @attr ref android.R.styleable#View_layoutDirection 8156 */ 8157 @RemotableViewMethod 8158 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8159 if (getRawLayoutDirection() != layoutDirection) { 8160 // Reset the current layout direction and the resolved one 8161 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8162 resetRtlProperties(); 8163 // Set the new layout direction (filtered) 8164 mPrivateFlags2 |= 8165 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8166 // We need to resolve all RTL properties as they all depend on layout direction 8167 resolveRtlPropertiesIfNeeded(); 8168 requestLayout(); 8169 invalidate(true); 8170 } 8171 } 8172 8173 /** 8174 * Returns the resolved layout direction for this view. 8175 * 8176 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8177 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8178 * 8179 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8180 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8181 * 8182 * @attr ref android.R.styleable#View_layoutDirection 8183 */ 8184 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8185 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8186 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8187 }) 8188 @ResolvedLayoutDir 8189 public int getLayoutDirection() { 8190 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8191 if (targetSdkVersion < JELLY_BEAN_MR1) { 8192 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8193 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8194 } 8195 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8196 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8197 } 8198 8199 /** 8200 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8201 * layout attribute and/or the inherited value from the parent 8202 * 8203 * @return true if the layout is right-to-left. 8204 * 8205 * @hide 8206 */ 8207 @ViewDebug.ExportedProperty(category = "layout") 8208 public boolean isLayoutRtl() { 8209 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8210 } 8211 8212 /** 8213 * Indicates whether the view is currently tracking transient state that the 8214 * app should not need to concern itself with saving and restoring, but that 8215 * the framework should take special note to preserve when possible. 8216 * 8217 * <p>A view with transient state cannot be trivially rebound from an external 8218 * data source, such as an adapter binding item views in a list. This may be 8219 * because the view is performing an animation, tracking user selection 8220 * of content, or similar.</p> 8221 * 8222 * @return true if the view has transient state 8223 */ 8224 @ViewDebug.ExportedProperty(category = "layout") 8225 public boolean hasTransientState() { 8226 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8227 } 8228 8229 /** 8230 * Set whether this view is currently tracking transient state that the 8231 * framework should attempt to preserve when possible. This flag is reference counted, 8232 * so every call to setHasTransientState(true) should be paired with a later call 8233 * to setHasTransientState(false). 8234 * 8235 * <p>A view with transient state cannot be trivially rebound from an external 8236 * data source, such as an adapter binding item views in a list. This may be 8237 * because the view is performing an animation, tracking user selection 8238 * of content, or similar.</p> 8239 * 8240 * @param hasTransientState true if this view has transient state 8241 */ 8242 public void setHasTransientState(boolean hasTransientState) { 8243 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8244 mTransientStateCount - 1; 8245 if (mTransientStateCount < 0) { 8246 mTransientStateCount = 0; 8247 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8248 "unmatched pair of setHasTransientState calls"); 8249 } else if ((hasTransientState && mTransientStateCount == 1) || 8250 (!hasTransientState && mTransientStateCount == 0)) { 8251 // update flag if we've just incremented up from 0 or decremented down to 0 8252 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8253 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8254 if (mParent != null) { 8255 try { 8256 mParent.childHasTransientStateChanged(this, hasTransientState); 8257 } catch (AbstractMethodError e) { 8258 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8259 " does not fully implement ViewParent", e); 8260 } 8261 } 8262 } 8263 } 8264 8265 /** 8266 * Returns true if this view is currently attached to a window. 8267 */ 8268 public boolean isAttachedToWindow() { 8269 return mAttachInfo != null; 8270 } 8271 8272 /** 8273 * Returns true if this view has been through at least one layout since it 8274 * was last attached to or detached from a window. 8275 */ 8276 public boolean isLaidOut() { 8277 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8278 } 8279 8280 /** 8281 * If this view doesn't do any drawing on its own, set this flag to 8282 * allow further optimizations. By default, this flag is not set on 8283 * View, but could be set on some View subclasses such as ViewGroup. 8284 * 8285 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8286 * you should clear this flag. 8287 * 8288 * @param willNotDraw whether or not this View draw on its own 8289 */ 8290 public void setWillNotDraw(boolean willNotDraw) { 8291 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8292 } 8293 8294 /** 8295 * Returns whether or not this View draws on its own. 8296 * 8297 * @return true if this view has nothing to draw, false otherwise 8298 */ 8299 @ViewDebug.ExportedProperty(category = "drawing") 8300 public boolean willNotDraw() { 8301 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8302 } 8303 8304 /** 8305 * When a View's drawing cache is enabled, drawing is redirected to an 8306 * offscreen bitmap. Some views, like an ImageView, must be able to 8307 * bypass this mechanism if they already draw a single bitmap, to avoid 8308 * unnecessary usage of the memory. 8309 * 8310 * @param willNotCacheDrawing true if this view does not cache its 8311 * drawing, false otherwise 8312 */ 8313 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8314 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8315 } 8316 8317 /** 8318 * Returns whether or not this View can cache its drawing or not. 8319 * 8320 * @return true if this view does not cache its drawing, false otherwise 8321 */ 8322 @ViewDebug.ExportedProperty(category = "drawing") 8323 public boolean willNotCacheDrawing() { 8324 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8325 } 8326 8327 /** 8328 * Indicates whether this view reacts to click events or not. 8329 * 8330 * @return true if the view is clickable, false otherwise 8331 * 8332 * @see #setClickable(boolean) 8333 * @attr ref android.R.styleable#View_clickable 8334 */ 8335 @ViewDebug.ExportedProperty 8336 public boolean isClickable() { 8337 return (mViewFlags & CLICKABLE) == CLICKABLE; 8338 } 8339 8340 /** 8341 * Enables or disables click events for this view. When a view 8342 * is clickable it will change its state to "pressed" on every click. 8343 * Subclasses should set the view clickable to visually react to 8344 * user's clicks. 8345 * 8346 * @param clickable true to make the view clickable, false otherwise 8347 * 8348 * @see #isClickable() 8349 * @attr ref android.R.styleable#View_clickable 8350 */ 8351 public void setClickable(boolean clickable) { 8352 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8353 } 8354 8355 /** 8356 * Indicates whether this view reacts to long click events or not. 8357 * 8358 * @return true if the view is long clickable, false otherwise 8359 * 8360 * @see #setLongClickable(boolean) 8361 * @attr ref android.R.styleable#View_longClickable 8362 */ 8363 public boolean isLongClickable() { 8364 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8365 } 8366 8367 /** 8368 * Enables or disables long click events for this view. When a view is long 8369 * clickable it reacts to the user holding down the button for a longer 8370 * duration than a tap. This event can either launch the listener or a 8371 * context menu. 8372 * 8373 * @param longClickable true to make the view long clickable, false otherwise 8374 * @see #isLongClickable() 8375 * @attr ref android.R.styleable#View_longClickable 8376 */ 8377 public void setLongClickable(boolean longClickable) { 8378 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8379 } 8380 8381 /** 8382 * Indicates whether this view reacts to context clicks or not. 8383 * 8384 * @return true if the view is context clickable, false otherwise 8385 * @see #setContextClickable(boolean) 8386 * @attr ref android.R.styleable#View_contextClickable 8387 */ 8388 public boolean isContextClickable() { 8389 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8390 } 8391 8392 /** 8393 * Enables or disables context clicking for this view. This event can launch the listener. 8394 * 8395 * @param contextClickable true to make the view react to a context click, false otherwise 8396 * @see #isContextClickable() 8397 * @attr ref android.R.styleable#View_contextClickable 8398 */ 8399 public void setContextClickable(boolean contextClickable) { 8400 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8401 } 8402 8403 /** 8404 * Sets the pressed state for this view and provides a touch coordinate for 8405 * animation hinting. 8406 * 8407 * @param pressed Pass true to set the View's internal state to "pressed", 8408 * or false to reverts the View's internal state from a 8409 * previously set "pressed" state. 8410 * @param x The x coordinate of the touch that caused the press 8411 * @param y The y coordinate of the touch that caused the press 8412 */ 8413 private void setPressed(boolean pressed, float x, float y) { 8414 if (pressed) { 8415 drawableHotspotChanged(x, y); 8416 } 8417 8418 setPressed(pressed); 8419 } 8420 8421 /** 8422 * Sets the pressed state for this view. 8423 * 8424 * @see #isClickable() 8425 * @see #setClickable(boolean) 8426 * 8427 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8428 * the View's internal state from a previously set "pressed" state. 8429 */ 8430 public void setPressed(boolean pressed) { 8431 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8432 8433 if (pressed) { 8434 mPrivateFlags |= PFLAG_PRESSED; 8435 } else { 8436 mPrivateFlags &= ~PFLAG_PRESSED; 8437 } 8438 8439 if (needsRefresh) { 8440 refreshDrawableState(); 8441 } 8442 dispatchSetPressed(pressed); 8443 } 8444 8445 /** 8446 * Dispatch setPressed to all of this View's children. 8447 * 8448 * @see #setPressed(boolean) 8449 * 8450 * @param pressed The new pressed state 8451 */ 8452 protected void dispatchSetPressed(boolean pressed) { 8453 } 8454 8455 /** 8456 * Indicates whether the view is currently in pressed state. Unless 8457 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8458 * the pressed state. 8459 * 8460 * @see #setPressed(boolean) 8461 * @see #isClickable() 8462 * @see #setClickable(boolean) 8463 * 8464 * @return true if the view is currently pressed, false otherwise 8465 */ 8466 @ViewDebug.ExportedProperty 8467 public boolean isPressed() { 8468 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8469 } 8470 8471 /** 8472 * @hide 8473 * Indicates whether this view will participate in data collection through 8474 * {@link ViewStructure}. If true, it will not provide any data 8475 * for itself or its children. If false, the normal data collection will be allowed. 8476 * 8477 * @return Returns false if assist data collection is not blocked, else true. 8478 * 8479 * @see #setAssistBlocked(boolean) 8480 * @attr ref android.R.styleable#View_assistBlocked 8481 */ 8482 public boolean isAssistBlocked() { 8483 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8484 } 8485 8486 /** 8487 * @hide 8488 * Controls whether assist data collection from this view and its children is enabled 8489 * (that is, whether {@link #onProvideStructure} and 8490 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8491 * allowing normal assist collection. Setting this to false will disable assist collection. 8492 * 8493 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8494 * (the default) to allow it. 8495 * 8496 * @see #isAssistBlocked() 8497 * @see #onProvideStructure 8498 * @see #onProvideVirtualStructure 8499 * @attr ref android.R.styleable#View_assistBlocked 8500 */ 8501 public void setAssistBlocked(boolean enabled) { 8502 if (enabled) { 8503 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8504 } else { 8505 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8506 } 8507 } 8508 8509 /** 8510 * Indicates whether this view will save its state (that is, 8511 * whether its {@link #onSaveInstanceState} method will be called). 8512 * 8513 * @return Returns true if the view state saving is enabled, else false. 8514 * 8515 * @see #setSaveEnabled(boolean) 8516 * @attr ref android.R.styleable#View_saveEnabled 8517 */ 8518 public boolean isSaveEnabled() { 8519 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8520 } 8521 8522 /** 8523 * Controls whether the saving of this view's state is 8524 * enabled (that is, whether its {@link #onSaveInstanceState} method 8525 * will be called). Note that even if freezing is enabled, the 8526 * view still must have an id assigned to it (via {@link #setId(int)}) 8527 * for its state to be saved. This flag can only disable the 8528 * saving of this view; any child views may still have their state saved. 8529 * 8530 * @param enabled Set to false to <em>disable</em> state saving, or true 8531 * (the default) to allow it. 8532 * 8533 * @see #isSaveEnabled() 8534 * @see #setId(int) 8535 * @see #onSaveInstanceState() 8536 * @attr ref android.R.styleable#View_saveEnabled 8537 */ 8538 public void setSaveEnabled(boolean enabled) { 8539 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8540 } 8541 8542 /** 8543 * Gets whether the framework should discard touches when the view's 8544 * window is obscured by another visible window. 8545 * Refer to the {@link View} security documentation for more details. 8546 * 8547 * @return True if touch filtering is enabled. 8548 * 8549 * @see #setFilterTouchesWhenObscured(boolean) 8550 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8551 */ 8552 @ViewDebug.ExportedProperty 8553 public boolean getFilterTouchesWhenObscured() { 8554 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8555 } 8556 8557 /** 8558 * Sets whether the framework should discard touches when the view's 8559 * window is obscured by another visible window. 8560 * Refer to the {@link View} security documentation for more details. 8561 * 8562 * @param enabled True if touch filtering should be enabled. 8563 * 8564 * @see #getFilterTouchesWhenObscured 8565 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8566 */ 8567 public void setFilterTouchesWhenObscured(boolean enabled) { 8568 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8569 FILTER_TOUCHES_WHEN_OBSCURED); 8570 } 8571 8572 /** 8573 * Indicates whether the entire hierarchy under this view will save its 8574 * state when a state saving traversal occurs from its parent. The default 8575 * is true; if false, these views will not be saved unless 8576 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8577 * 8578 * @return Returns true if the view state saving from parent is enabled, else false. 8579 * 8580 * @see #setSaveFromParentEnabled(boolean) 8581 */ 8582 public boolean isSaveFromParentEnabled() { 8583 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8584 } 8585 8586 /** 8587 * Controls whether the entire hierarchy under this view will save its 8588 * state when a state saving traversal occurs from its parent. The default 8589 * is true; if false, these views will not be saved unless 8590 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8591 * 8592 * @param enabled Set to false to <em>disable</em> state saving, or true 8593 * (the default) to allow it. 8594 * 8595 * @see #isSaveFromParentEnabled() 8596 * @see #setId(int) 8597 * @see #onSaveInstanceState() 8598 */ 8599 public void setSaveFromParentEnabled(boolean enabled) { 8600 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8601 } 8602 8603 8604 /** 8605 * Returns whether this View is able to take focus. 8606 * 8607 * @return True if this view can take focus, or false otherwise. 8608 * @attr ref android.R.styleable#View_focusable 8609 */ 8610 @ViewDebug.ExportedProperty(category = "focus") 8611 public final boolean isFocusable() { 8612 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8613 } 8614 8615 /** 8616 * When a view is focusable, it may not want to take focus when in touch mode. 8617 * For example, a button would like focus when the user is navigating via a D-pad 8618 * so that the user can click on it, but once the user starts touching the screen, 8619 * the button shouldn't take focus 8620 * @return Whether the view is focusable in touch mode. 8621 * @attr ref android.R.styleable#View_focusableInTouchMode 8622 */ 8623 @ViewDebug.ExportedProperty 8624 public final boolean isFocusableInTouchMode() { 8625 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8626 } 8627 8628 /** 8629 * Find the nearest view in the specified direction that can take focus. 8630 * This does not actually give focus to that view. 8631 * 8632 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8633 * 8634 * @return The nearest focusable in the specified direction, or null if none 8635 * can be found. 8636 */ 8637 public View focusSearch(@FocusRealDirection int direction) { 8638 if (mParent != null) { 8639 return mParent.focusSearch(this, direction); 8640 } else { 8641 return null; 8642 } 8643 } 8644 8645 /** 8646 * This method is the last chance for the focused view and its ancestors to 8647 * respond to an arrow key. This is called when the focused view did not 8648 * consume the key internally, nor could the view system find a new view in 8649 * the requested direction to give focus to. 8650 * 8651 * @param focused The currently focused view. 8652 * @param direction The direction focus wants to move. One of FOCUS_UP, 8653 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8654 * @return True if the this view consumed this unhandled move. 8655 */ 8656 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8657 return false; 8658 } 8659 8660 /** 8661 * If a user manually specified the next view id for a particular direction, 8662 * use the root to look up the view. 8663 * @param root The root view of the hierarchy containing this view. 8664 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8665 * or FOCUS_BACKWARD. 8666 * @return The user specified next view, or null if there is none. 8667 */ 8668 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8669 switch (direction) { 8670 case FOCUS_LEFT: 8671 if (mNextFocusLeftId == View.NO_ID) return null; 8672 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8673 case FOCUS_RIGHT: 8674 if (mNextFocusRightId == View.NO_ID) return null; 8675 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8676 case FOCUS_UP: 8677 if (mNextFocusUpId == View.NO_ID) return null; 8678 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8679 case FOCUS_DOWN: 8680 if (mNextFocusDownId == View.NO_ID) return null; 8681 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8682 case FOCUS_FORWARD: 8683 if (mNextFocusForwardId == View.NO_ID) return null; 8684 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8685 case FOCUS_BACKWARD: { 8686 if (mID == View.NO_ID) return null; 8687 final int id = mID; 8688 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8689 @Override 8690 public boolean apply(View t) { 8691 return t.mNextFocusForwardId == id; 8692 } 8693 }); 8694 } 8695 } 8696 return null; 8697 } 8698 8699 private View findViewInsideOutShouldExist(View root, int id) { 8700 if (mMatchIdPredicate == null) { 8701 mMatchIdPredicate = new MatchIdPredicate(); 8702 } 8703 mMatchIdPredicate.mId = id; 8704 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8705 if (result == null) { 8706 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8707 } 8708 return result; 8709 } 8710 8711 /** 8712 * Find and return all focusable views that are descendants of this view, 8713 * possibly including this view if it is focusable itself. 8714 * 8715 * @param direction The direction of the focus 8716 * @return A list of focusable views 8717 */ 8718 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8719 ArrayList<View> result = new ArrayList<View>(24); 8720 addFocusables(result, direction); 8721 return result; 8722 } 8723 8724 /** 8725 * Add any focusable views that are descendants of this view (possibly 8726 * including this view if it is focusable itself) to views. If we are in touch mode, 8727 * only add views that are also focusable in touch mode. 8728 * 8729 * @param views Focusable views found so far 8730 * @param direction The direction of the focus 8731 */ 8732 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8733 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8734 } 8735 8736 /** 8737 * Adds any focusable views that are descendants of this view (possibly 8738 * including this view if it is focusable itself) to views. This method 8739 * adds all focusable views regardless if we are in touch mode or 8740 * only views focusable in touch mode if we are in touch mode or 8741 * only views that can take accessibility focus if accessibility is enabled 8742 * depending on the focusable mode parameter. 8743 * 8744 * @param views Focusable views found so far or null if all we are interested is 8745 * the number of focusables. 8746 * @param direction The direction of the focus. 8747 * @param focusableMode The type of focusables to be added. 8748 * 8749 * @see #FOCUSABLES_ALL 8750 * @see #FOCUSABLES_TOUCH_MODE 8751 */ 8752 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8753 @FocusableMode int focusableMode) { 8754 if (views == null) { 8755 return; 8756 } 8757 if (!isFocusable()) { 8758 return; 8759 } 8760 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8761 && isInTouchMode() && !isFocusableInTouchMode()) { 8762 return; 8763 } 8764 views.add(this); 8765 } 8766 8767 /** 8768 * Finds the Views that contain given text. The containment is case insensitive. 8769 * The search is performed by either the text that the View renders or the content 8770 * description that describes the view for accessibility purposes and the view does 8771 * not render or both. Clients can specify how the search is to be performed via 8772 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8773 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8774 * 8775 * @param outViews The output list of matching Views. 8776 * @param searched The text to match against. 8777 * 8778 * @see #FIND_VIEWS_WITH_TEXT 8779 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8780 * @see #setContentDescription(CharSequence) 8781 */ 8782 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8783 @FindViewFlags int flags) { 8784 if (getAccessibilityNodeProvider() != null) { 8785 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8786 outViews.add(this); 8787 } 8788 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8789 && (searched != null && searched.length() > 0) 8790 && (mContentDescription != null && mContentDescription.length() > 0)) { 8791 String searchedLowerCase = searched.toString().toLowerCase(); 8792 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8793 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8794 outViews.add(this); 8795 } 8796 } 8797 } 8798 8799 /** 8800 * Find and return all touchable views that are descendants of this view, 8801 * possibly including this view if it is touchable itself. 8802 * 8803 * @return A list of touchable views 8804 */ 8805 public ArrayList<View> getTouchables() { 8806 ArrayList<View> result = new ArrayList<View>(); 8807 addTouchables(result); 8808 return result; 8809 } 8810 8811 /** 8812 * Add any touchable views that are descendants of this view (possibly 8813 * including this view if it is touchable itself) to views. 8814 * 8815 * @param views Touchable views found so far 8816 */ 8817 public void addTouchables(ArrayList<View> views) { 8818 final int viewFlags = mViewFlags; 8819 8820 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8821 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8822 && (viewFlags & ENABLED_MASK) == ENABLED) { 8823 views.add(this); 8824 } 8825 } 8826 8827 /** 8828 * Returns whether this View is accessibility focused. 8829 * 8830 * @return True if this View is accessibility focused. 8831 */ 8832 public boolean isAccessibilityFocused() { 8833 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8834 } 8835 8836 /** 8837 * Call this to try to give accessibility focus to this view. 8838 * 8839 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8840 * returns false or the view is no visible or the view already has accessibility 8841 * focus. 8842 * 8843 * See also {@link #focusSearch(int)}, which is what you call to say that you 8844 * have focus, and you want your parent to look for the next one. 8845 * 8846 * @return Whether this view actually took accessibility focus. 8847 * 8848 * @hide 8849 */ 8850 public boolean requestAccessibilityFocus() { 8851 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8852 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8853 return false; 8854 } 8855 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8856 return false; 8857 } 8858 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8859 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8860 ViewRootImpl viewRootImpl = getViewRootImpl(); 8861 if (viewRootImpl != null) { 8862 viewRootImpl.setAccessibilityFocus(this, null); 8863 } 8864 invalidate(); 8865 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8866 return true; 8867 } 8868 return false; 8869 } 8870 8871 /** 8872 * Call this to try to clear accessibility focus of this view. 8873 * 8874 * See also {@link #focusSearch(int)}, which is what you call to say that you 8875 * have focus, and you want your parent to look for the next one. 8876 * 8877 * @hide 8878 */ 8879 public void clearAccessibilityFocus() { 8880 clearAccessibilityFocusNoCallbacks(0); 8881 8882 // Clear the global reference of accessibility focus if this view or 8883 // any of its descendants had accessibility focus. This will NOT send 8884 // an event or update internal state if focus is cleared from a 8885 // descendant view, which may leave views in inconsistent states. 8886 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8887 if (viewRootImpl != null) { 8888 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8889 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8890 viewRootImpl.setAccessibilityFocus(null, null); 8891 } 8892 } 8893 } 8894 8895 private void sendAccessibilityHoverEvent(int eventType) { 8896 // Since we are not delivering to a client accessibility events from not 8897 // important views (unless the clinet request that) we need to fire the 8898 // event from the deepest view exposed to the client. As a consequence if 8899 // the user crosses a not exposed view the client will see enter and exit 8900 // of the exposed predecessor followed by and enter and exit of that same 8901 // predecessor when entering and exiting the not exposed descendant. This 8902 // is fine since the client has a clear idea which view is hovered at the 8903 // price of a couple more events being sent. This is a simple and 8904 // working solution. 8905 View source = this; 8906 while (true) { 8907 if (source.includeForAccessibility()) { 8908 source.sendAccessibilityEvent(eventType); 8909 return; 8910 } 8911 ViewParent parent = source.getParent(); 8912 if (parent instanceof View) { 8913 source = (View) parent; 8914 } else { 8915 return; 8916 } 8917 } 8918 } 8919 8920 /** 8921 * Clears accessibility focus without calling any callback methods 8922 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8923 * is used separately from that one for clearing accessibility focus when 8924 * giving this focus to another view. 8925 * 8926 * @param action The action, if any, that led to focus being cleared. Set to 8927 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 8928 * the window. 8929 */ 8930 void clearAccessibilityFocusNoCallbacks(int action) { 8931 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8932 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8933 invalidate(); 8934 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 8935 AccessibilityEvent event = AccessibilityEvent.obtain( 8936 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8937 event.setAction(action); 8938 if (mAccessibilityDelegate != null) { 8939 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 8940 } else { 8941 sendAccessibilityEventUnchecked(event); 8942 } 8943 } 8944 } 8945 } 8946 8947 /** 8948 * Call this to try to give focus to a specific view or to one of its 8949 * descendants. 8950 * 8951 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8952 * false), or if it is focusable and it is not focusable in touch mode 8953 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8954 * 8955 * See also {@link #focusSearch(int)}, which is what you call to say that you 8956 * have focus, and you want your parent to look for the next one. 8957 * 8958 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8959 * {@link #FOCUS_DOWN} and <code>null</code>. 8960 * 8961 * @return Whether this view or one of its descendants actually took focus. 8962 */ 8963 public final boolean requestFocus() { 8964 return requestFocus(View.FOCUS_DOWN); 8965 } 8966 8967 /** 8968 * Call this to try to give focus to a specific view or to one of its 8969 * descendants and give it a hint about what direction focus is heading. 8970 * 8971 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8972 * false), or if it is focusable and it is not focusable in touch mode 8973 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8974 * 8975 * See also {@link #focusSearch(int)}, which is what you call to say that you 8976 * have focus, and you want your parent to look for the next one. 8977 * 8978 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8979 * <code>null</code> set for the previously focused rectangle. 8980 * 8981 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8982 * @return Whether this view or one of its descendants actually took focus. 8983 */ 8984 public final boolean requestFocus(int direction) { 8985 return requestFocus(direction, null); 8986 } 8987 8988 /** 8989 * Call this to try to give focus to a specific view or to one of its descendants 8990 * and give it hints about the direction and a specific rectangle that the focus 8991 * is coming from. The rectangle can help give larger views a finer grained hint 8992 * about where focus is coming from, and therefore, where to show selection, or 8993 * forward focus change internally. 8994 * 8995 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8996 * false), or if it is focusable and it is not focusable in touch mode 8997 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8998 * 8999 * A View will not take focus if it is not visible. 9000 * 9001 * A View will not take focus if one of its parents has 9002 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 9003 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 9004 * 9005 * See also {@link #focusSearch(int)}, which is what you call to say that you 9006 * have focus, and you want your parent to look for the next one. 9007 * 9008 * You may wish to override this method if your custom {@link View} has an internal 9009 * {@link View} that it wishes to forward the request to. 9010 * 9011 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9012 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 9013 * to give a finer grained hint about where focus is coming from. May be null 9014 * if there is no hint. 9015 * @return Whether this view or one of its descendants actually took focus. 9016 */ 9017 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 9018 return requestFocusNoSearch(direction, previouslyFocusedRect); 9019 } 9020 9021 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 9022 // need to be focusable 9023 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 9024 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 9025 return false; 9026 } 9027 9028 // need to be focusable in touch mode if in touch mode 9029 if (isInTouchMode() && 9030 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 9031 return false; 9032 } 9033 9034 // need to not have any parents blocking us 9035 if (hasAncestorThatBlocksDescendantFocus()) { 9036 return false; 9037 } 9038 9039 handleFocusGainInternal(direction, previouslyFocusedRect); 9040 return true; 9041 } 9042 9043 /** 9044 * Call this to try to give focus to a specific view or to one of its descendants. This is a 9045 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 9046 * touch mode to request focus when they are touched. 9047 * 9048 * @return Whether this view or one of its descendants actually took focus. 9049 * 9050 * @see #isInTouchMode() 9051 * 9052 */ 9053 public final boolean requestFocusFromTouch() { 9054 // Leave touch mode if we need to 9055 if (isInTouchMode()) { 9056 ViewRootImpl viewRoot = getViewRootImpl(); 9057 if (viewRoot != null) { 9058 viewRoot.ensureTouchMode(false); 9059 } 9060 } 9061 return requestFocus(View.FOCUS_DOWN); 9062 } 9063 9064 /** 9065 * @return Whether any ancestor of this view blocks descendant focus. 9066 */ 9067 private boolean hasAncestorThatBlocksDescendantFocus() { 9068 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9069 ViewParent ancestor = mParent; 9070 while (ancestor instanceof ViewGroup) { 9071 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9072 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9073 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9074 return true; 9075 } else { 9076 ancestor = vgAncestor.getParent(); 9077 } 9078 } 9079 return false; 9080 } 9081 9082 /** 9083 * Gets the mode for determining whether this View is important for accessibility 9084 * which is if it fires accessibility events and if it is reported to 9085 * accessibility services that query the screen. 9086 * 9087 * @return The mode for determining whether a View is important for accessibility. 9088 * 9089 * @attr ref android.R.styleable#View_importantForAccessibility 9090 * 9091 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9092 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9093 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9094 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9095 */ 9096 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9097 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9098 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9099 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9100 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9101 to = "noHideDescendants") 9102 }) 9103 public int getImportantForAccessibility() { 9104 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9105 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9106 } 9107 9108 /** 9109 * Sets the live region mode for this view. This indicates to accessibility 9110 * services whether they should automatically notify the user about changes 9111 * to the view's content description or text, or to the content descriptions 9112 * or text of the view's children (where applicable). 9113 * <p> 9114 * For example, in a login screen with a TextView that displays an "incorrect 9115 * password" notification, that view should be marked as a live region with 9116 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9117 * <p> 9118 * To disable change notifications for this view, use 9119 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9120 * mode for most views. 9121 * <p> 9122 * To indicate that the user should be notified of changes, use 9123 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9124 * <p> 9125 * If the view's changes should interrupt ongoing speech and notify the user 9126 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9127 * 9128 * @param mode The live region mode for this view, one of: 9129 * <ul> 9130 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9131 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9132 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9133 * </ul> 9134 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9135 */ 9136 public void setAccessibilityLiveRegion(int mode) { 9137 if (mode != getAccessibilityLiveRegion()) { 9138 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9139 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9140 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9141 notifyViewAccessibilityStateChangedIfNeeded( 9142 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9143 } 9144 } 9145 9146 /** 9147 * Gets the live region mode for this View. 9148 * 9149 * @return The live region mode for the view. 9150 * 9151 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9152 * 9153 * @see #setAccessibilityLiveRegion(int) 9154 */ 9155 public int getAccessibilityLiveRegion() { 9156 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9157 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9158 } 9159 9160 /** 9161 * Sets how to determine whether this view is important for accessibility 9162 * which is if it fires accessibility events and if it is reported to 9163 * accessibility services that query the screen. 9164 * 9165 * @param mode How to determine whether this view is important for accessibility. 9166 * 9167 * @attr ref android.R.styleable#View_importantForAccessibility 9168 * 9169 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9170 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9171 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9172 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9173 */ 9174 public void setImportantForAccessibility(int mode) { 9175 final int oldMode = getImportantForAccessibility(); 9176 if (mode != oldMode) { 9177 final boolean hideDescendants = 9178 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9179 9180 // If this node or its descendants are no longer important, try to 9181 // clear accessibility focus. 9182 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9183 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9184 if (focusHost != null) { 9185 focusHost.clearAccessibilityFocus(); 9186 } 9187 } 9188 9189 // If we're moving between AUTO and another state, we might not need 9190 // to send a subtree changed notification. We'll store the computed 9191 // importance, since we'll need to check it later to make sure. 9192 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9193 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9194 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9195 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9196 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9197 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9198 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9199 notifySubtreeAccessibilityStateChangedIfNeeded(); 9200 } else { 9201 notifyViewAccessibilityStateChangedIfNeeded( 9202 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9203 } 9204 } 9205 } 9206 9207 /** 9208 * Returns the view within this view's hierarchy that is hosting 9209 * accessibility focus. 9210 * 9211 * @param searchDescendants whether to search for focus in descendant views 9212 * @return the view hosting accessibility focus, or {@code null} 9213 */ 9214 private View findAccessibilityFocusHost(boolean searchDescendants) { 9215 if (isAccessibilityFocusedViewOrHost()) { 9216 return this; 9217 } 9218 9219 if (searchDescendants) { 9220 final ViewRootImpl viewRoot = getViewRootImpl(); 9221 if (viewRoot != null) { 9222 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9223 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9224 return focusHost; 9225 } 9226 } 9227 } 9228 9229 return null; 9230 } 9231 9232 /** 9233 * Computes whether this view should be exposed for accessibility. In 9234 * general, views that are interactive or provide information are exposed 9235 * while views that serve only as containers are hidden. 9236 * <p> 9237 * If an ancestor of this view has importance 9238 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9239 * returns <code>false</code>. 9240 * <p> 9241 * Otherwise, the value is computed according to the view's 9242 * {@link #getImportantForAccessibility()} value: 9243 * <ol> 9244 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9245 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9246 * </code> 9247 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9248 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9249 * view satisfies any of the following: 9250 * <ul> 9251 * <li>Is actionable, e.g. {@link #isClickable()}, 9252 * {@link #isLongClickable()}, or {@link #isFocusable()} 9253 * <li>Has an {@link AccessibilityDelegate} 9254 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9255 * {@link OnKeyListener}, etc. 9256 * <li>Is an accessibility live region, e.g. 9257 * {@link #getAccessibilityLiveRegion()} is not 9258 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9259 * </ul> 9260 * </ol> 9261 * 9262 * @return Whether the view is exposed for accessibility. 9263 * @see #setImportantForAccessibility(int) 9264 * @see #getImportantForAccessibility() 9265 */ 9266 public boolean isImportantForAccessibility() { 9267 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9268 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9269 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9270 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9271 return false; 9272 } 9273 9274 // Check parent mode to ensure we're not hidden. 9275 ViewParent parent = mParent; 9276 while (parent instanceof View) { 9277 if (((View) parent).getImportantForAccessibility() 9278 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9279 return false; 9280 } 9281 parent = parent.getParent(); 9282 } 9283 9284 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9285 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9286 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9287 } 9288 9289 /** 9290 * Gets the parent for accessibility purposes. Note that the parent for 9291 * accessibility is not necessary the immediate parent. It is the first 9292 * predecessor that is important for accessibility. 9293 * 9294 * @return The parent for accessibility purposes. 9295 */ 9296 public ViewParent getParentForAccessibility() { 9297 if (mParent instanceof View) { 9298 View parentView = (View) mParent; 9299 if (parentView.includeForAccessibility()) { 9300 return mParent; 9301 } else { 9302 return mParent.getParentForAccessibility(); 9303 } 9304 } 9305 return null; 9306 } 9307 9308 /** 9309 * Adds the children of this View relevant for accessibility to the given list 9310 * as output. Since some Views are not important for accessibility the added 9311 * child views are not necessarily direct children of this view, rather they are 9312 * the first level of descendants important for accessibility. 9313 * 9314 * @param outChildren The output list that will receive children for accessibility. 9315 */ 9316 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9317 9318 } 9319 9320 /** 9321 * Whether to regard this view for accessibility. A view is regarded for 9322 * accessibility if it is important for accessibility or the querying 9323 * accessibility service has explicitly requested that view not 9324 * important for accessibility are regarded. 9325 * 9326 * @return Whether to regard the view for accessibility. 9327 * 9328 * @hide 9329 */ 9330 public boolean includeForAccessibility() { 9331 if (mAttachInfo != null) { 9332 return (mAttachInfo.mAccessibilityFetchFlags 9333 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9334 || isImportantForAccessibility(); 9335 } 9336 return false; 9337 } 9338 9339 /** 9340 * Returns whether the View is considered actionable from 9341 * accessibility perspective. Such view are important for 9342 * accessibility. 9343 * 9344 * @return True if the view is actionable for accessibility. 9345 * 9346 * @hide 9347 */ 9348 public boolean isActionableForAccessibility() { 9349 return (isClickable() || isLongClickable() || isFocusable()); 9350 } 9351 9352 /** 9353 * Returns whether the View has registered callbacks which makes it 9354 * important for accessibility. 9355 * 9356 * @return True if the view is actionable for accessibility. 9357 */ 9358 private boolean hasListenersForAccessibility() { 9359 ListenerInfo info = getListenerInfo(); 9360 return mTouchDelegate != null || info.mOnKeyListener != null 9361 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9362 || info.mOnHoverListener != null || info.mOnDragListener != null; 9363 } 9364 9365 /** 9366 * Notifies that the accessibility state of this view changed. The change 9367 * is local to this view and does not represent structural changes such 9368 * as children and parent. For example, the view became focusable. The 9369 * notification is at at most once every 9370 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9371 * to avoid unnecessary load to the system. Also once a view has a pending 9372 * notification this method is a NOP until the notification has been sent. 9373 * 9374 * @hide 9375 */ 9376 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9377 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9378 return; 9379 } 9380 if (mSendViewStateChangedAccessibilityEvent == null) { 9381 mSendViewStateChangedAccessibilityEvent = 9382 new SendViewStateChangedAccessibilityEvent(); 9383 } 9384 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9385 } 9386 9387 /** 9388 * Notifies that the accessibility state of this view changed. The change 9389 * is *not* local to this view and does represent structural changes such 9390 * as children and parent. For example, the view size changed. The 9391 * notification is at at most once every 9392 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9393 * to avoid unnecessary load to the system. Also once a view has a pending 9394 * notification this method is a NOP until the notification has been sent. 9395 * 9396 * @hide 9397 */ 9398 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9399 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9400 return; 9401 } 9402 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9403 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9404 if (mParent != null) { 9405 try { 9406 mParent.notifySubtreeAccessibilityStateChanged( 9407 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9408 } catch (AbstractMethodError e) { 9409 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9410 " does not fully implement ViewParent", e); 9411 } 9412 } 9413 } 9414 } 9415 9416 /** 9417 * Change the visibility of the View without triggering any other changes. This is 9418 * important for transitions, where visibility changes should not adjust focus or 9419 * trigger a new layout. This is only used when the visibility has already been changed 9420 * and we need a transient value during an animation. When the animation completes, 9421 * the original visibility value is always restored. 9422 * 9423 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9424 * @hide 9425 */ 9426 public void setTransitionVisibility(@Visibility int visibility) { 9427 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9428 } 9429 9430 /** 9431 * Reset the flag indicating the accessibility state of the subtree rooted 9432 * at this view changed. 9433 */ 9434 void resetSubtreeAccessibilityStateChanged() { 9435 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9436 } 9437 9438 /** 9439 * Report an accessibility action to this view's parents for delegated processing. 9440 * 9441 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9442 * call this method to delegate an accessibility action to a supporting parent. If the parent 9443 * returns true from its 9444 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9445 * method this method will return true to signify that the action was consumed.</p> 9446 * 9447 * <p>This method is useful for implementing nested scrolling child views. If 9448 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9449 * a custom view implementation may invoke this method to allow a parent to consume the 9450 * scroll first. If this method returns true the custom view should skip its own scrolling 9451 * behavior.</p> 9452 * 9453 * @param action Accessibility action to delegate 9454 * @param arguments Optional action arguments 9455 * @return true if the action was consumed by a parent 9456 */ 9457 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9458 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9459 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9460 return true; 9461 } 9462 } 9463 return false; 9464 } 9465 9466 /** 9467 * Performs the specified accessibility action on the view. For 9468 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9469 * <p> 9470 * If an {@link AccessibilityDelegate} has been specified via calling 9471 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9472 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9473 * is responsible for handling this call. 9474 * </p> 9475 * 9476 * <p>The default implementation will delegate 9477 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9478 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9479 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9480 * 9481 * @param action The action to perform. 9482 * @param arguments Optional action arguments. 9483 * @return Whether the action was performed. 9484 */ 9485 public boolean performAccessibilityAction(int action, Bundle arguments) { 9486 if (mAccessibilityDelegate != null) { 9487 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9488 } else { 9489 return performAccessibilityActionInternal(action, arguments); 9490 } 9491 } 9492 9493 /** 9494 * @see #performAccessibilityAction(int, Bundle) 9495 * 9496 * Note: Called from the default {@link AccessibilityDelegate}. 9497 * 9498 * @hide 9499 */ 9500 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9501 if (isNestedScrollingEnabled() 9502 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9503 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9504 || action == R.id.accessibilityActionScrollUp 9505 || action == R.id.accessibilityActionScrollLeft 9506 || action == R.id.accessibilityActionScrollDown 9507 || action == R.id.accessibilityActionScrollRight)) { 9508 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9509 return true; 9510 } 9511 } 9512 9513 switch (action) { 9514 case AccessibilityNodeInfo.ACTION_CLICK: { 9515 if (isClickable()) { 9516 performClick(); 9517 return true; 9518 } 9519 } break; 9520 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9521 if (isLongClickable()) { 9522 performLongClick(); 9523 return true; 9524 } 9525 } break; 9526 case AccessibilityNodeInfo.ACTION_FOCUS: { 9527 if (!hasFocus()) { 9528 // Get out of touch mode since accessibility 9529 // wants to move focus around. 9530 getViewRootImpl().ensureTouchMode(false); 9531 return requestFocus(); 9532 } 9533 } break; 9534 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9535 if (hasFocus()) { 9536 clearFocus(); 9537 return !isFocused(); 9538 } 9539 } break; 9540 case AccessibilityNodeInfo.ACTION_SELECT: { 9541 if (!isSelected()) { 9542 setSelected(true); 9543 return isSelected(); 9544 } 9545 } break; 9546 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9547 if (isSelected()) { 9548 setSelected(false); 9549 return !isSelected(); 9550 } 9551 } break; 9552 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9553 if (!isAccessibilityFocused()) { 9554 return requestAccessibilityFocus(); 9555 } 9556 } break; 9557 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9558 if (isAccessibilityFocused()) { 9559 clearAccessibilityFocus(); 9560 return true; 9561 } 9562 } break; 9563 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9564 if (arguments != null) { 9565 final int granularity = arguments.getInt( 9566 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9567 final boolean extendSelection = arguments.getBoolean( 9568 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9569 return traverseAtGranularity(granularity, true, extendSelection); 9570 } 9571 } break; 9572 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9573 if (arguments != null) { 9574 final int granularity = arguments.getInt( 9575 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9576 final boolean extendSelection = arguments.getBoolean( 9577 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9578 return traverseAtGranularity(granularity, false, extendSelection); 9579 } 9580 } break; 9581 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9582 CharSequence text = getIterableTextForAccessibility(); 9583 if (text == null) { 9584 return false; 9585 } 9586 final int start = (arguments != null) ? arguments.getInt( 9587 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9588 final int end = (arguments != null) ? arguments.getInt( 9589 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9590 // Only cursor position can be specified (selection length == 0) 9591 if ((getAccessibilitySelectionStart() != start 9592 || getAccessibilitySelectionEnd() != end) 9593 && (start == end)) { 9594 setAccessibilitySelection(start, end); 9595 notifyViewAccessibilityStateChangedIfNeeded( 9596 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9597 return true; 9598 } 9599 } break; 9600 case R.id.accessibilityActionShowOnScreen: { 9601 if (mAttachInfo != null) { 9602 final Rect r = mAttachInfo.mTmpInvalRect; 9603 getDrawingRect(r); 9604 return requestRectangleOnScreen(r, true); 9605 } 9606 } break; 9607 case R.id.accessibilityActionContextClick: { 9608 if (isContextClickable()) { 9609 performContextClick(); 9610 return true; 9611 } 9612 } break; 9613 } 9614 return false; 9615 } 9616 9617 private boolean traverseAtGranularity(int granularity, boolean forward, 9618 boolean extendSelection) { 9619 CharSequence text = getIterableTextForAccessibility(); 9620 if (text == null || text.length() == 0) { 9621 return false; 9622 } 9623 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9624 if (iterator == null) { 9625 return false; 9626 } 9627 int current = getAccessibilitySelectionEnd(); 9628 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9629 current = forward ? 0 : text.length(); 9630 } 9631 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9632 if (range == null) { 9633 return false; 9634 } 9635 final int segmentStart = range[0]; 9636 final int segmentEnd = range[1]; 9637 int selectionStart; 9638 int selectionEnd; 9639 if (extendSelection && isAccessibilitySelectionExtendable()) { 9640 selectionStart = getAccessibilitySelectionStart(); 9641 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9642 selectionStart = forward ? segmentStart : segmentEnd; 9643 } 9644 selectionEnd = forward ? segmentEnd : segmentStart; 9645 } else { 9646 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9647 } 9648 setAccessibilitySelection(selectionStart, selectionEnd); 9649 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9650 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9651 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9652 return true; 9653 } 9654 9655 /** 9656 * Gets the text reported for accessibility purposes. 9657 * 9658 * @return The accessibility text. 9659 * 9660 * @hide 9661 */ 9662 public CharSequence getIterableTextForAccessibility() { 9663 return getContentDescription(); 9664 } 9665 9666 /** 9667 * Gets whether accessibility selection can be extended. 9668 * 9669 * @return If selection is extensible. 9670 * 9671 * @hide 9672 */ 9673 public boolean isAccessibilitySelectionExtendable() { 9674 return false; 9675 } 9676 9677 /** 9678 * @hide 9679 */ 9680 public int getAccessibilitySelectionStart() { 9681 return mAccessibilityCursorPosition; 9682 } 9683 9684 /** 9685 * @hide 9686 */ 9687 public int getAccessibilitySelectionEnd() { 9688 return getAccessibilitySelectionStart(); 9689 } 9690 9691 /** 9692 * @hide 9693 */ 9694 public void setAccessibilitySelection(int start, int end) { 9695 if (start == end && end == mAccessibilityCursorPosition) { 9696 return; 9697 } 9698 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9699 mAccessibilityCursorPosition = start; 9700 } else { 9701 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9702 } 9703 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9704 } 9705 9706 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9707 int fromIndex, int toIndex) { 9708 if (mParent == null) { 9709 return; 9710 } 9711 AccessibilityEvent event = AccessibilityEvent.obtain( 9712 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9713 onInitializeAccessibilityEvent(event); 9714 onPopulateAccessibilityEvent(event); 9715 event.setFromIndex(fromIndex); 9716 event.setToIndex(toIndex); 9717 event.setAction(action); 9718 event.setMovementGranularity(granularity); 9719 mParent.requestSendAccessibilityEvent(this, event); 9720 } 9721 9722 /** 9723 * @hide 9724 */ 9725 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9726 switch (granularity) { 9727 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9728 CharSequence text = getIterableTextForAccessibility(); 9729 if (text != null && text.length() > 0) { 9730 CharacterTextSegmentIterator iterator = 9731 CharacterTextSegmentIterator.getInstance( 9732 mContext.getResources().getConfiguration().locale); 9733 iterator.initialize(text.toString()); 9734 return iterator; 9735 } 9736 } break; 9737 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9738 CharSequence text = getIterableTextForAccessibility(); 9739 if (text != null && text.length() > 0) { 9740 WordTextSegmentIterator iterator = 9741 WordTextSegmentIterator.getInstance( 9742 mContext.getResources().getConfiguration().locale); 9743 iterator.initialize(text.toString()); 9744 return iterator; 9745 } 9746 } break; 9747 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9748 CharSequence text = getIterableTextForAccessibility(); 9749 if (text != null && text.length() > 0) { 9750 ParagraphTextSegmentIterator iterator = 9751 ParagraphTextSegmentIterator.getInstance(); 9752 iterator.initialize(text.toString()); 9753 return iterator; 9754 } 9755 } break; 9756 } 9757 return null; 9758 } 9759 9760 /** 9761 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 9762 * and {@link #onFinishTemporaryDetach()}. 9763 */ 9764 public final boolean isTemporarilyDetached() { 9765 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 9766 } 9767 9768 /** 9769 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 9770 * a container View. 9771 */ 9772 @CallSuper 9773 public void dispatchStartTemporaryDetach() { 9774 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 9775 onStartTemporaryDetach(); 9776 } 9777 9778 /** 9779 * This is called when a container is going to temporarily detach a child, with 9780 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9781 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9782 * {@link #onDetachedFromWindow()} when the container is done. 9783 */ 9784 public void onStartTemporaryDetach() { 9785 removeUnsetPressCallback(); 9786 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9787 } 9788 9789 /** 9790 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 9791 * a container View. 9792 */ 9793 @CallSuper 9794 public void dispatchFinishTemporaryDetach() { 9795 onFinishTemporaryDetach(); 9796 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 9797 } 9798 9799 /** 9800 * Called after {@link #onStartTemporaryDetach} when the container is done 9801 * changing the view. 9802 */ 9803 public void onFinishTemporaryDetach() { 9804 } 9805 9806 /** 9807 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9808 * for this view's window. Returns null if the view is not currently attached 9809 * to the window. Normally you will not need to use this directly, but 9810 * just use the standard high-level event callbacks like 9811 * {@link #onKeyDown(int, KeyEvent)}. 9812 */ 9813 public KeyEvent.DispatcherState getKeyDispatcherState() { 9814 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9815 } 9816 9817 /** 9818 * Dispatch a key event before it is processed by any input method 9819 * associated with the view hierarchy. This can be used to intercept 9820 * key events in special situations before the IME consumes them; a 9821 * typical example would be handling the BACK key to update the application's 9822 * UI instead of allowing the IME to see it and close itself. 9823 * 9824 * @param event The key event to be dispatched. 9825 * @return True if the event was handled, false otherwise. 9826 */ 9827 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9828 return onKeyPreIme(event.getKeyCode(), event); 9829 } 9830 9831 /** 9832 * Dispatch a key event to the next view on the focus path. This path runs 9833 * from the top of the view tree down to the currently focused view. If this 9834 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9835 * the next node down the focus path. This method also fires any key 9836 * listeners. 9837 * 9838 * @param event The key event to be dispatched. 9839 * @return True if the event was handled, false otherwise. 9840 */ 9841 public boolean dispatchKeyEvent(KeyEvent event) { 9842 if (mInputEventConsistencyVerifier != null) { 9843 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9844 } 9845 9846 // Give any attached key listener a first crack at the event. 9847 //noinspection SimplifiableIfStatement 9848 ListenerInfo li = mListenerInfo; 9849 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9850 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9851 return true; 9852 } 9853 9854 if (event.dispatch(this, mAttachInfo != null 9855 ? mAttachInfo.mKeyDispatchState : null, this)) { 9856 return true; 9857 } 9858 9859 if (mInputEventConsistencyVerifier != null) { 9860 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9861 } 9862 return false; 9863 } 9864 9865 /** 9866 * Dispatches a key shortcut event. 9867 * 9868 * @param event The key event to be dispatched. 9869 * @return True if the event was handled by the view, false otherwise. 9870 */ 9871 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9872 return onKeyShortcut(event.getKeyCode(), event); 9873 } 9874 9875 /** 9876 * Pass the touch screen motion event down to the target view, or this 9877 * view if it is the target. 9878 * 9879 * @param event The motion event to be dispatched. 9880 * @return True if the event was handled by the view, false otherwise. 9881 */ 9882 public boolean dispatchTouchEvent(MotionEvent event) { 9883 // If the event should be handled by accessibility focus first. 9884 if (event.isTargetAccessibilityFocus()) { 9885 // We don't have focus or no virtual descendant has it, do not handle the event. 9886 if (!isAccessibilityFocusedViewOrHost()) { 9887 return false; 9888 } 9889 // We have focus and got the event, then use normal event dispatch. 9890 event.setTargetAccessibilityFocus(false); 9891 } 9892 9893 boolean result = false; 9894 9895 if (mInputEventConsistencyVerifier != null) { 9896 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9897 } 9898 9899 final int actionMasked = event.getActionMasked(); 9900 if (actionMasked == MotionEvent.ACTION_DOWN) { 9901 // Defensive cleanup for new gesture 9902 stopNestedScroll(); 9903 } 9904 9905 if (onFilterTouchEventForSecurity(event)) { 9906 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9907 result = true; 9908 } 9909 //noinspection SimplifiableIfStatement 9910 ListenerInfo li = mListenerInfo; 9911 if (li != null && li.mOnTouchListener != null 9912 && (mViewFlags & ENABLED_MASK) == ENABLED 9913 && li.mOnTouchListener.onTouch(this, event)) { 9914 result = true; 9915 } 9916 9917 if (!result && onTouchEvent(event)) { 9918 result = true; 9919 } 9920 } 9921 9922 if (!result && mInputEventConsistencyVerifier != null) { 9923 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9924 } 9925 9926 // Clean up after nested scrolls if this is the end of a gesture; 9927 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9928 // of the gesture. 9929 if (actionMasked == MotionEvent.ACTION_UP || 9930 actionMasked == MotionEvent.ACTION_CANCEL || 9931 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9932 stopNestedScroll(); 9933 } 9934 9935 return result; 9936 } 9937 9938 boolean isAccessibilityFocusedViewOrHost() { 9939 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9940 .getAccessibilityFocusedHost() == this); 9941 } 9942 9943 /** 9944 * Filter the touch event to apply security policies. 9945 * 9946 * @param event The motion event to be filtered. 9947 * @return True if the event should be dispatched, false if the event should be dropped. 9948 * 9949 * @see #getFilterTouchesWhenObscured 9950 */ 9951 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9952 //noinspection RedundantIfStatement 9953 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9954 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9955 // Window is obscured, drop this touch. 9956 return false; 9957 } 9958 return true; 9959 } 9960 9961 /** 9962 * Pass a trackball motion event down to the focused view. 9963 * 9964 * @param event The motion event to be dispatched. 9965 * @return True if the event was handled by the view, false otherwise. 9966 */ 9967 public boolean dispatchTrackballEvent(MotionEvent event) { 9968 if (mInputEventConsistencyVerifier != null) { 9969 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9970 } 9971 9972 return onTrackballEvent(event); 9973 } 9974 9975 /** 9976 * Dispatch a generic motion event. 9977 * <p> 9978 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9979 * are delivered to the view under the pointer. All other generic motion events are 9980 * delivered to the focused view. Hover events are handled specially and are delivered 9981 * to {@link #onHoverEvent(MotionEvent)}. 9982 * </p> 9983 * 9984 * @param event The motion event to be dispatched. 9985 * @return True if the event was handled by the view, false otherwise. 9986 */ 9987 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9988 if (mInputEventConsistencyVerifier != null) { 9989 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 9990 } 9991 9992 final int source = event.getSource(); 9993 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 9994 final int action = event.getAction(); 9995 if (action == MotionEvent.ACTION_HOVER_ENTER 9996 || action == MotionEvent.ACTION_HOVER_MOVE 9997 || action == MotionEvent.ACTION_HOVER_EXIT) { 9998 if (dispatchHoverEvent(event)) { 9999 return true; 10000 } 10001 } else if (dispatchGenericPointerEvent(event)) { 10002 return true; 10003 } 10004 } else if (dispatchGenericFocusedEvent(event)) { 10005 return true; 10006 } 10007 10008 if (dispatchGenericMotionEventInternal(event)) { 10009 return true; 10010 } 10011 10012 if (mInputEventConsistencyVerifier != null) { 10013 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10014 } 10015 return false; 10016 } 10017 10018 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 10019 //noinspection SimplifiableIfStatement 10020 ListenerInfo li = mListenerInfo; 10021 if (li != null && li.mOnGenericMotionListener != null 10022 && (mViewFlags & ENABLED_MASK) == ENABLED 10023 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 10024 return true; 10025 } 10026 10027 if (onGenericMotionEvent(event)) { 10028 return true; 10029 } 10030 10031 final int actionButton = event.getActionButton(); 10032 switch (event.getActionMasked()) { 10033 case MotionEvent.ACTION_BUTTON_PRESS: 10034 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 10035 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10036 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10037 if (performContextClick()) { 10038 mInContextButtonPress = true; 10039 setPressed(true, event.getX(), event.getY()); 10040 removeTapCallback(); 10041 removeLongPressCallback(); 10042 return true; 10043 } 10044 } 10045 break; 10046 10047 case MotionEvent.ACTION_BUTTON_RELEASE: 10048 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 10049 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 10050 mInContextButtonPress = false; 10051 mIgnoreNextUpEvent = true; 10052 } 10053 break; 10054 } 10055 10056 if (mInputEventConsistencyVerifier != null) { 10057 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 10058 } 10059 return false; 10060 } 10061 10062 /** 10063 * Dispatch a hover event. 10064 * <p> 10065 * Do not call this method directly. 10066 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10067 * </p> 10068 * 10069 * @param event The motion event to be dispatched. 10070 * @return True if the event was handled by the view, false otherwise. 10071 */ 10072 protected boolean dispatchHoverEvent(MotionEvent event) { 10073 ListenerInfo li = mListenerInfo; 10074 //noinspection SimplifiableIfStatement 10075 if (li != null && li.mOnHoverListener != null 10076 && (mViewFlags & ENABLED_MASK) == ENABLED 10077 && li.mOnHoverListener.onHover(this, event)) { 10078 return true; 10079 } 10080 10081 return onHoverEvent(event); 10082 } 10083 10084 /** 10085 * Returns true if the view has a child to which it has recently sent 10086 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10087 * it does not have a hovered child, then it must be the innermost hovered view. 10088 * @hide 10089 */ 10090 protected boolean hasHoveredChild() { 10091 return false; 10092 } 10093 10094 /** 10095 * Dispatch a generic motion event to the view under the first pointer. 10096 * <p> 10097 * Do not call this method directly. 10098 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10099 * </p> 10100 * 10101 * @param event The motion event to be dispatched. 10102 * @return True if the event was handled by the view, false otherwise. 10103 */ 10104 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10105 return false; 10106 } 10107 10108 /** 10109 * Dispatch a generic motion event to the currently focused view. 10110 * <p> 10111 * Do not call this method directly. 10112 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10113 * </p> 10114 * 10115 * @param event The motion event to be dispatched. 10116 * @return True if the event was handled by the view, false otherwise. 10117 */ 10118 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10119 return false; 10120 } 10121 10122 /** 10123 * Dispatch a pointer event. 10124 * <p> 10125 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10126 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10127 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10128 * and should not be expected to handle other pointing device features. 10129 * </p> 10130 * 10131 * @param event The motion event to be dispatched. 10132 * @return True if the event was handled by the view, false otherwise. 10133 * @hide 10134 */ 10135 public final boolean dispatchPointerEvent(MotionEvent event) { 10136 if (event.isTouchEvent()) { 10137 return dispatchTouchEvent(event); 10138 } else { 10139 return dispatchGenericMotionEvent(event); 10140 } 10141 } 10142 10143 /** 10144 * Called when the window containing this view gains or loses window focus. 10145 * ViewGroups should override to route to their children. 10146 * 10147 * @param hasFocus True if the window containing this view now has focus, 10148 * false otherwise. 10149 */ 10150 public void dispatchWindowFocusChanged(boolean hasFocus) { 10151 onWindowFocusChanged(hasFocus); 10152 } 10153 10154 /** 10155 * Called when the window containing this view gains or loses focus. Note 10156 * that this is separate from view focus: to receive key events, both 10157 * your view and its window must have focus. If a window is displayed 10158 * on top of yours that takes input focus, then your own window will lose 10159 * focus but the view focus will remain unchanged. 10160 * 10161 * @param hasWindowFocus True if the window containing this view now has 10162 * focus, false otherwise. 10163 */ 10164 public void onWindowFocusChanged(boolean hasWindowFocus) { 10165 InputMethodManager imm = InputMethodManager.peekInstance(); 10166 if (!hasWindowFocus) { 10167 if (isPressed()) { 10168 setPressed(false); 10169 } 10170 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10171 imm.focusOut(this); 10172 } 10173 removeLongPressCallback(); 10174 removeTapCallback(); 10175 onFocusLost(); 10176 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10177 imm.focusIn(this); 10178 } 10179 refreshDrawableState(); 10180 } 10181 10182 /** 10183 * Returns true if this view is in a window that currently has window focus. 10184 * Note that this is not the same as the view itself having focus. 10185 * 10186 * @return True if this view is in a window that currently has window focus. 10187 */ 10188 public boolean hasWindowFocus() { 10189 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10190 } 10191 10192 /** 10193 * Dispatch a view visibility change down the view hierarchy. 10194 * ViewGroups should override to route to their children. 10195 * @param changedView The view whose visibility changed. Could be 'this' or 10196 * an ancestor view. 10197 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10198 * {@link #INVISIBLE} or {@link #GONE}. 10199 */ 10200 protected void dispatchVisibilityChanged(@NonNull View changedView, 10201 @Visibility int visibility) { 10202 onVisibilityChanged(changedView, visibility); 10203 } 10204 10205 /** 10206 * Called when the visibility of the view or an ancestor of the view has 10207 * changed. 10208 * 10209 * @param changedView The view whose visibility changed. May be 10210 * {@code this} or an ancestor view. 10211 * @param visibility The new visibility, one of {@link #VISIBLE}, 10212 * {@link #INVISIBLE} or {@link #GONE}. 10213 */ 10214 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10215 } 10216 10217 /** 10218 * Dispatch a hint about whether this view is displayed. For instance, when 10219 * a View moves out of the screen, it might receives a display hint indicating 10220 * the view is not displayed. Applications should not <em>rely</em> on this hint 10221 * as there is no guarantee that they will receive one. 10222 * 10223 * @param hint A hint about whether or not this view is displayed: 10224 * {@link #VISIBLE} or {@link #INVISIBLE}. 10225 */ 10226 public void dispatchDisplayHint(@Visibility int hint) { 10227 onDisplayHint(hint); 10228 } 10229 10230 /** 10231 * Gives this view a hint about whether is displayed or not. For instance, when 10232 * a View moves out of the screen, it might receives a display hint indicating 10233 * the view is not displayed. Applications should not <em>rely</em> on this hint 10234 * as there is no guarantee that they will receive one. 10235 * 10236 * @param hint A hint about whether or not this view is displayed: 10237 * {@link #VISIBLE} or {@link #INVISIBLE}. 10238 */ 10239 protected void onDisplayHint(@Visibility int hint) { 10240 } 10241 10242 /** 10243 * Dispatch a window visibility change down the view hierarchy. 10244 * ViewGroups should override to route to their children. 10245 * 10246 * @param visibility The new visibility of the window. 10247 * 10248 * @see #onWindowVisibilityChanged(int) 10249 */ 10250 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10251 onWindowVisibilityChanged(visibility); 10252 } 10253 10254 /** 10255 * Called when the window containing has change its visibility 10256 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10257 * that this tells you whether or not your window is being made visible 10258 * to the window manager; this does <em>not</em> tell you whether or not 10259 * your window is obscured by other windows on the screen, even if it 10260 * is itself visible. 10261 * 10262 * @param visibility The new visibility of the window. 10263 */ 10264 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10265 if (visibility == VISIBLE) { 10266 initialAwakenScrollBars(); 10267 } 10268 } 10269 10270 /** 10271 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 10272 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 10273 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 10274 * 10275 * @param isVisible true if this view's visibility to the user is uninterrupted by its 10276 * ancestors or by window visibility 10277 * @return true if this view is visible to the user, not counting clipping or overlapping 10278 */ 10279 @Visibility boolean dispatchVisibilityAggregated(boolean isVisible) { 10280 final boolean thisVisible = getVisibility() == VISIBLE; 10281 // If we're not visible but something is telling us we are, ignore it. 10282 if (thisVisible || !isVisible) { 10283 onVisibilityAggregated(isVisible); 10284 } 10285 return thisVisible && isVisible; 10286 } 10287 10288 /** 10289 * Called when the user-visibility of this View is potentially affected by a change 10290 * to this view itself, an ancestor view or the window this view is attached to. 10291 * 10292 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 10293 * and this view's window is also visible 10294 */ 10295 @CallSuper 10296 public void onVisibilityAggregated(boolean isVisible) { 10297 if (isVisible && mAttachInfo != null) { 10298 initialAwakenScrollBars(); 10299 } 10300 10301 final Drawable dr = mBackground; 10302 if (dr != null && isVisible != dr.isVisible()) { 10303 dr.setVisible(isVisible, false); 10304 } 10305 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10306 if (fg != null && isVisible != fg.isVisible()) { 10307 fg.setVisible(isVisible, false); 10308 } 10309 } 10310 10311 /** 10312 * Returns the current visibility of the window this view is attached to 10313 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10314 * 10315 * @return Returns the current visibility of the view's window. 10316 */ 10317 @Visibility 10318 public int getWindowVisibility() { 10319 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10320 } 10321 10322 /** 10323 * Retrieve the overall visible display size in which the window this view is 10324 * attached to has been positioned in. This takes into account screen 10325 * decorations above the window, for both cases where the window itself 10326 * is being position inside of them or the window is being placed under 10327 * then and covered insets are used for the window to position its content 10328 * inside. In effect, this tells you the available area where content can 10329 * be placed and remain visible to users. 10330 * 10331 * <p>This function requires an IPC back to the window manager to retrieve 10332 * the requested information, so should not be used in performance critical 10333 * code like drawing. 10334 * 10335 * @param outRect Filled in with the visible display frame. If the view 10336 * is not attached to a window, this is simply the raw display size. 10337 */ 10338 public void getWindowVisibleDisplayFrame(Rect outRect) { 10339 if (mAttachInfo != null) { 10340 try { 10341 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10342 } catch (RemoteException e) { 10343 return; 10344 } 10345 // XXX This is really broken, and probably all needs to be done 10346 // in the window manager, and we need to know more about whether 10347 // we want the area behind or in front of the IME. 10348 final Rect insets = mAttachInfo.mVisibleInsets; 10349 outRect.left += insets.left; 10350 outRect.top += insets.top; 10351 outRect.right -= insets.right; 10352 outRect.bottom -= insets.bottom; 10353 return; 10354 } 10355 // The view is not attached to a display so we don't have a context. 10356 // Make a best guess about the display size. 10357 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10358 d.getRectSize(outRect); 10359 } 10360 10361 /** 10362 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 10363 * is currently in without any insets. 10364 * 10365 * @hide 10366 */ 10367 public void getWindowDisplayFrame(Rect outRect) { 10368 if (mAttachInfo != null) { 10369 try { 10370 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10371 } catch (RemoteException e) { 10372 return; 10373 } 10374 return; 10375 } 10376 // The view is not attached to a display so we don't have a context. 10377 // Make a best guess about the display size. 10378 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10379 d.getRectSize(outRect); 10380 } 10381 10382 /** 10383 * Dispatch a notification about a resource configuration change down 10384 * the view hierarchy. 10385 * ViewGroups should override to route to their children. 10386 * 10387 * @param newConfig The new resource configuration. 10388 * 10389 * @see #onConfigurationChanged(android.content.res.Configuration) 10390 */ 10391 public void dispatchConfigurationChanged(Configuration newConfig) { 10392 onConfigurationChanged(newConfig); 10393 } 10394 10395 /** 10396 * Called when the current configuration of the resources being used 10397 * by the application have changed. You can use this to decide when 10398 * to reload resources that can changed based on orientation and other 10399 * configuration characteristics. You only need to use this if you are 10400 * not relying on the normal {@link android.app.Activity} mechanism of 10401 * recreating the activity instance upon a configuration change. 10402 * 10403 * @param newConfig The new resource configuration. 10404 */ 10405 protected void onConfigurationChanged(Configuration newConfig) { 10406 } 10407 10408 /** 10409 * Private function to aggregate all per-view attributes in to the view 10410 * root. 10411 */ 10412 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10413 performCollectViewAttributes(attachInfo, visibility); 10414 } 10415 10416 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10417 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10418 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10419 attachInfo.mKeepScreenOn = true; 10420 } 10421 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10422 ListenerInfo li = mListenerInfo; 10423 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10424 attachInfo.mHasSystemUiListeners = true; 10425 } 10426 } 10427 } 10428 10429 void needGlobalAttributesUpdate(boolean force) { 10430 final AttachInfo ai = mAttachInfo; 10431 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10432 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10433 || ai.mHasSystemUiListeners) { 10434 ai.mRecomputeGlobalAttributes = true; 10435 } 10436 } 10437 } 10438 10439 /** 10440 * Returns whether the device is currently in touch mode. Touch mode is entered 10441 * once the user begins interacting with the device by touch, and affects various 10442 * things like whether focus is always visible to the user. 10443 * 10444 * @return Whether the device is in touch mode. 10445 */ 10446 @ViewDebug.ExportedProperty 10447 public boolean isInTouchMode() { 10448 if (mAttachInfo != null) { 10449 return mAttachInfo.mInTouchMode; 10450 } else { 10451 return ViewRootImpl.isInTouchMode(); 10452 } 10453 } 10454 10455 /** 10456 * Returns the context the view is running in, through which it can 10457 * access the current theme, resources, etc. 10458 * 10459 * @return The view's Context. 10460 */ 10461 @ViewDebug.CapturedViewProperty 10462 public final Context getContext() { 10463 return mContext; 10464 } 10465 10466 /** 10467 * Handle a key event before it is processed by any input method 10468 * associated with the view hierarchy. This can be used to intercept 10469 * key events in special situations before the IME consumes them; a 10470 * typical example would be handling the BACK key to update the application's 10471 * UI instead of allowing the IME to see it and close itself. 10472 * 10473 * @param keyCode The value in event.getKeyCode(). 10474 * @param event Description of the key event. 10475 * @return If you handled the event, return true. If you want to allow the 10476 * event to be handled by the next receiver, return false. 10477 */ 10478 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10479 return false; 10480 } 10481 10482 /** 10483 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10484 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10485 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10486 * is released, if the view is enabled and clickable. 10487 * <p> 10488 * Key presses in software keyboards will generally NOT trigger this 10489 * listener, although some may elect to do so in some situations. Do not 10490 * rely on this to catch software key presses. 10491 * 10492 * @param keyCode a key code that represents the button pressed, from 10493 * {@link android.view.KeyEvent} 10494 * @param event the KeyEvent object that defines the button action 10495 */ 10496 public boolean onKeyDown(int keyCode, KeyEvent event) { 10497 if (KeyEvent.isConfirmKey(keyCode)) { 10498 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10499 return true; 10500 } 10501 10502 // Long clickable items don't necessarily have to be clickable. 10503 if (((mViewFlags & CLICKABLE) == CLICKABLE 10504 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10505 && (event.getRepeatCount() == 0)) { 10506 // For the purposes of menu anchoring and drawable hotspots, 10507 // key events are considered to be at the center of the view. 10508 final float x = getWidth() / 2f; 10509 final float y = getHeight() / 2f; 10510 setPressed(true, x, y); 10511 checkForLongClick(0, x, y); 10512 return true; 10513 } 10514 } 10515 10516 return false; 10517 } 10518 10519 /** 10520 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10521 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10522 * the event). 10523 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10524 * although some may elect to do so in some situations. Do not rely on this to 10525 * catch software key presses. 10526 */ 10527 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10528 return false; 10529 } 10530 10531 /** 10532 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10533 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10534 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10535 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10536 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10537 * although some may elect to do so in some situations. Do not rely on this to 10538 * catch software key presses. 10539 * 10540 * @param keyCode A key code that represents the button pressed, from 10541 * {@link android.view.KeyEvent}. 10542 * @param event The KeyEvent object that defines the button action. 10543 */ 10544 public boolean onKeyUp(int keyCode, KeyEvent event) { 10545 if (KeyEvent.isConfirmKey(keyCode)) { 10546 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10547 return true; 10548 } 10549 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10550 setPressed(false); 10551 10552 if (!mHasPerformedLongPress) { 10553 // This is a tap, so remove the longpress check 10554 removeLongPressCallback(); 10555 return performClick(); 10556 } 10557 } 10558 } 10559 return false; 10560 } 10561 10562 /** 10563 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10564 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10565 * the event). 10566 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10567 * although some may elect to do so in some situations. Do not rely on this to 10568 * catch software key presses. 10569 * 10570 * @param keyCode A key code that represents the button pressed, from 10571 * {@link android.view.KeyEvent}. 10572 * @param repeatCount The number of times the action was made. 10573 * @param event The KeyEvent object that defines the button action. 10574 */ 10575 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10576 return false; 10577 } 10578 10579 /** 10580 * Called on the focused view when a key shortcut event is not handled. 10581 * Override this method to implement local key shortcuts for the View. 10582 * Key shortcuts can also be implemented by setting the 10583 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10584 * 10585 * @param keyCode The value in event.getKeyCode(). 10586 * @param event Description of the key event. 10587 * @return If you handled the event, return true. If you want to allow the 10588 * event to be handled by the next receiver, return false. 10589 */ 10590 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10591 return false; 10592 } 10593 10594 /** 10595 * Check whether the called view is a text editor, in which case it 10596 * would make sense to automatically display a soft input window for 10597 * it. Subclasses should override this if they implement 10598 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10599 * a call on that method would return a non-null InputConnection, and 10600 * they are really a first-class editor that the user would normally 10601 * start typing on when the go into a window containing your view. 10602 * 10603 * <p>The default implementation always returns false. This does 10604 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10605 * will not be called or the user can not otherwise perform edits on your 10606 * view; it is just a hint to the system that this is not the primary 10607 * purpose of this view. 10608 * 10609 * @return Returns true if this view is a text editor, else false. 10610 */ 10611 public boolean onCheckIsTextEditor() { 10612 return false; 10613 } 10614 10615 /** 10616 * Create a new InputConnection for an InputMethod to interact 10617 * with the view. The default implementation returns null, since it doesn't 10618 * support input methods. You can override this to implement such support. 10619 * This is only needed for views that take focus and text input. 10620 * 10621 * <p>When implementing this, you probably also want to implement 10622 * {@link #onCheckIsTextEditor()} to indicate you will return a 10623 * non-null InputConnection.</p> 10624 * 10625 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10626 * object correctly and in its entirety, so that the connected IME can rely 10627 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10628 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10629 * must be filled in with the correct cursor position for IMEs to work correctly 10630 * with your application.</p> 10631 * 10632 * @param outAttrs Fill in with attribute information about the connection. 10633 */ 10634 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10635 return null; 10636 } 10637 10638 /** 10639 * Called by the {@link android.view.inputmethod.InputMethodManager} 10640 * when a view who is not the current 10641 * input connection target is trying to make a call on the manager. The 10642 * default implementation returns false; you can override this to return 10643 * true for certain views if you are performing InputConnection proxying 10644 * to them. 10645 * @param view The View that is making the InputMethodManager call. 10646 * @return Return true to allow the call, false to reject. 10647 */ 10648 public boolean checkInputConnectionProxy(View view) { 10649 return false; 10650 } 10651 10652 /** 10653 * Show the context menu for this view. It is not safe to hold on to the 10654 * menu after returning from this method. 10655 * 10656 * You should normally not overload this method. Overload 10657 * {@link #onCreateContextMenu(ContextMenu)} or define an 10658 * {@link OnCreateContextMenuListener} to add items to the context menu. 10659 * 10660 * @param menu The context menu to populate 10661 */ 10662 public void createContextMenu(ContextMenu menu) { 10663 ContextMenuInfo menuInfo = getContextMenuInfo(); 10664 10665 // Sets the current menu info so all items added to menu will have 10666 // my extra info set. 10667 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10668 10669 onCreateContextMenu(menu); 10670 ListenerInfo li = mListenerInfo; 10671 if (li != null && li.mOnCreateContextMenuListener != null) { 10672 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10673 } 10674 10675 // Clear the extra information so subsequent items that aren't mine don't 10676 // have my extra info. 10677 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10678 10679 if (mParent != null) { 10680 mParent.createContextMenu(menu); 10681 } 10682 } 10683 10684 /** 10685 * Views should implement this if they have extra information to associate 10686 * with the context menu. The return result is supplied as a parameter to 10687 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10688 * callback. 10689 * 10690 * @return Extra information about the item for which the context menu 10691 * should be shown. This information will vary across different 10692 * subclasses of View. 10693 */ 10694 protected ContextMenuInfo getContextMenuInfo() { 10695 return null; 10696 } 10697 10698 /** 10699 * Views should implement this if the view itself is going to add items to 10700 * the context menu. 10701 * 10702 * @param menu the context menu to populate 10703 */ 10704 protected void onCreateContextMenu(ContextMenu menu) { 10705 } 10706 10707 /** 10708 * Implement this method to handle trackball motion events. The 10709 * <em>relative</em> movement of the trackball since the last event 10710 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10711 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10712 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10713 * they will often be fractional values, representing the more fine-grained 10714 * movement information available from a trackball). 10715 * 10716 * @param event The motion event. 10717 * @return True if the event was handled, false otherwise. 10718 */ 10719 public boolean onTrackballEvent(MotionEvent event) { 10720 return false; 10721 } 10722 10723 /** 10724 * Implement this method to handle generic motion events. 10725 * <p> 10726 * Generic motion events describe joystick movements, mouse hovers, track pad 10727 * touches, scroll wheel movements and other input events. The 10728 * {@link MotionEvent#getSource() source} of the motion event specifies 10729 * the class of input that was received. Implementations of this method 10730 * must examine the bits in the source before processing the event. 10731 * The following code example shows how this is done. 10732 * </p><p> 10733 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10734 * are delivered to the view under the pointer. All other generic motion events are 10735 * delivered to the focused view. 10736 * </p> 10737 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10738 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10739 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10740 * // process the joystick movement... 10741 * return true; 10742 * } 10743 * } 10744 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10745 * switch (event.getAction()) { 10746 * case MotionEvent.ACTION_HOVER_MOVE: 10747 * // process the mouse hover movement... 10748 * return true; 10749 * case MotionEvent.ACTION_SCROLL: 10750 * // process the scroll wheel movement... 10751 * return true; 10752 * } 10753 * } 10754 * return super.onGenericMotionEvent(event); 10755 * }</pre> 10756 * 10757 * @param event The generic motion event being processed. 10758 * @return True if the event was handled, false otherwise. 10759 */ 10760 public boolean onGenericMotionEvent(MotionEvent event) { 10761 return false; 10762 } 10763 10764 /** 10765 * Implement this method to handle hover events. 10766 * <p> 10767 * This method is called whenever a pointer is hovering into, over, or out of the 10768 * bounds of a view and the view is not currently being touched. 10769 * Hover events are represented as pointer events with action 10770 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10771 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10772 * </p> 10773 * <ul> 10774 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10775 * when the pointer enters the bounds of the view.</li> 10776 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10777 * when the pointer has already entered the bounds of the view and has moved.</li> 10778 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10779 * when the pointer has exited the bounds of the view or when the pointer is 10780 * about to go down due to a button click, tap, or similar user action that 10781 * causes the view to be touched.</li> 10782 * </ul> 10783 * <p> 10784 * The view should implement this method to return true to indicate that it is 10785 * handling the hover event, such as by changing its drawable state. 10786 * </p><p> 10787 * The default implementation calls {@link #setHovered} to update the hovered state 10788 * of the view when a hover enter or hover exit event is received, if the view 10789 * is enabled and is clickable. The default implementation also sends hover 10790 * accessibility events. 10791 * </p> 10792 * 10793 * @param event The motion event that describes the hover. 10794 * @return True if the view handled the hover event. 10795 * 10796 * @see #isHovered 10797 * @see #setHovered 10798 * @see #onHoverChanged 10799 */ 10800 public boolean onHoverEvent(MotionEvent event) { 10801 // The root view may receive hover (or touch) events that are outside the bounds of 10802 // the window. This code ensures that we only send accessibility events for 10803 // hovers that are actually within the bounds of the root view. 10804 final int action = event.getActionMasked(); 10805 if (!mSendingHoverAccessibilityEvents) { 10806 if ((action == MotionEvent.ACTION_HOVER_ENTER 10807 || action == MotionEvent.ACTION_HOVER_MOVE) 10808 && !hasHoveredChild() 10809 && pointInView(event.getX(), event.getY())) { 10810 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10811 mSendingHoverAccessibilityEvents = true; 10812 } 10813 } else { 10814 if (action == MotionEvent.ACTION_HOVER_EXIT 10815 || (action == MotionEvent.ACTION_MOVE 10816 && !pointInView(event.getX(), event.getY()))) { 10817 mSendingHoverAccessibilityEvents = false; 10818 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10819 } 10820 } 10821 10822 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10823 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10824 && isOnScrollbar(event.getX(), event.getY())) { 10825 awakenScrollBars(); 10826 } 10827 if (isHoverable()) { 10828 switch (action) { 10829 case MotionEvent.ACTION_HOVER_ENTER: 10830 setHovered(true); 10831 break; 10832 case MotionEvent.ACTION_HOVER_EXIT: 10833 setHovered(false); 10834 break; 10835 } 10836 10837 // Dispatch the event to onGenericMotionEvent before returning true. 10838 // This is to provide compatibility with existing applications that 10839 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10840 // break because of the new default handling for hoverable views 10841 // in onHoverEvent. 10842 // Note that onGenericMotionEvent will be called by default when 10843 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10844 dispatchGenericMotionEventInternal(event); 10845 // The event was already handled by calling setHovered(), so always 10846 // return true. 10847 return true; 10848 } 10849 10850 return false; 10851 } 10852 10853 /** 10854 * Returns true if the view should handle {@link #onHoverEvent} 10855 * by calling {@link #setHovered} to change its hovered state. 10856 * 10857 * @return True if the view is hoverable. 10858 */ 10859 private boolean isHoverable() { 10860 final int viewFlags = mViewFlags; 10861 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10862 return false; 10863 } 10864 10865 return (viewFlags & CLICKABLE) == CLICKABLE 10866 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10867 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10868 } 10869 10870 /** 10871 * Returns true if the view is currently hovered. 10872 * 10873 * @return True if the view is currently hovered. 10874 * 10875 * @see #setHovered 10876 * @see #onHoverChanged 10877 */ 10878 @ViewDebug.ExportedProperty 10879 public boolean isHovered() { 10880 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10881 } 10882 10883 /** 10884 * Sets whether the view is currently hovered. 10885 * <p> 10886 * Calling this method also changes the drawable state of the view. This 10887 * enables the view to react to hover by using different drawable resources 10888 * to change its appearance. 10889 * </p><p> 10890 * The {@link #onHoverChanged} method is called when the hovered state changes. 10891 * </p> 10892 * 10893 * @param hovered True if the view is hovered. 10894 * 10895 * @see #isHovered 10896 * @see #onHoverChanged 10897 */ 10898 public void setHovered(boolean hovered) { 10899 if (hovered) { 10900 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10901 mPrivateFlags |= PFLAG_HOVERED; 10902 refreshDrawableState(); 10903 onHoverChanged(true); 10904 } 10905 } else { 10906 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10907 mPrivateFlags &= ~PFLAG_HOVERED; 10908 refreshDrawableState(); 10909 onHoverChanged(false); 10910 } 10911 } 10912 } 10913 10914 /** 10915 * Implement this method to handle hover state changes. 10916 * <p> 10917 * This method is called whenever the hover state changes as a result of a 10918 * call to {@link #setHovered}. 10919 * </p> 10920 * 10921 * @param hovered The current hover state, as returned by {@link #isHovered}. 10922 * 10923 * @see #isHovered 10924 * @see #setHovered 10925 */ 10926 public void onHoverChanged(boolean hovered) { 10927 } 10928 10929 /** 10930 * Handles scroll bar dragging by mouse input. 10931 * 10932 * @hide 10933 * @param event The motion event. 10934 * 10935 * @return true if the event was handled as a scroll bar dragging, false otherwise. 10936 */ 10937 protected boolean handleScrollBarDragging(MotionEvent event) { 10938 if (mScrollCache == null) { 10939 return false; 10940 } 10941 final float x = event.getX(); 10942 final float y = event.getY(); 10943 final int action = event.getAction(); 10944 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 10945 && action != MotionEvent.ACTION_DOWN) 10946 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 10947 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 10948 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10949 return false; 10950 } 10951 10952 switch (action) { 10953 case MotionEvent.ACTION_MOVE: 10954 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 10955 return false; 10956 } 10957 if (mScrollCache.mScrollBarDraggingState 10958 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 10959 final Rect bounds = mScrollCache.mScrollBarBounds; 10960 getVerticalScrollBarBounds(bounds); 10961 final int range = computeVerticalScrollRange(); 10962 final int offset = computeVerticalScrollOffset(); 10963 final int extent = computeVerticalScrollExtent(); 10964 10965 final int thumbLength = ScrollBarUtils.getThumbLength( 10966 bounds.height(), bounds.width(), extent, range); 10967 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10968 bounds.height(), thumbLength, extent, range, offset); 10969 10970 final float diff = y - mScrollCache.mScrollBarDraggingPos; 10971 final float maxThumbOffset = bounds.height() - thumbLength; 10972 final float newThumbOffset = 10973 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10974 final int height = getHeight(); 10975 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10976 && height > 0 && extent > 0) { 10977 final int newY = Math.round((range - extent) 10978 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 10979 if (newY != getScrollY()) { 10980 mScrollCache.mScrollBarDraggingPos = y; 10981 setScrollY(newY); 10982 } 10983 } 10984 return true; 10985 } 10986 if (mScrollCache.mScrollBarDraggingState 10987 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 10988 final Rect bounds = mScrollCache.mScrollBarBounds; 10989 getHorizontalScrollBarBounds(bounds); 10990 final int range = computeHorizontalScrollRange(); 10991 final int offset = computeHorizontalScrollOffset(); 10992 final int extent = computeHorizontalScrollExtent(); 10993 10994 final int thumbLength = ScrollBarUtils.getThumbLength( 10995 bounds.width(), bounds.height(), extent, range); 10996 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10997 bounds.width(), thumbLength, extent, range, offset); 10998 10999 final float diff = x - mScrollCache.mScrollBarDraggingPos; 11000 final float maxThumbOffset = bounds.width() - thumbLength; 11001 final float newThumbOffset = 11002 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 11003 final int width = getWidth(); 11004 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 11005 && width > 0 && extent > 0) { 11006 final int newX = Math.round((range - extent) 11007 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 11008 if (newX != getScrollX()) { 11009 mScrollCache.mScrollBarDraggingPos = x; 11010 setScrollX(newX); 11011 } 11012 } 11013 return true; 11014 } 11015 case MotionEvent.ACTION_DOWN: 11016 if (mScrollCache.state == ScrollabilityCache.OFF) { 11017 return false; 11018 } 11019 if (isOnVerticalScrollbarThumb(x, y)) { 11020 mScrollCache.mScrollBarDraggingState = 11021 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 11022 mScrollCache.mScrollBarDraggingPos = y; 11023 return true; 11024 } 11025 if (isOnHorizontalScrollbarThumb(x, y)) { 11026 mScrollCache.mScrollBarDraggingState = 11027 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 11028 mScrollCache.mScrollBarDraggingPos = x; 11029 return true; 11030 } 11031 } 11032 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 11033 return false; 11034 } 11035 11036 /** 11037 * Implement this method to handle touch screen motion events. 11038 * <p> 11039 * If this method is used to detect click actions, it is recommended that 11040 * the actions be performed by implementing and calling 11041 * {@link #performClick()}. This will ensure consistent system behavior, 11042 * including: 11043 * <ul> 11044 * <li>obeying click sound preferences 11045 * <li>dispatching OnClickListener calls 11046 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 11047 * accessibility features are enabled 11048 * </ul> 11049 * 11050 * @param event The motion event. 11051 * @return True if the event was handled, false otherwise. 11052 */ 11053 public boolean onTouchEvent(MotionEvent event) { 11054 final float x = event.getX(); 11055 final float y = event.getY(); 11056 final int viewFlags = mViewFlags; 11057 final int action = event.getAction(); 11058 11059 if ((viewFlags & ENABLED_MASK) == DISABLED) { 11060 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 11061 setPressed(false); 11062 } 11063 // A disabled view that is clickable still consumes the touch 11064 // events, it just doesn't respond to them. 11065 return (((viewFlags & CLICKABLE) == CLICKABLE 11066 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 11067 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 11068 } 11069 if (mTouchDelegate != null) { 11070 if (mTouchDelegate.onTouchEvent(event)) { 11071 return true; 11072 } 11073 } 11074 11075 if (((viewFlags & CLICKABLE) == CLICKABLE || 11076 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 11077 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 11078 switch (action) { 11079 case MotionEvent.ACTION_UP: 11080 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 11081 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 11082 // take focus if we don't have it already and we should in 11083 // touch mode. 11084 boolean focusTaken = false; 11085 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 11086 focusTaken = requestFocus(); 11087 } 11088 11089 if (prepressed) { 11090 // The button is being released before we actually 11091 // showed it as pressed. Make it show the pressed 11092 // state now (before scheduling the click) to ensure 11093 // the user sees it. 11094 setPressed(true, x, y); 11095 } 11096 11097 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 11098 // This is a tap, so remove the longpress check 11099 removeLongPressCallback(); 11100 11101 // Only perform take click actions if we were in the pressed state 11102 if (!focusTaken) { 11103 // Use a Runnable and post this rather than calling 11104 // performClick directly. This lets other visual state 11105 // of the view update before click actions start. 11106 if (mPerformClick == null) { 11107 mPerformClick = new PerformClick(); 11108 } 11109 if (!post(mPerformClick)) { 11110 performClick(); 11111 } 11112 } 11113 } 11114 11115 if (mUnsetPressedState == null) { 11116 mUnsetPressedState = new UnsetPressedState(); 11117 } 11118 11119 if (prepressed) { 11120 postDelayed(mUnsetPressedState, 11121 ViewConfiguration.getPressedStateDuration()); 11122 } else if (!post(mUnsetPressedState)) { 11123 // If the post failed, unpress right now 11124 mUnsetPressedState.run(); 11125 } 11126 11127 removeTapCallback(); 11128 } 11129 mIgnoreNextUpEvent = false; 11130 break; 11131 11132 case MotionEvent.ACTION_DOWN: 11133 mHasPerformedLongPress = false; 11134 11135 if (performButtonActionOnTouchDown(event)) { 11136 break; 11137 } 11138 11139 // Walk up the hierarchy to determine if we're inside a scrolling container. 11140 boolean isInScrollingContainer = isInScrollingContainer(); 11141 11142 // For views inside a scrolling container, delay the pressed feedback for 11143 // a short period in case this is a scroll. 11144 if (isInScrollingContainer) { 11145 mPrivateFlags |= PFLAG_PREPRESSED; 11146 if (mPendingCheckForTap == null) { 11147 mPendingCheckForTap = new CheckForTap(); 11148 } 11149 mPendingCheckForTap.x = event.getX(); 11150 mPendingCheckForTap.y = event.getY(); 11151 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11152 } else { 11153 // Not inside a scrolling container, so show the feedback right away 11154 setPressed(true, x, y); 11155 checkForLongClick(0, x, y); 11156 } 11157 break; 11158 11159 case MotionEvent.ACTION_CANCEL: 11160 setPressed(false); 11161 removeTapCallback(); 11162 removeLongPressCallback(); 11163 mInContextButtonPress = false; 11164 mHasPerformedLongPress = false; 11165 mIgnoreNextUpEvent = false; 11166 break; 11167 11168 case MotionEvent.ACTION_MOVE: 11169 drawableHotspotChanged(x, y); 11170 11171 // Be lenient about moving outside of buttons 11172 if (!pointInView(x, y, mTouchSlop)) { 11173 // Outside button 11174 removeTapCallback(); 11175 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11176 // Remove any future long press/tap checks 11177 removeLongPressCallback(); 11178 11179 setPressed(false); 11180 } 11181 } 11182 break; 11183 } 11184 11185 return true; 11186 } 11187 11188 return false; 11189 } 11190 11191 /** 11192 * @hide 11193 */ 11194 public boolean isInScrollingContainer() { 11195 ViewParent p = getParent(); 11196 while (p != null && p instanceof ViewGroup) { 11197 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11198 return true; 11199 } 11200 p = p.getParent(); 11201 } 11202 return false; 11203 } 11204 11205 /** 11206 * Remove the longpress detection timer. 11207 */ 11208 private void removeLongPressCallback() { 11209 if (mPendingCheckForLongPress != null) { 11210 removeCallbacks(mPendingCheckForLongPress); 11211 } 11212 } 11213 11214 /** 11215 * Remove the pending click action 11216 */ 11217 private void removePerformClickCallback() { 11218 if (mPerformClick != null) { 11219 removeCallbacks(mPerformClick); 11220 } 11221 } 11222 11223 /** 11224 * Remove the prepress detection timer. 11225 */ 11226 private void removeUnsetPressCallback() { 11227 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11228 setPressed(false); 11229 removeCallbacks(mUnsetPressedState); 11230 } 11231 } 11232 11233 /** 11234 * Remove the tap detection timer. 11235 */ 11236 private void removeTapCallback() { 11237 if (mPendingCheckForTap != null) { 11238 mPrivateFlags &= ~PFLAG_PREPRESSED; 11239 removeCallbacks(mPendingCheckForTap); 11240 } 11241 } 11242 11243 /** 11244 * Cancels a pending long press. Your subclass can use this if you 11245 * want the context menu to come up if the user presses and holds 11246 * at the same place, but you don't want it to come up if they press 11247 * and then move around enough to cause scrolling. 11248 */ 11249 public void cancelLongPress() { 11250 removeLongPressCallback(); 11251 11252 /* 11253 * The prepressed state handled by the tap callback is a display 11254 * construct, but the tap callback will post a long press callback 11255 * less its own timeout. Remove it here. 11256 */ 11257 removeTapCallback(); 11258 } 11259 11260 /** 11261 * Remove the pending callback for sending a 11262 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11263 */ 11264 private void removeSendViewScrolledAccessibilityEventCallback() { 11265 if (mSendViewScrolledAccessibilityEvent != null) { 11266 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11267 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11268 } 11269 } 11270 11271 /** 11272 * Sets the TouchDelegate for this View. 11273 */ 11274 public void setTouchDelegate(TouchDelegate delegate) { 11275 mTouchDelegate = delegate; 11276 } 11277 11278 /** 11279 * Gets the TouchDelegate for this View. 11280 */ 11281 public TouchDelegate getTouchDelegate() { 11282 return mTouchDelegate; 11283 } 11284 11285 /** 11286 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11287 * 11288 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11289 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11290 * available. This method should only be called for touch events. 11291 * 11292 * <p class="note">This api is not intended for most applications. Buffered dispatch 11293 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11294 * streams will not improve your input latency. Side effects include: increased latency, 11295 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11296 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11297 * you.</p> 11298 */ 11299 public final void requestUnbufferedDispatch(MotionEvent event) { 11300 final int action = event.getAction(); 11301 if (mAttachInfo == null 11302 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11303 || !event.isTouchEvent()) { 11304 return; 11305 } 11306 mAttachInfo.mUnbufferedDispatchRequested = true; 11307 } 11308 11309 /** 11310 * Set flags controlling behavior of this view. 11311 * 11312 * @param flags Constant indicating the value which should be set 11313 * @param mask Constant indicating the bit range that should be changed 11314 */ 11315 void setFlags(int flags, int mask) { 11316 final boolean accessibilityEnabled = 11317 AccessibilityManager.getInstance(mContext).isEnabled(); 11318 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11319 11320 int old = mViewFlags; 11321 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11322 11323 int changed = mViewFlags ^ old; 11324 if (changed == 0) { 11325 return; 11326 } 11327 int privateFlags = mPrivateFlags; 11328 11329 /* Check if the FOCUSABLE bit has changed */ 11330 if (((changed & FOCUSABLE_MASK) != 0) && 11331 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11332 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11333 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11334 /* Give up focus if we are no longer focusable */ 11335 clearFocus(); 11336 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11337 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11338 /* 11339 * Tell the view system that we are now available to take focus 11340 * if no one else already has it. 11341 */ 11342 if (mParent != null) mParent.focusableViewAvailable(this); 11343 } 11344 } 11345 11346 final int newVisibility = flags & VISIBILITY_MASK; 11347 if (newVisibility == VISIBLE) { 11348 if ((changed & VISIBILITY_MASK) != 0) { 11349 /* 11350 * If this view is becoming visible, invalidate it in case it changed while 11351 * it was not visible. Marking it drawn ensures that the invalidation will 11352 * go through. 11353 */ 11354 mPrivateFlags |= PFLAG_DRAWN; 11355 invalidate(true); 11356 11357 needGlobalAttributesUpdate(true); 11358 11359 // a view becoming visible is worth notifying the parent 11360 // about in case nothing has focus. even if this specific view 11361 // isn't focusable, it may contain something that is, so let 11362 // the root view try to give this focus if nothing else does. 11363 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11364 mParent.focusableViewAvailable(this); 11365 } 11366 } 11367 } 11368 11369 /* Check if the GONE bit has changed */ 11370 if ((changed & GONE) != 0) { 11371 needGlobalAttributesUpdate(false); 11372 requestLayout(); 11373 11374 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11375 if (hasFocus()) clearFocus(); 11376 clearAccessibilityFocus(); 11377 destroyDrawingCache(); 11378 if (mParent instanceof View) { 11379 // GONE views noop invalidation, so invalidate the parent 11380 ((View) mParent).invalidate(true); 11381 } 11382 // Mark the view drawn to ensure that it gets invalidated properly the next 11383 // time it is visible and gets invalidated 11384 mPrivateFlags |= PFLAG_DRAWN; 11385 } 11386 if (mAttachInfo != null) { 11387 mAttachInfo.mViewVisibilityChanged = true; 11388 } 11389 } 11390 11391 /* Check if the VISIBLE bit has changed */ 11392 if ((changed & INVISIBLE) != 0) { 11393 needGlobalAttributesUpdate(false); 11394 /* 11395 * If this view is becoming invisible, set the DRAWN flag so that 11396 * the next invalidate() will not be skipped. 11397 */ 11398 mPrivateFlags |= PFLAG_DRAWN; 11399 11400 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11401 // root view becoming invisible shouldn't clear focus and accessibility focus 11402 if (getRootView() != this) { 11403 if (hasFocus()) clearFocus(); 11404 clearAccessibilityFocus(); 11405 } 11406 } 11407 if (mAttachInfo != null) { 11408 mAttachInfo.mViewVisibilityChanged = true; 11409 } 11410 } 11411 11412 if ((changed & VISIBILITY_MASK) != 0) { 11413 // If the view is invisible, cleanup its display list to free up resources 11414 if (newVisibility != VISIBLE && mAttachInfo != null) { 11415 cleanupDraw(); 11416 } 11417 11418 if (mParent instanceof ViewGroup) { 11419 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11420 (changed & VISIBILITY_MASK), newVisibility); 11421 ((View) mParent).invalidate(true); 11422 } else if (mParent != null) { 11423 mParent.invalidateChild(this, null); 11424 } 11425 11426 if (mAttachInfo != null) { 11427 dispatchVisibilityChanged(this, newVisibility); 11428 11429 // Aggregated visibility changes are dispatched to attached views 11430 // in visible windows where the parent is currently shown/drawn 11431 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 11432 // discounting clipping or overlapping. This makes it a good place 11433 // to change animation states. 11434 if (mParent != null && getWindowVisibility() == VISIBLE && 11435 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 11436 dispatchVisibilityAggregated(newVisibility == VISIBLE); 11437 } 11438 notifySubtreeAccessibilityStateChangedIfNeeded(); 11439 } 11440 } 11441 11442 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11443 destroyDrawingCache(); 11444 } 11445 11446 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11447 destroyDrawingCache(); 11448 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11449 invalidateParentCaches(); 11450 } 11451 11452 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11453 destroyDrawingCache(); 11454 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11455 } 11456 11457 if ((changed & DRAW_MASK) != 0) { 11458 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11459 if (mBackground != null 11460 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11461 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11462 } else { 11463 mPrivateFlags |= PFLAG_SKIP_DRAW; 11464 } 11465 } else { 11466 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11467 } 11468 requestLayout(); 11469 invalidate(true); 11470 } 11471 11472 if ((changed & KEEP_SCREEN_ON) != 0) { 11473 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11474 mParent.recomputeViewAttributes(this); 11475 } 11476 } 11477 11478 if (accessibilityEnabled) { 11479 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11480 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11481 || (changed & CONTEXT_CLICKABLE) != 0) { 11482 if (oldIncludeForAccessibility != includeForAccessibility()) { 11483 notifySubtreeAccessibilityStateChangedIfNeeded(); 11484 } else { 11485 notifyViewAccessibilityStateChangedIfNeeded( 11486 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11487 } 11488 } else if ((changed & ENABLED_MASK) != 0) { 11489 notifyViewAccessibilityStateChangedIfNeeded( 11490 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11491 } 11492 } 11493 } 11494 11495 /** 11496 * Change the view's z order in the tree, so it's on top of other sibling 11497 * views. This ordering change may affect layout, if the parent container 11498 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11499 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11500 * method should be followed by calls to {@link #requestLayout()} and 11501 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11502 * with the new child ordering. 11503 * 11504 * @see ViewGroup#bringChildToFront(View) 11505 */ 11506 public void bringToFront() { 11507 if (mParent != null) { 11508 mParent.bringChildToFront(this); 11509 } 11510 } 11511 11512 /** 11513 * This is called in response to an internal scroll in this view (i.e., the 11514 * view scrolled its own contents). This is typically as a result of 11515 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11516 * called. 11517 * 11518 * @param l Current horizontal scroll origin. 11519 * @param t Current vertical scroll origin. 11520 * @param oldl Previous horizontal scroll origin. 11521 * @param oldt Previous vertical scroll origin. 11522 */ 11523 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11524 notifySubtreeAccessibilityStateChangedIfNeeded(); 11525 11526 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11527 postSendViewScrolledAccessibilityEventCallback(); 11528 } 11529 11530 mBackgroundSizeChanged = true; 11531 if (mForegroundInfo != null) { 11532 mForegroundInfo.mBoundsChanged = true; 11533 } 11534 11535 final AttachInfo ai = mAttachInfo; 11536 if (ai != null) { 11537 ai.mViewScrollChanged = true; 11538 } 11539 11540 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11541 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11542 } 11543 } 11544 11545 /** 11546 * Interface definition for a callback to be invoked when the scroll 11547 * X or Y positions of a view change. 11548 * <p> 11549 * <b>Note:</b> Some views handle scrolling independently from View and may 11550 * have their own separate listeners for scroll-type events. For example, 11551 * {@link android.widget.ListView ListView} allows clients to register an 11552 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11553 * to listen for changes in list scroll position. 11554 * 11555 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11556 */ 11557 public interface OnScrollChangeListener { 11558 /** 11559 * Called when the scroll position of a view changes. 11560 * 11561 * @param v The view whose scroll position has changed. 11562 * @param scrollX Current horizontal scroll origin. 11563 * @param scrollY Current vertical scroll origin. 11564 * @param oldScrollX Previous horizontal scroll origin. 11565 * @param oldScrollY Previous vertical scroll origin. 11566 */ 11567 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11568 } 11569 11570 /** 11571 * Interface definition for a callback to be invoked when the layout bounds of a view 11572 * changes due to layout processing. 11573 */ 11574 public interface OnLayoutChangeListener { 11575 /** 11576 * Called when the layout bounds of a view changes due to layout processing. 11577 * 11578 * @param v The view whose bounds have changed. 11579 * @param left The new value of the view's left property. 11580 * @param top The new value of the view's top property. 11581 * @param right The new value of the view's right property. 11582 * @param bottom The new value of the view's bottom property. 11583 * @param oldLeft The previous value of the view's left property. 11584 * @param oldTop The previous value of the view's top property. 11585 * @param oldRight The previous value of the view's right property. 11586 * @param oldBottom The previous value of the view's bottom property. 11587 */ 11588 void onLayoutChange(View v, int left, int top, int right, int bottom, 11589 int oldLeft, int oldTop, int oldRight, int oldBottom); 11590 } 11591 11592 /** 11593 * This is called during layout when the size of this view has changed. If 11594 * you were just added to the view hierarchy, you're called with the old 11595 * values of 0. 11596 * 11597 * @param w Current width of this view. 11598 * @param h Current height of this view. 11599 * @param oldw Old width of this view. 11600 * @param oldh Old height of this view. 11601 */ 11602 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11603 } 11604 11605 /** 11606 * Called by draw to draw the child views. This may be overridden 11607 * by derived classes to gain control just before its children are drawn 11608 * (but after its own view has been drawn). 11609 * @param canvas the canvas on which to draw the view 11610 */ 11611 protected void dispatchDraw(Canvas canvas) { 11612 11613 } 11614 11615 /** 11616 * Gets the parent of this view. Note that the parent is a 11617 * ViewParent and not necessarily a View. 11618 * 11619 * @return Parent of this view. 11620 */ 11621 public final ViewParent getParent() { 11622 return mParent; 11623 } 11624 11625 /** 11626 * Set the horizontal scrolled position of your view. This will cause a call to 11627 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11628 * invalidated. 11629 * @param value the x position to scroll to 11630 */ 11631 public void setScrollX(int value) { 11632 scrollTo(value, mScrollY); 11633 } 11634 11635 /** 11636 * Set the vertical scrolled position of your view. This will cause a call to 11637 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11638 * invalidated. 11639 * @param value the y position to scroll to 11640 */ 11641 public void setScrollY(int value) { 11642 scrollTo(mScrollX, value); 11643 } 11644 11645 /** 11646 * Return the scrolled left position of this view. This is the left edge of 11647 * the displayed part of your view. You do not need to draw any pixels 11648 * farther left, since those are outside of the frame of your view on 11649 * screen. 11650 * 11651 * @return The left edge of the displayed part of your view, in pixels. 11652 */ 11653 public final int getScrollX() { 11654 return mScrollX; 11655 } 11656 11657 /** 11658 * Return the scrolled top position of this view. This is the top edge of 11659 * the displayed part of your view. You do not need to draw any pixels above 11660 * it, since those are outside of the frame of your view on screen. 11661 * 11662 * @return The top edge of the displayed part of your view, in pixels. 11663 */ 11664 public final int getScrollY() { 11665 return mScrollY; 11666 } 11667 11668 /** 11669 * Return the width of the your view. 11670 * 11671 * @return The width of your view, in pixels. 11672 */ 11673 @ViewDebug.ExportedProperty(category = "layout") 11674 public final int getWidth() { 11675 return mRight - mLeft; 11676 } 11677 11678 /** 11679 * Return the height of your view. 11680 * 11681 * @return The height of your view, in pixels. 11682 */ 11683 @ViewDebug.ExportedProperty(category = "layout") 11684 public final int getHeight() { 11685 return mBottom - mTop; 11686 } 11687 11688 /** 11689 * Return the visible drawing bounds of your view. Fills in the output 11690 * rectangle with the values from getScrollX(), getScrollY(), 11691 * getWidth(), and getHeight(). These bounds do not account for any 11692 * transformation properties currently set on the view, such as 11693 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11694 * 11695 * @param outRect The (scrolled) drawing bounds of the view. 11696 */ 11697 public void getDrawingRect(Rect outRect) { 11698 outRect.left = mScrollX; 11699 outRect.top = mScrollY; 11700 outRect.right = mScrollX + (mRight - mLeft); 11701 outRect.bottom = mScrollY + (mBottom - mTop); 11702 } 11703 11704 /** 11705 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11706 * raw width component (that is the result is masked by 11707 * {@link #MEASURED_SIZE_MASK}). 11708 * 11709 * @return The raw measured width of this view. 11710 */ 11711 public final int getMeasuredWidth() { 11712 return mMeasuredWidth & MEASURED_SIZE_MASK; 11713 } 11714 11715 /** 11716 * Return the full width measurement information for this view as computed 11717 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11718 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11719 * This should be used during measurement and layout calculations only. Use 11720 * {@link #getWidth()} to see how wide a view is after layout. 11721 * 11722 * @return The measured width of this view as a bit mask. 11723 */ 11724 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11725 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11726 name = "MEASURED_STATE_TOO_SMALL"), 11727 }) 11728 public final int getMeasuredWidthAndState() { 11729 return mMeasuredWidth; 11730 } 11731 11732 /** 11733 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11734 * raw width component (that is the result is masked by 11735 * {@link #MEASURED_SIZE_MASK}). 11736 * 11737 * @return The raw measured height of this view. 11738 */ 11739 public final int getMeasuredHeight() { 11740 return mMeasuredHeight & MEASURED_SIZE_MASK; 11741 } 11742 11743 /** 11744 * Return the full height measurement information for this view as computed 11745 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11746 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11747 * This should be used during measurement and layout calculations only. Use 11748 * {@link #getHeight()} to see how wide a view is after layout. 11749 * 11750 * @return The measured width of this view as a bit mask. 11751 */ 11752 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11753 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11754 name = "MEASURED_STATE_TOO_SMALL"), 11755 }) 11756 public final int getMeasuredHeightAndState() { 11757 return mMeasuredHeight; 11758 } 11759 11760 /** 11761 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11762 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11763 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11764 * and the height component is at the shifted bits 11765 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11766 */ 11767 public final int getMeasuredState() { 11768 return (mMeasuredWidth&MEASURED_STATE_MASK) 11769 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11770 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11771 } 11772 11773 /** 11774 * The transform matrix of this view, which is calculated based on the current 11775 * rotation, scale, and pivot properties. 11776 * 11777 * @see #getRotation() 11778 * @see #getScaleX() 11779 * @see #getScaleY() 11780 * @see #getPivotX() 11781 * @see #getPivotY() 11782 * @return The current transform matrix for the view 11783 */ 11784 public Matrix getMatrix() { 11785 ensureTransformationInfo(); 11786 final Matrix matrix = mTransformationInfo.mMatrix; 11787 mRenderNode.getMatrix(matrix); 11788 return matrix; 11789 } 11790 11791 /** 11792 * Returns true if the transform matrix is the identity matrix. 11793 * Recomputes the matrix if necessary. 11794 * 11795 * @return True if the transform matrix is the identity matrix, false otherwise. 11796 */ 11797 final boolean hasIdentityMatrix() { 11798 return mRenderNode.hasIdentityMatrix(); 11799 } 11800 11801 void ensureTransformationInfo() { 11802 if (mTransformationInfo == null) { 11803 mTransformationInfo = new TransformationInfo(); 11804 } 11805 } 11806 11807 /** 11808 * Utility method to retrieve the inverse of the current mMatrix property. 11809 * We cache the matrix to avoid recalculating it when transform properties 11810 * have not changed. 11811 * 11812 * @return The inverse of the current matrix of this view. 11813 * @hide 11814 */ 11815 public final Matrix getInverseMatrix() { 11816 ensureTransformationInfo(); 11817 if (mTransformationInfo.mInverseMatrix == null) { 11818 mTransformationInfo.mInverseMatrix = new Matrix(); 11819 } 11820 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11821 mRenderNode.getInverseMatrix(matrix); 11822 return matrix; 11823 } 11824 11825 /** 11826 * Gets the distance along the Z axis from the camera to this view. 11827 * 11828 * @see #setCameraDistance(float) 11829 * 11830 * @return The distance along the Z axis. 11831 */ 11832 public float getCameraDistance() { 11833 final float dpi = mResources.getDisplayMetrics().densityDpi; 11834 return -(mRenderNode.getCameraDistance() * dpi); 11835 } 11836 11837 /** 11838 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11839 * views are drawn) from the camera to this view. The camera's distance 11840 * affects 3D transformations, for instance rotations around the X and Y 11841 * axis. If the rotationX or rotationY properties are changed and this view is 11842 * large (more than half the size of the screen), it is recommended to always 11843 * use a camera distance that's greater than the height (X axis rotation) or 11844 * the width (Y axis rotation) of this view.</p> 11845 * 11846 * <p>The distance of the camera from the view plane can have an affect on the 11847 * perspective distortion of the view when it is rotated around the x or y axis. 11848 * For example, a large distance will result in a large viewing angle, and there 11849 * will not be much perspective distortion of the view as it rotates. A short 11850 * distance may cause much more perspective distortion upon rotation, and can 11851 * also result in some drawing artifacts if the rotated view ends up partially 11852 * behind the camera (which is why the recommendation is to use a distance at 11853 * least as far as the size of the view, if the view is to be rotated.)</p> 11854 * 11855 * <p>The distance is expressed in "depth pixels." The default distance depends 11856 * on the screen density. For instance, on a medium density display, the 11857 * default distance is 1280. On a high density display, the default distance 11858 * is 1920.</p> 11859 * 11860 * <p>If you want to specify a distance that leads to visually consistent 11861 * results across various densities, use the following formula:</p> 11862 * <pre> 11863 * float scale = context.getResources().getDisplayMetrics().density; 11864 * view.setCameraDistance(distance * scale); 11865 * </pre> 11866 * 11867 * <p>The density scale factor of a high density display is 1.5, 11868 * and 1920 = 1280 * 1.5.</p> 11869 * 11870 * @param distance The distance in "depth pixels", if negative the opposite 11871 * value is used 11872 * 11873 * @see #setRotationX(float) 11874 * @see #setRotationY(float) 11875 */ 11876 public void setCameraDistance(float distance) { 11877 final float dpi = mResources.getDisplayMetrics().densityDpi; 11878 11879 invalidateViewProperty(true, false); 11880 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11881 invalidateViewProperty(false, false); 11882 11883 invalidateParentIfNeededAndWasQuickRejected(); 11884 } 11885 11886 /** 11887 * The degrees that the view is rotated around the pivot point. 11888 * 11889 * @see #setRotation(float) 11890 * @see #getPivotX() 11891 * @see #getPivotY() 11892 * 11893 * @return The degrees of rotation. 11894 */ 11895 @ViewDebug.ExportedProperty(category = "drawing") 11896 public float getRotation() { 11897 return mRenderNode.getRotation(); 11898 } 11899 11900 /** 11901 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11902 * result in clockwise rotation. 11903 * 11904 * @param rotation The degrees of rotation. 11905 * 11906 * @see #getRotation() 11907 * @see #getPivotX() 11908 * @see #getPivotY() 11909 * @see #setRotationX(float) 11910 * @see #setRotationY(float) 11911 * 11912 * @attr ref android.R.styleable#View_rotation 11913 */ 11914 public void setRotation(float rotation) { 11915 if (rotation != getRotation()) { 11916 // Double-invalidation is necessary to capture view's old and new areas 11917 invalidateViewProperty(true, false); 11918 mRenderNode.setRotation(rotation); 11919 invalidateViewProperty(false, true); 11920 11921 invalidateParentIfNeededAndWasQuickRejected(); 11922 notifySubtreeAccessibilityStateChangedIfNeeded(); 11923 } 11924 } 11925 11926 /** 11927 * The degrees that the view is rotated around the vertical axis through the pivot point. 11928 * 11929 * @see #getPivotX() 11930 * @see #getPivotY() 11931 * @see #setRotationY(float) 11932 * 11933 * @return The degrees of Y rotation. 11934 */ 11935 @ViewDebug.ExportedProperty(category = "drawing") 11936 public float getRotationY() { 11937 return mRenderNode.getRotationY(); 11938 } 11939 11940 /** 11941 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11942 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11943 * down the y axis. 11944 * 11945 * When rotating large views, it is recommended to adjust the camera distance 11946 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11947 * 11948 * @param rotationY The degrees of Y rotation. 11949 * 11950 * @see #getRotationY() 11951 * @see #getPivotX() 11952 * @see #getPivotY() 11953 * @see #setRotation(float) 11954 * @see #setRotationX(float) 11955 * @see #setCameraDistance(float) 11956 * 11957 * @attr ref android.R.styleable#View_rotationY 11958 */ 11959 public void setRotationY(float rotationY) { 11960 if (rotationY != getRotationY()) { 11961 invalidateViewProperty(true, false); 11962 mRenderNode.setRotationY(rotationY); 11963 invalidateViewProperty(false, true); 11964 11965 invalidateParentIfNeededAndWasQuickRejected(); 11966 notifySubtreeAccessibilityStateChangedIfNeeded(); 11967 } 11968 } 11969 11970 /** 11971 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11972 * 11973 * @see #getPivotX() 11974 * @see #getPivotY() 11975 * @see #setRotationX(float) 11976 * 11977 * @return The degrees of X rotation. 11978 */ 11979 @ViewDebug.ExportedProperty(category = "drawing") 11980 public float getRotationX() { 11981 return mRenderNode.getRotationX(); 11982 } 11983 11984 /** 11985 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11986 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11987 * x axis. 11988 * 11989 * When rotating large views, it is recommended to adjust the camera distance 11990 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11991 * 11992 * @param rotationX The degrees of X rotation. 11993 * 11994 * @see #getRotationX() 11995 * @see #getPivotX() 11996 * @see #getPivotY() 11997 * @see #setRotation(float) 11998 * @see #setRotationY(float) 11999 * @see #setCameraDistance(float) 12000 * 12001 * @attr ref android.R.styleable#View_rotationX 12002 */ 12003 public void setRotationX(float rotationX) { 12004 if (rotationX != getRotationX()) { 12005 invalidateViewProperty(true, false); 12006 mRenderNode.setRotationX(rotationX); 12007 invalidateViewProperty(false, true); 12008 12009 invalidateParentIfNeededAndWasQuickRejected(); 12010 notifySubtreeAccessibilityStateChangedIfNeeded(); 12011 } 12012 } 12013 12014 /** 12015 * The amount that the view is scaled in x around the pivot point, as a proportion of 12016 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 12017 * 12018 * <p>By default, this is 1.0f. 12019 * 12020 * @see #getPivotX() 12021 * @see #getPivotY() 12022 * @return The scaling factor. 12023 */ 12024 @ViewDebug.ExportedProperty(category = "drawing") 12025 public float getScaleX() { 12026 return mRenderNode.getScaleX(); 12027 } 12028 12029 /** 12030 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 12031 * the view's unscaled width. A value of 1 means that no scaling is applied. 12032 * 12033 * @param scaleX The scaling factor. 12034 * @see #getPivotX() 12035 * @see #getPivotY() 12036 * 12037 * @attr ref android.R.styleable#View_scaleX 12038 */ 12039 public void setScaleX(float scaleX) { 12040 if (scaleX != getScaleX()) { 12041 invalidateViewProperty(true, false); 12042 mRenderNode.setScaleX(scaleX); 12043 invalidateViewProperty(false, true); 12044 12045 invalidateParentIfNeededAndWasQuickRejected(); 12046 notifySubtreeAccessibilityStateChangedIfNeeded(); 12047 } 12048 } 12049 12050 /** 12051 * The amount that the view is scaled in y around the pivot point, as a proportion of 12052 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 12053 * 12054 * <p>By default, this is 1.0f. 12055 * 12056 * @see #getPivotX() 12057 * @see #getPivotY() 12058 * @return The scaling factor. 12059 */ 12060 @ViewDebug.ExportedProperty(category = "drawing") 12061 public float getScaleY() { 12062 return mRenderNode.getScaleY(); 12063 } 12064 12065 /** 12066 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 12067 * the view's unscaled width. A value of 1 means that no scaling is applied. 12068 * 12069 * @param scaleY The scaling factor. 12070 * @see #getPivotX() 12071 * @see #getPivotY() 12072 * 12073 * @attr ref android.R.styleable#View_scaleY 12074 */ 12075 public void setScaleY(float scaleY) { 12076 if (scaleY != getScaleY()) { 12077 invalidateViewProperty(true, false); 12078 mRenderNode.setScaleY(scaleY); 12079 invalidateViewProperty(false, true); 12080 12081 invalidateParentIfNeededAndWasQuickRejected(); 12082 notifySubtreeAccessibilityStateChangedIfNeeded(); 12083 } 12084 } 12085 12086 /** 12087 * The x location of the point around which the view is {@link #setRotation(float) rotated} 12088 * and {@link #setScaleX(float) scaled}. 12089 * 12090 * @see #getRotation() 12091 * @see #getScaleX() 12092 * @see #getScaleY() 12093 * @see #getPivotY() 12094 * @return The x location of the pivot point. 12095 * 12096 * @attr ref android.R.styleable#View_transformPivotX 12097 */ 12098 @ViewDebug.ExportedProperty(category = "drawing") 12099 public float getPivotX() { 12100 return mRenderNode.getPivotX(); 12101 } 12102 12103 /** 12104 * Sets the x location of the point around which the view is 12105 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 12106 * By default, the pivot point is centered on the object. 12107 * Setting this property disables this behavior and causes the view to use only the 12108 * explicitly set pivotX and pivotY values. 12109 * 12110 * @param pivotX The x location of the pivot point. 12111 * @see #getRotation() 12112 * @see #getScaleX() 12113 * @see #getScaleY() 12114 * @see #getPivotY() 12115 * 12116 * @attr ref android.R.styleable#View_transformPivotX 12117 */ 12118 public void setPivotX(float pivotX) { 12119 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12120 invalidateViewProperty(true, false); 12121 mRenderNode.setPivotX(pivotX); 12122 invalidateViewProperty(false, true); 12123 12124 invalidateParentIfNeededAndWasQuickRejected(); 12125 } 12126 } 12127 12128 /** 12129 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12130 * and {@link #setScaleY(float) scaled}. 12131 * 12132 * @see #getRotation() 12133 * @see #getScaleX() 12134 * @see #getScaleY() 12135 * @see #getPivotY() 12136 * @return The y location of the pivot point. 12137 * 12138 * @attr ref android.R.styleable#View_transformPivotY 12139 */ 12140 @ViewDebug.ExportedProperty(category = "drawing") 12141 public float getPivotY() { 12142 return mRenderNode.getPivotY(); 12143 } 12144 12145 /** 12146 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12147 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12148 * Setting this property disables this behavior and causes the view to use only the 12149 * explicitly set pivotX and pivotY values. 12150 * 12151 * @param pivotY The y location of the pivot point. 12152 * @see #getRotation() 12153 * @see #getScaleX() 12154 * @see #getScaleY() 12155 * @see #getPivotY() 12156 * 12157 * @attr ref android.R.styleable#View_transformPivotY 12158 */ 12159 public void setPivotY(float pivotY) { 12160 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12161 invalidateViewProperty(true, false); 12162 mRenderNode.setPivotY(pivotY); 12163 invalidateViewProperty(false, true); 12164 12165 invalidateParentIfNeededAndWasQuickRejected(); 12166 } 12167 } 12168 12169 /** 12170 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12171 * completely transparent and 1 means the view is completely opaque. 12172 * 12173 * <p>By default this is 1.0f. 12174 * @return The opacity of the view. 12175 */ 12176 @ViewDebug.ExportedProperty(category = "drawing") 12177 public float getAlpha() { 12178 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12179 } 12180 12181 /** 12182 * Sets the behavior for overlapping rendering for this view (see {@link 12183 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 12184 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 12185 * providing the value which is then used internally. That is, when {@link 12186 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 12187 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 12188 * instead. 12189 * 12190 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 12191 * instead of that returned by {@link #hasOverlappingRendering()}. 12192 * 12193 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 12194 */ 12195 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 12196 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 12197 if (hasOverlappingRendering) { 12198 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12199 } else { 12200 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 12201 } 12202 } 12203 12204 /** 12205 * Returns the value for overlapping rendering that is used internally. This is either 12206 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 12207 * the return value of {@link #hasOverlappingRendering()}, otherwise. 12208 * 12209 * @return The value for overlapping rendering being used internally. 12210 */ 12211 public final boolean getHasOverlappingRendering() { 12212 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 12213 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 12214 hasOverlappingRendering(); 12215 } 12216 12217 /** 12218 * Returns whether this View has content which overlaps. 12219 * 12220 * <p>This function, intended to be overridden by specific View types, is an optimization when 12221 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12222 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12223 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12224 * directly. An example of overlapping rendering is a TextView with a background image, such as 12225 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12226 * ImageView with only the foreground image. The default implementation returns true; subclasses 12227 * should override if they have cases which can be optimized.</p> 12228 * 12229 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12230 * necessitates that a View return true if it uses the methods internally without passing the 12231 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12232 * 12233 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 12234 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 12235 * 12236 * @return true if the content in this view might overlap, false otherwise. 12237 */ 12238 @ViewDebug.ExportedProperty(category = "drawing") 12239 public boolean hasOverlappingRendering() { 12240 return true; 12241 } 12242 12243 /** 12244 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12245 * completely transparent and 1 means the view is completely opaque. 12246 * 12247 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12248 * can have significant performance implications, especially for large views. It is best to use 12249 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12250 * 12251 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12252 * strongly recommended for performance reasons to either override 12253 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12254 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12255 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12256 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12257 * of rendering cost, even for simple or small views. Starting with 12258 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12259 * applied to the view at the rendering level.</p> 12260 * 12261 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12262 * responsible for applying the opacity itself.</p> 12263 * 12264 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12265 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12266 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12267 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12268 * 12269 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12270 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12271 * {@link #hasOverlappingRendering}.</p> 12272 * 12273 * @param alpha The opacity of the view. 12274 * 12275 * @see #hasOverlappingRendering() 12276 * @see #setLayerType(int, android.graphics.Paint) 12277 * 12278 * @attr ref android.R.styleable#View_alpha 12279 */ 12280 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12281 ensureTransformationInfo(); 12282 if (mTransformationInfo.mAlpha != alpha) { 12283 mTransformationInfo.mAlpha = alpha; 12284 if (onSetAlpha((int) (alpha * 255))) { 12285 mPrivateFlags |= PFLAG_ALPHA_SET; 12286 // subclass is handling alpha - don't optimize rendering cache invalidation 12287 invalidateParentCaches(); 12288 invalidate(true); 12289 } else { 12290 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12291 invalidateViewProperty(true, false); 12292 mRenderNode.setAlpha(getFinalAlpha()); 12293 notifyViewAccessibilityStateChangedIfNeeded( 12294 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12295 } 12296 } 12297 } 12298 12299 /** 12300 * Faster version of setAlpha() which performs the same steps except there are 12301 * no calls to invalidate(). The caller of this function should perform proper invalidation 12302 * on the parent and this object. The return value indicates whether the subclass handles 12303 * alpha (the return value for onSetAlpha()). 12304 * 12305 * @param alpha The new value for the alpha property 12306 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12307 * the new value for the alpha property is different from the old value 12308 */ 12309 boolean setAlphaNoInvalidation(float alpha) { 12310 ensureTransformationInfo(); 12311 if (mTransformationInfo.mAlpha != alpha) { 12312 mTransformationInfo.mAlpha = alpha; 12313 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12314 if (subclassHandlesAlpha) { 12315 mPrivateFlags |= PFLAG_ALPHA_SET; 12316 return true; 12317 } else { 12318 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12319 mRenderNode.setAlpha(getFinalAlpha()); 12320 } 12321 } 12322 return false; 12323 } 12324 12325 /** 12326 * This property is hidden and intended only for use by the Fade transition, which 12327 * animates it to produce a visual translucency that does not side-effect (or get 12328 * affected by) the real alpha property. This value is composited with the other 12329 * alpha value (and the AlphaAnimation value, when that is present) to produce 12330 * a final visual translucency result, which is what is passed into the DisplayList. 12331 * 12332 * @hide 12333 */ 12334 public void setTransitionAlpha(float alpha) { 12335 ensureTransformationInfo(); 12336 if (mTransformationInfo.mTransitionAlpha != alpha) { 12337 mTransformationInfo.mTransitionAlpha = alpha; 12338 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12339 invalidateViewProperty(true, false); 12340 mRenderNode.setAlpha(getFinalAlpha()); 12341 } 12342 } 12343 12344 /** 12345 * Calculates the visual alpha of this view, which is a combination of the actual 12346 * alpha value and the transitionAlpha value (if set). 12347 */ 12348 private float getFinalAlpha() { 12349 if (mTransformationInfo != null) { 12350 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12351 } 12352 return 1; 12353 } 12354 12355 /** 12356 * This property is hidden and intended only for use by the Fade transition, which 12357 * animates it to produce a visual translucency that does not side-effect (or get 12358 * affected by) the real alpha property. This value is composited with the other 12359 * alpha value (and the AlphaAnimation value, when that is present) to produce 12360 * a final visual translucency result, which is what is passed into the DisplayList. 12361 * 12362 * @hide 12363 */ 12364 @ViewDebug.ExportedProperty(category = "drawing") 12365 public float getTransitionAlpha() { 12366 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12367 } 12368 12369 /** 12370 * Top position of this view relative to its parent. 12371 * 12372 * @return The top of this view, in pixels. 12373 */ 12374 @ViewDebug.CapturedViewProperty 12375 public final int getTop() { 12376 return mTop; 12377 } 12378 12379 /** 12380 * Sets the top position of this view relative to its parent. This method is meant to be called 12381 * by the layout system and should not generally be called otherwise, because the property 12382 * may be changed at any time by the layout. 12383 * 12384 * @param top The top of this view, in pixels. 12385 */ 12386 public final void setTop(int top) { 12387 if (top != mTop) { 12388 final boolean matrixIsIdentity = hasIdentityMatrix(); 12389 if (matrixIsIdentity) { 12390 if (mAttachInfo != null) { 12391 int minTop; 12392 int yLoc; 12393 if (top < mTop) { 12394 minTop = top; 12395 yLoc = top - mTop; 12396 } else { 12397 minTop = mTop; 12398 yLoc = 0; 12399 } 12400 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12401 } 12402 } else { 12403 // Double-invalidation is necessary to capture view's old and new areas 12404 invalidate(true); 12405 } 12406 12407 int width = mRight - mLeft; 12408 int oldHeight = mBottom - mTop; 12409 12410 mTop = top; 12411 mRenderNode.setTop(mTop); 12412 12413 sizeChange(width, mBottom - mTop, width, oldHeight); 12414 12415 if (!matrixIsIdentity) { 12416 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12417 invalidate(true); 12418 } 12419 mBackgroundSizeChanged = true; 12420 if (mForegroundInfo != null) { 12421 mForegroundInfo.mBoundsChanged = true; 12422 } 12423 invalidateParentIfNeeded(); 12424 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12425 // View was rejected last time it was drawn by its parent; this may have changed 12426 invalidateParentIfNeeded(); 12427 } 12428 } 12429 } 12430 12431 /** 12432 * Bottom position of this view relative to its parent. 12433 * 12434 * @return The bottom of this view, in pixels. 12435 */ 12436 @ViewDebug.CapturedViewProperty 12437 public final int getBottom() { 12438 return mBottom; 12439 } 12440 12441 /** 12442 * True if this view has changed since the last time being drawn. 12443 * 12444 * @return The dirty state of this view. 12445 */ 12446 public boolean isDirty() { 12447 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12448 } 12449 12450 /** 12451 * Sets the bottom position of this view relative to its parent. This method is meant to be 12452 * called by the layout system and should not generally be called otherwise, because the 12453 * property may be changed at any time by the layout. 12454 * 12455 * @param bottom The bottom of this view, in pixels. 12456 */ 12457 public final void setBottom(int bottom) { 12458 if (bottom != mBottom) { 12459 final boolean matrixIsIdentity = hasIdentityMatrix(); 12460 if (matrixIsIdentity) { 12461 if (mAttachInfo != null) { 12462 int maxBottom; 12463 if (bottom < mBottom) { 12464 maxBottom = mBottom; 12465 } else { 12466 maxBottom = bottom; 12467 } 12468 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12469 } 12470 } else { 12471 // Double-invalidation is necessary to capture view's old and new areas 12472 invalidate(true); 12473 } 12474 12475 int width = mRight - mLeft; 12476 int oldHeight = mBottom - mTop; 12477 12478 mBottom = bottom; 12479 mRenderNode.setBottom(mBottom); 12480 12481 sizeChange(width, mBottom - mTop, width, oldHeight); 12482 12483 if (!matrixIsIdentity) { 12484 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12485 invalidate(true); 12486 } 12487 mBackgroundSizeChanged = true; 12488 if (mForegroundInfo != null) { 12489 mForegroundInfo.mBoundsChanged = true; 12490 } 12491 invalidateParentIfNeeded(); 12492 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12493 // View was rejected last time it was drawn by its parent; this may have changed 12494 invalidateParentIfNeeded(); 12495 } 12496 } 12497 } 12498 12499 /** 12500 * Left position of this view relative to its parent. 12501 * 12502 * @return The left edge of this view, in pixels. 12503 */ 12504 @ViewDebug.CapturedViewProperty 12505 public final int getLeft() { 12506 return mLeft; 12507 } 12508 12509 /** 12510 * Sets the left position of this view relative to its parent. This method is meant to be called 12511 * by the layout system and should not generally be called otherwise, because the property 12512 * may be changed at any time by the layout. 12513 * 12514 * @param left The left of this view, in pixels. 12515 */ 12516 public final void setLeft(int left) { 12517 if (left != mLeft) { 12518 final boolean matrixIsIdentity = hasIdentityMatrix(); 12519 if (matrixIsIdentity) { 12520 if (mAttachInfo != null) { 12521 int minLeft; 12522 int xLoc; 12523 if (left < mLeft) { 12524 minLeft = left; 12525 xLoc = left - mLeft; 12526 } else { 12527 minLeft = mLeft; 12528 xLoc = 0; 12529 } 12530 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12531 } 12532 } else { 12533 // Double-invalidation is necessary to capture view's old and new areas 12534 invalidate(true); 12535 } 12536 12537 int oldWidth = mRight - mLeft; 12538 int height = mBottom - mTop; 12539 12540 mLeft = left; 12541 mRenderNode.setLeft(left); 12542 12543 sizeChange(mRight - mLeft, height, oldWidth, height); 12544 12545 if (!matrixIsIdentity) { 12546 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12547 invalidate(true); 12548 } 12549 mBackgroundSizeChanged = true; 12550 if (mForegroundInfo != null) { 12551 mForegroundInfo.mBoundsChanged = true; 12552 } 12553 invalidateParentIfNeeded(); 12554 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12555 // View was rejected last time it was drawn by its parent; this may have changed 12556 invalidateParentIfNeeded(); 12557 } 12558 } 12559 } 12560 12561 /** 12562 * Right position of this view relative to its parent. 12563 * 12564 * @return The right edge of this view, in pixels. 12565 */ 12566 @ViewDebug.CapturedViewProperty 12567 public final int getRight() { 12568 return mRight; 12569 } 12570 12571 /** 12572 * Sets the right position of this view relative to its parent. This method is meant to be called 12573 * by the layout system and should not generally be called otherwise, because the property 12574 * may be changed at any time by the layout. 12575 * 12576 * @param right The right of this view, in pixels. 12577 */ 12578 public final void setRight(int right) { 12579 if (right != mRight) { 12580 final boolean matrixIsIdentity = hasIdentityMatrix(); 12581 if (matrixIsIdentity) { 12582 if (mAttachInfo != null) { 12583 int maxRight; 12584 if (right < mRight) { 12585 maxRight = mRight; 12586 } else { 12587 maxRight = right; 12588 } 12589 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12590 } 12591 } else { 12592 // Double-invalidation is necessary to capture view's old and new areas 12593 invalidate(true); 12594 } 12595 12596 int oldWidth = mRight - mLeft; 12597 int height = mBottom - mTop; 12598 12599 mRight = right; 12600 mRenderNode.setRight(mRight); 12601 12602 sizeChange(mRight - mLeft, height, oldWidth, height); 12603 12604 if (!matrixIsIdentity) { 12605 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12606 invalidate(true); 12607 } 12608 mBackgroundSizeChanged = true; 12609 if (mForegroundInfo != null) { 12610 mForegroundInfo.mBoundsChanged = true; 12611 } 12612 invalidateParentIfNeeded(); 12613 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12614 // View was rejected last time it was drawn by its parent; this may have changed 12615 invalidateParentIfNeeded(); 12616 } 12617 } 12618 } 12619 12620 /** 12621 * The visual x position of this view, in pixels. This is equivalent to the 12622 * {@link #setTranslationX(float) translationX} property plus the current 12623 * {@link #getLeft() left} property. 12624 * 12625 * @return The visual x position of this view, in pixels. 12626 */ 12627 @ViewDebug.ExportedProperty(category = "drawing") 12628 public float getX() { 12629 return mLeft + getTranslationX(); 12630 } 12631 12632 /** 12633 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12634 * {@link #setTranslationX(float) translationX} property to be the difference between 12635 * the x value passed in and the current {@link #getLeft() left} property. 12636 * 12637 * @param x The visual x position of this view, in pixels. 12638 */ 12639 public void setX(float x) { 12640 setTranslationX(x - mLeft); 12641 } 12642 12643 /** 12644 * The visual y position of this view, in pixels. This is equivalent to the 12645 * {@link #setTranslationY(float) translationY} property plus the current 12646 * {@link #getTop() top} property. 12647 * 12648 * @return The visual y position of this view, in pixels. 12649 */ 12650 @ViewDebug.ExportedProperty(category = "drawing") 12651 public float getY() { 12652 return mTop + getTranslationY(); 12653 } 12654 12655 /** 12656 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12657 * {@link #setTranslationY(float) translationY} property to be the difference between 12658 * the y value passed in and the current {@link #getTop() top} property. 12659 * 12660 * @param y The visual y position of this view, in pixels. 12661 */ 12662 public void setY(float y) { 12663 setTranslationY(y - mTop); 12664 } 12665 12666 /** 12667 * The visual z position of this view, in pixels. This is equivalent to the 12668 * {@link #setTranslationZ(float) translationZ} property plus the current 12669 * {@link #getElevation() elevation} property. 12670 * 12671 * @return The visual z position of this view, in pixels. 12672 */ 12673 @ViewDebug.ExportedProperty(category = "drawing") 12674 public float getZ() { 12675 return getElevation() + getTranslationZ(); 12676 } 12677 12678 /** 12679 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12680 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12681 * the x value passed in and the current {@link #getElevation() elevation} property. 12682 * 12683 * @param z The visual z position of this view, in pixels. 12684 */ 12685 public void setZ(float z) { 12686 setTranslationZ(z - getElevation()); 12687 } 12688 12689 /** 12690 * The base elevation of this view relative to its parent, in pixels. 12691 * 12692 * @return The base depth position of the view, in pixels. 12693 */ 12694 @ViewDebug.ExportedProperty(category = "drawing") 12695 public float getElevation() { 12696 return mRenderNode.getElevation(); 12697 } 12698 12699 /** 12700 * Sets the base elevation of this view, in pixels. 12701 * 12702 * @attr ref android.R.styleable#View_elevation 12703 */ 12704 public void setElevation(float elevation) { 12705 if (elevation != getElevation()) { 12706 invalidateViewProperty(true, false); 12707 mRenderNode.setElevation(elevation); 12708 invalidateViewProperty(false, true); 12709 12710 invalidateParentIfNeededAndWasQuickRejected(); 12711 } 12712 } 12713 12714 /** 12715 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12716 * This position is post-layout, in addition to wherever the object's 12717 * layout placed it. 12718 * 12719 * @return The horizontal position of this view relative to its left position, in pixels. 12720 */ 12721 @ViewDebug.ExportedProperty(category = "drawing") 12722 public float getTranslationX() { 12723 return mRenderNode.getTranslationX(); 12724 } 12725 12726 /** 12727 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12728 * This effectively positions the object post-layout, in addition to wherever the object's 12729 * layout placed it. 12730 * 12731 * @param translationX The horizontal position of this view relative to its left position, 12732 * in pixels. 12733 * 12734 * @attr ref android.R.styleable#View_translationX 12735 */ 12736 public void setTranslationX(float translationX) { 12737 if (translationX != getTranslationX()) { 12738 invalidateViewProperty(true, false); 12739 mRenderNode.setTranslationX(translationX); 12740 invalidateViewProperty(false, true); 12741 12742 invalidateParentIfNeededAndWasQuickRejected(); 12743 notifySubtreeAccessibilityStateChangedIfNeeded(); 12744 } 12745 } 12746 12747 /** 12748 * The vertical location of this view relative to its {@link #getTop() top} position. 12749 * This position is post-layout, in addition to wherever the object's 12750 * layout placed it. 12751 * 12752 * @return The vertical position of this view relative to its top position, 12753 * in pixels. 12754 */ 12755 @ViewDebug.ExportedProperty(category = "drawing") 12756 public float getTranslationY() { 12757 return mRenderNode.getTranslationY(); 12758 } 12759 12760 /** 12761 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12762 * This effectively positions the object post-layout, in addition to wherever the object's 12763 * layout placed it. 12764 * 12765 * @param translationY The vertical position of this view relative to its top position, 12766 * in pixels. 12767 * 12768 * @attr ref android.R.styleable#View_translationY 12769 */ 12770 public void setTranslationY(float translationY) { 12771 if (translationY != getTranslationY()) { 12772 invalidateViewProperty(true, false); 12773 mRenderNode.setTranslationY(translationY); 12774 invalidateViewProperty(false, true); 12775 12776 invalidateParentIfNeededAndWasQuickRejected(); 12777 notifySubtreeAccessibilityStateChangedIfNeeded(); 12778 } 12779 } 12780 12781 /** 12782 * The depth location of this view relative to its {@link #getElevation() elevation}. 12783 * 12784 * @return The depth of this view relative to its elevation. 12785 */ 12786 @ViewDebug.ExportedProperty(category = "drawing") 12787 public float getTranslationZ() { 12788 return mRenderNode.getTranslationZ(); 12789 } 12790 12791 /** 12792 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12793 * 12794 * @attr ref android.R.styleable#View_translationZ 12795 */ 12796 public void setTranslationZ(float translationZ) { 12797 if (translationZ != getTranslationZ()) { 12798 invalidateViewProperty(true, false); 12799 mRenderNode.setTranslationZ(translationZ); 12800 invalidateViewProperty(false, true); 12801 12802 invalidateParentIfNeededAndWasQuickRejected(); 12803 } 12804 } 12805 12806 /** @hide */ 12807 public void setAnimationMatrix(Matrix matrix) { 12808 invalidateViewProperty(true, false); 12809 mRenderNode.setAnimationMatrix(matrix); 12810 invalidateViewProperty(false, true); 12811 12812 invalidateParentIfNeededAndWasQuickRejected(); 12813 } 12814 12815 /** 12816 * Returns the current StateListAnimator if exists. 12817 * 12818 * @return StateListAnimator or null if it does not exists 12819 * @see #setStateListAnimator(android.animation.StateListAnimator) 12820 */ 12821 public StateListAnimator getStateListAnimator() { 12822 return mStateListAnimator; 12823 } 12824 12825 /** 12826 * Attaches the provided StateListAnimator to this View. 12827 * <p> 12828 * Any previously attached StateListAnimator will be detached. 12829 * 12830 * @param stateListAnimator The StateListAnimator to update the view 12831 * @see {@link android.animation.StateListAnimator} 12832 */ 12833 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12834 if (mStateListAnimator == stateListAnimator) { 12835 return; 12836 } 12837 if (mStateListAnimator != null) { 12838 mStateListAnimator.setTarget(null); 12839 } 12840 mStateListAnimator = stateListAnimator; 12841 if (stateListAnimator != null) { 12842 stateListAnimator.setTarget(this); 12843 if (isAttachedToWindow()) { 12844 stateListAnimator.setState(getDrawableState()); 12845 } 12846 } 12847 } 12848 12849 /** 12850 * Returns whether the Outline should be used to clip the contents of the View. 12851 * <p> 12852 * Note that this flag will only be respected if the View's Outline returns true from 12853 * {@link Outline#canClip()}. 12854 * 12855 * @see #setOutlineProvider(ViewOutlineProvider) 12856 * @see #setClipToOutline(boolean) 12857 */ 12858 public final boolean getClipToOutline() { 12859 return mRenderNode.getClipToOutline(); 12860 } 12861 12862 /** 12863 * Sets whether the View's Outline should be used to clip the contents of the View. 12864 * <p> 12865 * Only a single non-rectangular clip can be applied on a View at any time. 12866 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12867 * circular reveal} animation take priority over Outline clipping, and 12868 * child Outline clipping takes priority over Outline clipping done by a 12869 * parent. 12870 * <p> 12871 * Note that this flag will only be respected if the View's Outline returns true from 12872 * {@link Outline#canClip()}. 12873 * 12874 * @see #setOutlineProvider(ViewOutlineProvider) 12875 * @see #getClipToOutline() 12876 */ 12877 public void setClipToOutline(boolean clipToOutline) { 12878 damageInParent(); 12879 if (getClipToOutline() != clipToOutline) { 12880 mRenderNode.setClipToOutline(clipToOutline); 12881 } 12882 } 12883 12884 // correspond to the enum values of View_outlineProvider 12885 private static final int PROVIDER_BACKGROUND = 0; 12886 private static final int PROVIDER_NONE = 1; 12887 private static final int PROVIDER_BOUNDS = 2; 12888 private static final int PROVIDER_PADDED_BOUNDS = 3; 12889 private void setOutlineProviderFromAttribute(int providerInt) { 12890 switch (providerInt) { 12891 case PROVIDER_BACKGROUND: 12892 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12893 break; 12894 case PROVIDER_NONE: 12895 setOutlineProvider(null); 12896 break; 12897 case PROVIDER_BOUNDS: 12898 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12899 break; 12900 case PROVIDER_PADDED_BOUNDS: 12901 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12902 break; 12903 } 12904 } 12905 12906 /** 12907 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12908 * the shape of the shadow it casts, and enables outline clipping. 12909 * <p> 12910 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12911 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12912 * outline provider with this method allows this behavior to be overridden. 12913 * <p> 12914 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12915 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12916 * <p> 12917 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12918 * 12919 * @see #setClipToOutline(boolean) 12920 * @see #getClipToOutline() 12921 * @see #getOutlineProvider() 12922 */ 12923 public void setOutlineProvider(ViewOutlineProvider provider) { 12924 mOutlineProvider = provider; 12925 invalidateOutline(); 12926 } 12927 12928 /** 12929 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12930 * that defines the shape of the shadow it casts, and enables outline clipping. 12931 * 12932 * @see #setOutlineProvider(ViewOutlineProvider) 12933 */ 12934 public ViewOutlineProvider getOutlineProvider() { 12935 return mOutlineProvider; 12936 } 12937 12938 /** 12939 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12940 * 12941 * @see #setOutlineProvider(ViewOutlineProvider) 12942 */ 12943 public void invalidateOutline() { 12944 rebuildOutline(); 12945 12946 notifySubtreeAccessibilityStateChangedIfNeeded(); 12947 invalidateViewProperty(false, false); 12948 } 12949 12950 /** 12951 * Internal version of {@link #invalidateOutline()} which invalidates the 12952 * outline without invalidating the view itself. This is intended to be called from 12953 * within methods in the View class itself which are the result of the view being 12954 * invalidated already. For example, when we are drawing the background of a View, 12955 * we invalidate the outline in case it changed in the meantime, but we do not 12956 * need to invalidate the view because we're already drawing the background as part 12957 * of drawing the view in response to an earlier invalidation of the view. 12958 */ 12959 private void rebuildOutline() { 12960 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12961 if (mAttachInfo == null) return; 12962 12963 if (mOutlineProvider == null) { 12964 // no provider, remove outline 12965 mRenderNode.setOutline(null); 12966 } else { 12967 final Outline outline = mAttachInfo.mTmpOutline; 12968 outline.setEmpty(); 12969 outline.setAlpha(1.0f); 12970 12971 mOutlineProvider.getOutline(this, outline); 12972 mRenderNode.setOutline(outline); 12973 } 12974 } 12975 12976 /** 12977 * HierarchyViewer only 12978 * 12979 * @hide 12980 */ 12981 @ViewDebug.ExportedProperty(category = "drawing") 12982 public boolean hasShadow() { 12983 return mRenderNode.hasShadow(); 12984 } 12985 12986 12987 /** @hide */ 12988 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 12989 mRenderNode.setRevealClip(shouldClip, x, y, radius); 12990 invalidateViewProperty(false, false); 12991 } 12992 12993 /** 12994 * Hit rectangle in parent's coordinates 12995 * 12996 * @param outRect The hit rectangle of the view. 12997 */ 12998 public void getHitRect(Rect outRect) { 12999 if (hasIdentityMatrix() || mAttachInfo == null) { 13000 outRect.set(mLeft, mTop, mRight, mBottom); 13001 } else { 13002 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 13003 tmpRect.set(0, 0, getWidth(), getHeight()); 13004 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 13005 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 13006 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 13007 } 13008 } 13009 13010 /** 13011 * Determines whether the given point, in local coordinates is inside the view. 13012 */ 13013 /*package*/ final boolean pointInView(float localX, float localY) { 13014 return pointInView(localX, localY, 0); 13015 } 13016 13017 /** 13018 * Utility method to determine whether the given point, in local coordinates, 13019 * is inside the view, where the area of the view is expanded by the slop factor. 13020 * This method is called while processing touch-move events to determine if the event 13021 * is still within the view. 13022 * 13023 * @hide 13024 */ 13025 public boolean pointInView(float localX, float localY, float slop) { 13026 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 13027 localY < ((mBottom - mTop) + slop); 13028 } 13029 13030 /** 13031 * When a view has focus and the user navigates away from it, the next view is searched for 13032 * starting from the rectangle filled in by this method. 13033 * 13034 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 13035 * of the view. However, if your view maintains some idea of internal selection, 13036 * such as a cursor, or a selected row or column, you should override this method and 13037 * fill in a more specific rectangle. 13038 * 13039 * @param r The rectangle to fill in, in this view's coordinates. 13040 */ 13041 public void getFocusedRect(Rect r) { 13042 getDrawingRect(r); 13043 } 13044 13045 /** 13046 * If some part of this view is not clipped by any of its parents, then 13047 * return that area in r in global (root) coordinates. To convert r to local 13048 * coordinates (without taking possible View rotations into account), offset 13049 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 13050 * If the view is completely clipped or translated out, return false. 13051 * 13052 * @param r If true is returned, r holds the global coordinates of the 13053 * visible portion of this view. 13054 * @param globalOffset If true is returned, globalOffset holds the dx,dy 13055 * between this view and its root. globalOffet may be null. 13056 * @return true if r is non-empty (i.e. part of the view is visible at the 13057 * root level. 13058 */ 13059 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 13060 int width = mRight - mLeft; 13061 int height = mBottom - mTop; 13062 if (width > 0 && height > 0) { 13063 r.set(0, 0, width, height); 13064 if (globalOffset != null) { 13065 globalOffset.set(-mScrollX, -mScrollY); 13066 } 13067 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 13068 } 13069 return false; 13070 } 13071 13072 public final boolean getGlobalVisibleRect(Rect r) { 13073 return getGlobalVisibleRect(r, null); 13074 } 13075 13076 public final boolean getLocalVisibleRect(Rect r) { 13077 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 13078 if (getGlobalVisibleRect(r, offset)) { 13079 r.offset(-offset.x, -offset.y); // make r local 13080 return true; 13081 } 13082 return false; 13083 } 13084 13085 /** 13086 * Offset this view's vertical location by the specified number of pixels. 13087 * 13088 * @param offset the number of pixels to offset the view by 13089 */ 13090 public void offsetTopAndBottom(int offset) { 13091 if (offset != 0) { 13092 final boolean matrixIsIdentity = hasIdentityMatrix(); 13093 if (matrixIsIdentity) { 13094 if (isHardwareAccelerated()) { 13095 invalidateViewProperty(false, false); 13096 } else { 13097 final ViewParent p = mParent; 13098 if (p != null && mAttachInfo != null) { 13099 final Rect r = mAttachInfo.mTmpInvalRect; 13100 int minTop; 13101 int maxBottom; 13102 int yLoc; 13103 if (offset < 0) { 13104 minTop = mTop + offset; 13105 maxBottom = mBottom; 13106 yLoc = offset; 13107 } else { 13108 minTop = mTop; 13109 maxBottom = mBottom + offset; 13110 yLoc = 0; 13111 } 13112 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 13113 p.invalidateChild(this, r); 13114 } 13115 } 13116 } else { 13117 invalidateViewProperty(false, false); 13118 } 13119 13120 mTop += offset; 13121 mBottom += offset; 13122 mRenderNode.offsetTopAndBottom(offset); 13123 if (isHardwareAccelerated()) { 13124 invalidateViewProperty(false, false); 13125 invalidateParentIfNeededAndWasQuickRejected(); 13126 } else { 13127 if (!matrixIsIdentity) { 13128 invalidateViewProperty(false, true); 13129 } 13130 invalidateParentIfNeeded(); 13131 } 13132 notifySubtreeAccessibilityStateChangedIfNeeded(); 13133 } 13134 } 13135 13136 /** 13137 * Offset this view's horizontal location by the specified amount of pixels. 13138 * 13139 * @param offset the number of pixels to offset the view by 13140 */ 13141 public void offsetLeftAndRight(int offset) { 13142 if (offset != 0) { 13143 final boolean matrixIsIdentity = hasIdentityMatrix(); 13144 if (matrixIsIdentity) { 13145 if (isHardwareAccelerated()) { 13146 invalidateViewProperty(false, false); 13147 } else { 13148 final ViewParent p = mParent; 13149 if (p != null && mAttachInfo != null) { 13150 final Rect r = mAttachInfo.mTmpInvalRect; 13151 int minLeft; 13152 int maxRight; 13153 if (offset < 0) { 13154 minLeft = mLeft + offset; 13155 maxRight = mRight; 13156 } else { 13157 minLeft = mLeft; 13158 maxRight = mRight + offset; 13159 } 13160 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13161 p.invalidateChild(this, r); 13162 } 13163 } 13164 } else { 13165 invalidateViewProperty(false, false); 13166 } 13167 13168 mLeft += offset; 13169 mRight += offset; 13170 mRenderNode.offsetLeftAndRight(offset); 13171 if (isHardwareAccelerated()) { 13172 invalidateViewProperty(false, false); 13173 invalidateParentIfNeededAndWasQuickRejected(); 13174 } else { 13175 if (!matrixIsIdentity) { 13176 invalidateViewProperty(false, true); 13177 } 13178 invalidateParentIfNeeded(); 13179 } 13180 notifySubtreeAccessibilityStateChangedIfNeeded(); 13181 } 13182 } 13183 13184 /** 13185 * Get the LayoutParams associated with this view. All views should have 13186 * layout parameters. These supply parameters to the <i>parent</i> of this 13187 * view specifying how it should be arranged. There are many subclasses of 13188 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13189 * of ViewGroup that are responsible for arranging their children. 13190 * 13191 * This method may return null if this View is not attached to a parent 13192 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13193 * was not invoked successfully. When a View is attached to a parent 13194 * ViewGroup, this method must not return null. 13195 * 13196 * @return The LayoutParams associated with this view, or null if no 13197 * parameters have been set yet 13198 */ 13199 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13200 public ViewGroup.LayoutParams getLayoutParams() { 13201 return mLayoutParams; 13202 } 13203 13204 /** 13205 * Set the layout parameters associated with this view. These supply 13206 * parameters to the <i>parent</i> of this view specifying how it should be 13207 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13208 * correspond to the different subclasses of ViewGroup that are responsible 13209 * for arranging their children. 13210 * 13211 * @param params The layout parameters for this view, cannot be null 13212 */ 13213 public void setLayoutParams(ViewGroup.LayoutParams params) { 13214 if (params == null) { 13215 throw new NullPointerException("Layout parameters cannot be null"); 13216 } 13217 mLayoutParams = params; 13218 resolveLayoutParams(); 13219 if (mParent instanceof ViewGroup) { 13220 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13221 } 13222 requestLayout(); 13223 } 13224 13225 /** 13226 * Resolve the layout parameters depending on the resolved layout direction 13227 * 13228 * @hide 13229 */ 13230 public void resolveLayoutParams() { 13231 if (mLayoutParams != null) { 13232 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13233 } 13234 } 13235 13236 /** 13237 * Set the scrolled position of your view. This will cause a call to 13238 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13239 * invalidated. 13240 * @param x the x position to scroll to 13241 * @param y the y position to scroll to 13242 */ 13243 public void scrollTo(int x, int y) { 13244 if (mScrollX != x || mScrollY != y) { 13245 int oldX = mScrollX; 13246 int oldY = mScrollY; 13247 mScrollX = x; 13248 mScrollY = y; 13249 invalidateParentCaches(); 13250 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13251 if (!awakenScrollBars()) { 13252 postInvalidateOnAnimation(); 13253 } 13254 } 13255 } 13256 13257 /** 13258 * Move the scrolled position of your view. This will cause a call to 13259 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13260 * invalidated. 13261 * @param x the amount of pixels to scroll by horizontally 13262 * @param y the amount of pixels to scroll by vertically 13263 */ 13264 public void scrollBy(int x, int y) { 13265 scrollTo(mScrollX + x, mScrollY + y); 13266 } 13267 13268 /** 13269 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13270 * animation to fade the scrollbars out after a default delay. If a subclass 13271 * provides animated scrolling, the start delay should equal the duration 13272 * of the scrolling animation.</p> 13273 * 13274 * <p>The animation starts only if at least one of the scrollbars is 13275 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13276 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13277 * this method returns true, and false otherwise. If the animation is 13278 * started, this method calls {@link #invalidate()}; in that case the 13279 * caller should not call {@link #invalidate()}.</p> 13280 * 13281 * <p>This method should be invoked every time a subclass directly updates 13282 * the scroll parameters.</p> 13283 * 13284 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13285 * and {@link #scrollTo(int, int)}.</p> 13286 * 13287 * @return true if the animation is played, false otherwise 13288 * 13289 * @see #awakenScrollBars(int) 13290 * @see #scrollBy(int, int) 13291 * @see #scrollTo(int, int) 13292 * @see #isHorizontalScrollBarEnabled() 13293 * @see #isVerticalScrollBarEnabled() 13294 * @see #setHorizontalScrollBarEnabled(boolean) 13295 * @see #setVerticalScrollBarEnabled(boolean) 13296 */ 13297 protected boolean awakenScrollBars() { 13298 return mScrollCache != null && 13299 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13300 } 13301 13302 /** 13303 * Trigger the scrollbars to draw. 13304 * This method differs from awakenScrollBars() only in its default duration. 13305 * initialAwakenScrollBars() will show the scroll bars for longer than 13306 * usual to give the user more of a chance to notice them. 13307 * 13308 * @return true if the animation is played, false otherwise. 13309 */ 13310 private boolean initialAwakenScrollBars() { 13311 return mScrollCache != null && 13312 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13313 } 13314 13315 /** 13316 * <p> 13317 * Trigger the scrollbars to draw. When invoked this method starts an 13318 * animation to fade the scrollbars out after a fixed delay. If a subclass 13319 * provides animated scrolling, the start delay should equal the duration of 13320 * the scrolling animation. 13321 * </p> 13322 * 13323 * <p> 13324 * The animation starts only if at least one of the scrollbars is enabled, 13325 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13326 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13327 * this method returns true, and false otherwise. If the animation is 13328 * started, this method calls {@link #invalidate()}; in that case the caller 13329 * should not call {@link #invalidate()}. 13330 * </p> 13331 * 13332 * <p> 13333 * This method should be invoked every time a subclass directly updates the 13334 * scroll parameters. 13335 * </p> 13336 * 13337 * @param startDelay the delay, in milliseconds, after which the animation 13338 * should start; when the delay is 0, the animation starts 13339 * immediately 13340 * @return true if the animation is played, false otherwise 13341 * 13342 * @see #scrollBy(int, int) 13343 * @see #scrollTo(int, int) 13344 * @see #isHorizontalScrollBarEnabled() 13345 * @see #isVerticalScrollBarEnabled() 13346 * @see #setHorizontalScrollBarEnabled(boolean) 13347 * @see #setVerticalScrollBarEnabled(boolean) 13348 */ 13349 protected boolean awakenScrollBars(int startDelay) { 13350 return awakenScrollBars(startDelay, true); 13351 } 13352 13353 /** 13354 * <p> 13355 * Trigger the scrollbars to draw. When invoked this method starts an 13356 * animation to fade the scrollbars out after a fixed delay. If a subclass 13357 * provides animated scrolling, the start delay should equal the duration of 13358 * the scrolling animation. 13359 * </p> 13360 * 13361 * <p> 13362 * The animation starts only if at least one of the scrollbars is enabled, 13363 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13364 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13365 * this method returns true, and false otherwise. If the animation is 13366 * started, this method calls {@link #invalidate()} if the invalidate parameter 13367 * is set to true; in that case the caller 13368 * should not call {@link #invalidate()}. 13369 * </p> 13370 * 13371 * <p> 13372 * This method should be invoked every time a subclass directly updates the 13373 * scroll parameters. 13374 * </p> 13375 * 13376 * @param startDelay the delay, in milliseconds, after which the animation 13377 * should start; when the delay is 0, the animation starts 13378 * immediately 13379 * 13380 * @param invalidate Whether this method should call invalidate 13381 * 13382 * @return true if the animation is played, false otherwise 13383 * 13384 * @see #scrollBy(int, int) 13385 * @see #scrollTo(int, int) 13386 * @see #isHorizontalScrollBarEnabled() 13387 * @see #isVerticalScrollBarEnabled() 13388 * @see #setHorizontalScrollBarEnabled(boolean) 13389 * @see #setVerticalScrollBarEnabled(boolean) 13390 */ 13391 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13392 final ScrollabilityCache scrollCache = mScrollCache; 13393 13394 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13395 return false; 13396 } 13397 13398 if (scrollCache.scrollBar == null) { 13399 scrollCache.scrollBar = new ScrollBarDrawable(); 13400 scrollCache.scrollBar.setState(getDrawableState()); 13401 scrollCache.scrollBar.setCallback(this); 13402 } 13403 13404 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13405 13406 if (invalidate) { 13407 // Invalidate to show the scrollbars 13408 postInvalidateOnAnimation(); 13409 } 13410 13411 if (scrollCache.state == ScrollabilityCache.OFF) { 13412 // FIXME: this is copied from WindowManagerService. 13413 // We should get this value from the system when it 13414 // is possible to do so. 13415 final int KEY_REPEAT_FIRST_DELAY = 750; 13416 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13417 } 13418 13419 // Tell mScrollCache when we should start fading. This may 13420 // extend the fade start time if one was already scheduled 13421 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13422 scrollCache.fadeStartTime = fadeStartTime; 13423 scrollCache.state = ScrollabilityCache.ON; 13424 13425 // Schedule our fader to run, unscheduling any old ones first 13426 if (mAttachInfo != null) { 13427 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13428 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13429 } 13430 13431 return true; 13432 } 13433 13434 return false; 13435 } 13436 13437 /** 13438 * Do not invalidate views which are not visible and which are not running an animation. They 13439 * will not get drawn and they should not set dirty flags as if they will be drawn 13440 */ 13441 private boolean skipInvalidate() { 13442 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13443 (!(mParent instanceof ViewGroup) || 13444 !((ViewGroup) mParent).isViewTransitioning(this)); 13445 } 13446 13447 /** 13448 * Mark the area defined by dirty as needing to be drawn. If the view is 13449 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13450 * point in the future. 13451 * <p> 13452 * This must be called from a UI thread. To call from a non-UI thread, call 13453 * {@link #postInvalidate()}. 13454 * <p> 13455 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13456 * {@code dirty}. 13457 * 13458 * @param dirty the rectangle representing the bounds of the dirty region 13459 */ 13460 public void invalidate(Rect dirty) { 13461 final int scrollX = mScrollX; 13462 final int scrollY = mScrollY; 13463 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13464 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13465 } 13466 13467 /** 13468 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13469 * coordinates of the dirty rect are relative to the view. If the view is 13470 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13471 * point in the future. 13472 * <p> 13473 * This must be called from a UI thread. To call from a non-UI thread, call 13474 * {@link #postInvalidate()}. 13475 * 13476 * @param l the left position of the dirty region 13477 * @param t the top position of the dirty region 13478 * @param r the right position of the dirty region 13479 * @param b the bottom position of the dirty region 13480 */ 13481 public void invalidate(int l, int t, int r, int b) { 13482 final int scrollX = mScrollX; 13483 final int scrollY = mScrollY; 13484 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13485 } 13486 13487 /** 13488 * Invalidate the whole view. If the view is visible, 13489 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13490 * the future. 13491 * <p> 13492 * This must be called from a UI thread. To call from a non-UI thread, call 13493 * {@link #postInvalidate()}. 13494 */ 13495 public void invalidate() { 13496 invalidate(true); 13497 } 13498 13499 /** 13500 * This is where the invalidate() work actually happens. A full invalidate() 13501 * causes the drawing cache to be invalidated, but this function can be 13502 * called with invalidateCache set to false to skip that invalidation step 13503 * for cases that do not need it (for example, a component that remains at 13504 * the same dimensions with the same content). 13505 * 13506 * @param invalidateCache Whether the drawing cache for this view should be 13507 * invalidated as well. This is usually true for a full 13508 * invalidate, but may be set to false if the View's contents or 13509 * dimensions have not changed. 13510 */ 13511 void invalidate(boolean invalidateCache) { 13512 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13513 } 13514 13515 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13516 boolean fullInvalidate) { 13517 if (mGhostView != null) { 13518 mGhostView.invalidate(true); 13519 return; 13520 } 13521 13522 if (skipInvalidate()) { 13523 return; 13524 } 13525 13526 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13527 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13528 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13529 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13530 if (fullInvalidate) { 13531 mLastIsOpaque = isOpaque(); 13532 mPrivateFlags &= ~PFLAG_DRAWN; 13533 } 13534 13535 mPrivateFlags |= PFLAG_DIRTY; 13536 13537 if (invalidateCache) { 13538 mPrivateFlags |= PFLAG_INVALIDATED; 13539 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13540 } 13541 13542 // Propagate the damage rectangle to the parent view. 13543 final AttachInfo ai = mAttachInfo; 13544 final ViewParent p = mParent; 13545 if (p != null && ai != null && l < r && t < b) { 13546 final Rect damage = ai.mTmpInvalRect; 13547 damage.set(l, t, r, b); 13548 p.invalidateChild(this, damage); 13549 } 13550 13551 // Damage the entire projection receiver, if necessary. 13552 if (mBackground != null && mBackground.isProjected()) { 13553 final View receiver = getProjectionReceiver(); 13554 if (receiver != null) { 13555 receiver.damageInParent(); 13556 } 13557 } 13558 13559 // Damage the entire IsolatedZVolume receiving this view's shadow. 13560 if (isHardwareAccelerated() && getZ() != 0) { 13561 damageShadowReceiver(); 13562 } 13563 } 13564 } 13565 13566 /** 13567 * @return this view's projection receiver, or {@code null} if none exists 13568 */ 13569 private View getProjectionReceiver() { 13570 ViewParent p = getParent(); 13571 while (p != null && p instanceof View) { 13572 final View v = (View) p; 13573 if (v.isProjectionReceiver()) { 13574 return v; 13575 } 13576 p = p.getParent(); 13577 } 13578 13579 return null; 13580 } 13581 13582 /** 13583 * @return whether the view is a projection receiver 13584 */ 13585 private boolean isProjectionReceiver() { 13586 return mBackground != null; 13587 } 13588 13589 /** 13590 * Damage area of the screen that can be covered by this View's shadow. 13591 * 13592 * This method will guarantee that any changes to shadows cast by a View 13593 * are damaged on the screen for future redraw. 13594 */ 13595 private void damageShadowReceiver() { 13596 final AttachInfo ai = mAttachInfo; 13597 if (ai != null) { 13598 ViewParent p = getParent(); 13599 if (p != null && p instanceof ViewGroup) { 13600 final ViewGroup vg = (ViewGroup) p; 13601 vg.damageInParent(); 13602 } 13603 } 13604 } 13605 13606 /** 13607 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13608 * set any flags or handle all of the cases handled by the default invalidation methods. 13609 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13610 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13611 * walk up the hierarchy, transforming the dirty rect as necessary. 13612 * 13613 * The method also handles normal invalidation logic if display list properties are not 13614 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13615 * backup approach, to handle these cases used in the various property-setting methods. 13616 * 13617 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13618 * are not being used in this view 13619 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13620 * list properties are not being used in this view 13621 */ 13622 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13623 if (!isHardwareAccelerated() 13624 || !mRenderNode.isValid() 13625 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13626 if (invalidateParent) { 13627 invalidateParentCaches(); 13628 } 13629 if (forceRedraw) { 13630 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13631 } 13632 invalidate(false); 13633 } else { 13634 damageInParent(); 13635 } 13636 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13637 damageShadowReceiver(); 13638 } 13639 } 13640 13641 /** 13642 * Tells the parent view to damage this view's bounds. 13643 * 13644 * @hide 13645 */ 13646 protected void damageInParent() { 13647 final AttachInfo ai = mAttachInfo; 13648 final ViewParent p = mParent; 13649 if (p != null && ai != null) { 13650 final Rect r = ai.mTmpInvalRect; 13651 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13652 if (mParent instanceof ViewGroup) { 13653 ((ViewGroup) mParent).damageChild(this, r); 13654 } else { 13655 mParent.invalidateChild(this, r); 13656 } 13657 } 13658 } 13659 13660 /** 13661 * Utility method to transform a given Rect by the current matrix of this view. 13662 */ 13663 void transformRect(final Rect rect) { 13664 if (!getMatrix().isIdentity()) { 13665 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13666 boundingRect.set(rect); 13667 getMatrix().mapRect(boundingRect); 13668 rect.set((int) Math.floor(boundingRect.left), 13669 (int) Math.floor(boundingRect.top), 13670 (int) Math.ceil(boundingRect.right), 13671 (int) Math.ceil(boundingRect.bottom)); 13672 } 13673 } 13674 13675 /** 13676 * Used to indicate that the parent of this view should clear its caches. This functionality 13677 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13678 * which is necessary when various parent-managed properties of the view change, such as 13679 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13680 * clears the parent caches and does not causes an invalidate event. 13681 * 13682 * @hide 13683 */ 13684 protected void invalidateParentCaches() { 13685 if (mParent instanceof View) { 13686 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13687 } 13688 } 13689 13690 /** 13691 * Used to indicate that the parent of this view should be invalidated. This functionality 13692 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13693 * which is necessary when various parent-managed properties of the view change, such as 13694 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13695 * an invalidation event to the parent. 13696 * 13697 * @hide 13698 */ 13699 protected void invalidateParentIfNeeded() { 13700 if (isHardwareAccelerated() && mParent instanceof View) { 13701 ((View) mParent).invalidate(true); 13702 } 13703 } 13704 13705 /** 13706 * @hide 13707 */ 13708 protected void invalidateParentIfNeededAndWasQuickRejected() { 13709 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13710 // View was rejected last time it was drawn by its parent; this may have changed 13711 invalidateParentIfNeeded(); 13712 } 13713 } 13714 13715 /** 13716 * Indicates whether this View is opaque. An opaque View guarantees that it will 13717 * draw all the pixels overlapping its bounds using a fully opaque color. 13718 * 13719 * Subclasses of View should override this method whenever possible to indicate 13720 * whether an instance is opaque. Opaque Views are treated in a special way by 13721 * the View hierarchy, possibly allowing it to perform optimizations during 13722 * invalidate/draw passes. 13723 * 13724 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13725 */ 13726 @ViewDebug.ExportedProperty(category = "drawing") 13727 public boolean isOpaque() { 13728 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13729 getFinalAlpha() >= 1.0f; 13730 } 13731 13732 /** 13733 * @hide 13734 */ 13735 protected void computeOpaqueFlags() { 13736 // Opaque if: 13737 // - Has a background 13738 // - Background is opaque 13739 // - Doesn't have scrollbars or scrollbars overlay 13740 13741 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13742 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13743 } else { 13744 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13745 } 13746 13747 final int flags = mViewFlags; 13748 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13749 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13750 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13751 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13752 } else { 13753 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13754 } 13755 } 13756 13757 /** 13758 * @hide 13759 */ 13760 protected boolean hasOpaqueScrollbars() { 13761 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13762 } 13763 13764 /** 13765 * @return A handler associated with the thread running the View. This 13766 * handler can be used to pump events in the UI events queue. 13767 */ 13768 public Handler getHandler() { 13769 final AttachInfo attachInfo = mAttachInfo; 13770 if (attachInfo != null) { 13771 return attachInfo.mHandler; 13772 } 13773 return null; 13774 } 13775 13776 /** 13777 * Returns the queue of runnable for this view. 13778 * 13779 * @return the queue of runnables for this view 13780 */ 13781 private HandlerActionQueue getRunQueue() { 13782 if (mRunQueue == null) { 13783 mRunQueue = new HandlerActionQueue(); 13784 } 13785 return mRunQueue; 13786 } 13787 13788 /** 13789 * Gets the view root associated with the View. 13790 * @return The view root, or null if none. 13791 * @hide 13792 */ 13793 public ViewRootImpl getViewRootImpl() { 13794 if (mAttachInfo != null) { 13795 return mAttachInfo.mViewRootImpl; 13796 } 13797 return null; 13798 } 13799 13800 /** 13801 * @hide 13802 */ 13803 public ThreadedRenderer getHardwareRenderer() { 13804 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 13805 } 13806 13807 /** 13808 * <p>Causes the Runnable to be added to the message queue. 13809 * The runnable will be run on the user interface thread.</p> 13810 * 13811 * @param action The Runnable that will be executed. 13812 * 13813 * @return Returns true if the Runnable was successfully placed in to the 13814 * message queue. Returns false on failure, usually because the 13815 * looper processing the message queue is exiting. 13816 * 13817 * @see #postDelayed 13818 * @see #removeCallbacks 13819 */ 13820 public boolean post(Runnable action) { 13821 final AttachInfo attachInfo = mAttachInfo; 13822 if (attachInfo != null) { 13823 return attachInfo.mHandler.post(action); 13824 } 13825 13826 // Postpone the runnable until we know on which thread it needs to run. 13827 // Assume that the runnable will be successfully placed after attach. 13828 getRunQueue().post(action); 13829 return true; 13830 } 13831 13832 /** 13833 * <p>Causes the Runnable to be added to the message queue, to be run 13834 * after the specified amount of time elapses. 13835 * The runnable will be run on the user interface thread.</p> 13836 * 13837 * @param action The Runnable that will be executed. 13838 * @param delayMillis The delay (in milliseconds) until the Runnable 13839 * will be executed. 13840 * 13841 * @return true if the Runnable was successfully placed in to the 13842 * message queue. Returns false on failure, usually because the 13843 * looper processing the message queue is exiting. Note that a 13844 * result of true does not mean the Runnable will be processed -- 13845 * if the looper is quit before the delivery time of the message 13846 * occurs then the message will be dropped. 13847 * 13848 * @see #post 13849 * @see #removeCallbacks 13850 */ 13851 public boolean postDelayed(Runnable action, long delayMillis) { 13852 final AttachInfo attachInfo = mAttachInfo; 13853 if (attachInfo != null) { 13854 return attachInfo.mHandler.postDelayed(action, delayMillis); 13855 } 13856 13857 // Postpone the runnable until we know on which thread it needs to run. 13858 // Assume that the runnable will be successfully placed after attach. 13859 getRunQueue().postDelayed(action, delayMillis); 13860 return true; 13861 } 13862 13863 /** 13864 * <p>Causes the Runnable to execute on the next animation time step. 13865 * The runnable will be run on the user interface thread.</p> 13866 * 13867 * @param action The Runnable that will be executed. 13868 * 13869 * @see #postOnAnimationDelayed 13870 * @see #removeCallbacks 13871 */ 13872 public void postOnAnimation(Runnable action) { 13873 final AttachInfo attachInfo = mAttachInfo; 13874 if (attachInfo != null) { 13875 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13876 Choreographer.CALLBACK_ANIMATION, action, null); 13877 } else { 13878 // Postpone the runnable until we know 13879 // on which thread it needs to run. 13880 getRunQueue().post(action); 13881 } 13882 } 13883 13884 /** 13885 * <p>Causes the Runnable to execute on the next animation time step, 13886 * after the specified amount of time elapses. 13887 * The runnable will be run on the user interface thread.</p> 13888 * 13889 * @param action The Runnable that will be executed. 13890 * @param delayMillis The delay (in milliseconds) until the Runnable 13891 * will be executed. 13892 * 13893 * @see #postOnAnimation 13894 * @see #removeCallbacks 13895 */ 13896 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13897 final AttachInfo attachInfo = mAttachInfo; 13898 if (attachInfo != null) { 13899 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13900 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13901 } else { 13902 // Postpone the runnable until we know 13903 // on which thread it needs to run. 13904 getRunQueue().postDelayed(action, delayMillis); 13905 } 13906 } 13907 13908 /** 13909 * <p>Removes the specified Runnable from the message queue.</p> 13910 * 13911 * @param action The Runnable to remove from the message handling queue 13912 * 13913 * @return true if this view could ask the Handler to remove the Runnable, 13914 * false otherwise. When the returned value is true, the Runnable 13915 * may or may not have been actually removed from the message queue 13916 * (for instance, if the Runnable was not in the queue already.) 13917 * 13918 * @see #post 13919 * @see #postDelayed 13920 * @see #postOnAnimation 13921 * @see #postOnAnimationDelayed 13922 */ 13923 public boolean removeCallbacks(Runnable action) { 13924 if (action != null) { 13925 final AttachInfo attachInfo = mAttachInfo; 13926 if (attachInfo != null) { 13927 attachInfo.mHandler.removeCallbacks(action); 13928 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13929 Choreographer.CALLBACK_ANIMATION, action, null); 13930 } 13931 getRunQueue().removeCallbacks(action); 13932 } 13933 return true; 13934 } 13935 13936 /** 13937 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13938 * Use this to invalidate the View from a non-UI thread.</p> 13939 * 13940 * <p>This method can be invoked from outside of the UI thread 13941 * only when this View is attached to a window.</p> 13942 * 13943 * @see #invalidate() 13944 * @see #postInvalidateDelayed(long) 13945 */ 13946 public void postInvalidate() { 13947 postInvalidateDelayed(0); 13948 } 13949 13950 /** 13951 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13952 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13953 * 13954 * <p>This method can be invoked from outside of the UI thread 13955 * only when this View is attached to a window.</p> 13956 * 13957 * @param left The left coordinate of the rectangle to invalidate. 13958 * @param top The top coordinate of the rectangle to invalidate. 13959 * @param right The right coordinate of the rectangle to invalidate. 13960 * @param bottom The bottom coordinate of the rectangle to invalidate. 13961 * 13962 * @see #invalidate(int, int, int, int) 13963 * @see #invalidate(Rect) 13964 * @see #postInvalidateDelayed(long, int, int, int, int) 13965 */ 13966 public void postInvalidate(int left, int top, int right, int bottom) { 13967 postInvalidateDelayed(0, left, top, right, bottom); 13968 } 13969 13970 /** 13971 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13972 * loop. Waits for the specified amount of time.</p> 13973 * 13974 * <p>This method can be invoked from outside of the UI thread 13975 * only when this View is attached to a window.</p> 13976 * 13977 * @param delayMilliseconds the duration in milliseconds to delay the 13978 * invalidation by 13979 * 13980 * @see #invalidate() 13981 * @see #postInvalidate() 13982 */ 13983 public void postInvalidateDelayed(long delayMilliseconds) { 13984 // We try only with the AttachInfo because there's no point in invalidating 13985 // if we are not attached to our window 13986 final AttachInfo attachInfo = mAttachInfo; 13987 if (attachInfo != null) { 13988 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 13989 } 13990 } 13991 13992 /** 13993 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13994 * through the event loop. Waits for the specified amount of time.</p> 13995 * 13996 * <p>This method can be invoked from outside of the UI thread 13997 * only when this View is attached to a window.</p> 13998 * 13999 * @param delayMilliseconds the duration in milliseconds to delay the 14000 * invalidation by 14001 * @param left The left coordinate of the rectangle to invalidate. 14002 * @param top The top coordinate of the rectangle to invalidate. 14003 * @param right The right coordinate of the rectangle to invalidate. 14004 * @param bottom The bottom coordinate of the rectangle to invalidate. 14005 * 14006 * @see #invalidate(int, int, int, int) 14007 * @see #invalidate(Rect) 14008 * @see #postInvalidate(int, int, int, int) 14009 */ 14010 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 14011 int right, int bottom) { 14012 14013 // We try only with the AttachInfo because there's no point in invalidating 14014 // if we are not attached to our window 14015 final AttachInfo attachInfo = mAttachInfo; 14016 if (attachInfo != null) { 14017 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14018 info.target = this; 14019 info.left = left; 14020 info.top = top; 14021 info.right = right; 14022 info.bottom = bottom; 14023 14024 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 14025 } 14026 } 14027 14028 /** 14029 * <p>Cause an invalidate to happen on the next animation time step, typically the 14030 * next display frame.</p> 14031 * 14032 * <p>This method can be invoked from outside of the UI thread 14033 * only when this View is attached to a window.</p> 14034 * 14035 * @see #invalidate() 14036 */ 14037 public void postInvalidateOnAnimation() { 14038 // We try only with the AttachInfo because there's no point in invalidating 14039 // if we are not attached to our window 14040 final AttachInfo attachInfo = mAttachInfo; 14041 if (attachInfo != null) { 14042 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 14043 } 14044 } 14045 14046 /** 14047 * <p>Cause an invalidate of the specified area to happen on the next animation 14048 * time step, typically the next display frame.</p> 14049 * 14050 * <p>This method can be invoked from outside of the UI thread 14051 * only when this View is attached to a window.</p> 14052 * 14053 * @param left The left coordinate of the rectangle to invalidate. 14054 * @param top The top coordinate of the rectangle to invalidate. 14055 * @param right The right coordinate of the rectangle to invalidate. 14056 * @param bottom The bottom coordinate of the rectangle to invalidate. 14057 * 14058 * @see #invalidate(int, int, int, int) 14059 * @see #invalidate(Rect) 14060 */ 14061 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 14062 // We try only with the AttachInfo because there's no point in invalidating 14063 // if we are not attached to our window 14064 final AttachInfo attachInfo = mAttachInfo; 14065 if (attachInfo != null) { 14066 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 14067 info.target = this; 14068 info.left = left; 14069 info.top = top; 14070 info.right = right; 14071 info.bottom = bottom; 14072 14073 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 14074 } 14075 } 14076 14077 /** 14078 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 14079 * This event is sent at most once every 14080 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 14081 */ 14082 private void postSendViewScrolledAccessibilityEventCallback() { 14083 if (mSendViewScrolledAccessibilityEvent == null) { 14084 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 14085 } 14086 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 14087 mSendViewScrolledAccessibilityEvent.mIsPending = true; 14088 postDelayed(mSendViewScrolledAccessibilityEvent, 14089 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 14090 } 14091 } 14092 14093 /** 14094 * Called by a parent to request that a child update its values for mScrollX 14095 * and mScrollY if necessary. This will typically be done if the child is 14096 * animating a scroll using a {@link android.widget.Scroller Scroller} 14097 * object. 14098 */ 14099 public void computeScroll() { 14100 } 14101 14102 /** 14103 * <p>Indicate whether the horizontal edges are faded when the view is 14104 * scrolled horizontally.</p> 14105 * 14106 * @return true if the horizontal edges should are faded on scroll, false 14107 * otherwise 14108 * 14109 * @see #setHorizontalFadingEdgeEnabled(boolean) 14110 * 14111 * @attr ref android.R.styleable#View_requiresFadingEdge 14112 */ 14113 public boolean isHorizontalFadingEdgeEnabled() { 14114 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 14115 } 14116 14117 /** 14118 * <p>Define whether the horizontal edges should be faded when this view 14119 * is scrolled horizontally.</p> 14120 * 14121 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 14122 * be faded when the view is scrolled 14123 * horizontally 14124 * 14125 * @see #isHorizontalFadingEdgeEnabled() 14126 * 14127 * @attr ref android.R.styleable#View_requiresFadingEdge 14128 */ 14129 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 14130 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 14131 if (horizontalFadingEdgeEnabled) { 14132 initScrollCache(); 14133 } 14134 14135 mViewFlags ^= FADING_EDGE_HORIZONTAL; 14136 } 14137 } 14138 14139 /** 14140 * <p>Indicate whether the vertical edges are faded when the view is 14141 * scrolled horizontally.</p> 14142 * 14143 * @return true if the vertical edges should are faded on scroll, false 14144 * otherwise 14145 * 14146 * @see #setVerticalFadingEdgeEnabled(boolean) 14147 * 14148 * @attr ref android.R.styleable#View_requiresFadingEdge 14149 */ 14150 public boolean isVerticalFadingEdgeEnabled() { 14151 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 14152 } 14153 14154 /** 14155 * <p>Define whether the vertical edges should be faded when this view 14156 * is scrolled vertically.</p> 14157 * 14158 * @param verticalFadingEdgeEnabled true if the vertical edges should 14159 * be faded when the view is scrolled 14160 * vertically 14161 * 14162 * @see #isVerticalFadingEdgeEnabled() 14163 * 14164 * @attr ref android.R.styleable#View_requiresFadingEdge 14165 */ 14166 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14167 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14168 if (verticalFadingEdgeEnabled) { 14169 initScrollCache(); 14170 } 14171 14172 mViewFlags ^= FADING_EDGE_VERTICAL; 14173 } 14174 } 14175 14176 /** 14177 * Returns the strength, or intensity, of the top faded edge. The strength is 14178 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14179 * returns 0.0 or 1.0 but no value in between. 14180 * 14181 * Subclasses should override this method to provide a smoother fade transition 14182 * when scrolling occurs. 14183 * 14184 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14185 */ 14186 protected float getTopFadingEdgeStrength() { 14187 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14188 } 14189 14190 /** 14191 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14192 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14193 * returns 0.0 or 1.0 but no value in between. 14194 * 14195 * Subclasses should override this method to provide a smoother fade transition 14196 * when scrolling occurs. 14197 * 14198 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14199 */ 14200 protected float getBottomFadingEdgeStrength() { 14201 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14202 computeVerticalScrollRange() ? 1.0f : 0.0f; 14203 } 14204 14205 /** 14206 * Returns the strength, or intensity, of the left faded edge. The strength is 14207 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14208 * returns 0.0 or 1.0 but no value in between. 14209 * 14210 * Subclasses should override this method to provide a smoother fade transition 14211 * when scrolling occurs. 14212 * 14213 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14214 */ 14215 protected float getLeftFadingEdgeStrength() { 14216 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14217 } 14218 14219 /** 14220 * Returns the strength, or intensity, of the right faded edge. The strength is 14221 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14222 * returns 0.0 or 1.0 but no value in between. 14223 * 14224 * Subclasses should override this method to provide a smoother fade transition 14225 * when scrolling occurs. 14226 * 14227 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14228 */ 14229 protected float getRightFadingEdgeStrength() { 14230 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14231 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14232 } 14233 14234 /** 14235 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14236 * scrollbar is not drawn by default.</p> 14237 * 14238 * @return true if the horizontal scrollbar should be painted, false 14239 * otherwise 14240 * 14241 * @see #setHorizontalScrollBarEnabled(boolean) 14242 */ 14243 public boolean isHorizontalScrollBarEnabled() { 14244 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14245 } 14246 14247 /** 14248 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14249 * scrollbar is not drawn by default.</p> 14250 * 14251 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14252 * be painted 14253 * 14254 * @see #isHorizontalScrollBarEnabled() 14255 */ 14256 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14257 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14258 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14259 computeOpaqueFlags(); 14260 resolvePadding(); 14261 } 14262 } 14263 14264 /** 14265 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14266 * scrollbar is not drawn by default.</p> 14267 * 14268 * @return true if the vertical scrollbar should be painted, false 14269 * otherwise 14270 * 14271 * @see #setVerticalScrollBarEnabled(boolean) 14272 */ 14273 public boolean isVerticalScrollBarEnabled() { 14274 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14275 } 14276 14277 /** 14278 * <p>Define whether the vertical scrollbar should be drawn or not. The 14279 * scrollbar is not drawn by default.</p> 14280 * 14281 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14282 * be painted 14283 * 14284 * @see #isVerticalScrollBarEnabled() 14285 */ 14286 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14287 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14288 mViewFlags ^= SCROLLBARS_VERTICAL; 14289 computeOpaqueFlags(); 14290 resolvePadding(); 14291 } 14292 } 14293 14294 /** 14295 * @hide 14296 */ 14297 protected void recomputePadding() { 14298 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14299 } 14300 14301 /** 14302 * Define whether scrollbars will fade when the view is not scrolling. 14303 * 14304 * @param fadeScrollbars whether to enable fading 14305 * 14306 * @attr ref android.R.styleable#View_fadeScrollbars 14307 */ 14308 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14309 initScrollCache(); 14310 final ScrollabilityCache scrollabilityCache = mScrollCache; 14311 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14312 if (fadeScrollbars) { 14313 scrollabilityCache.state = ScrollabilityCache.OFF; 14314 } else { 14315 scrollabilityCache.state = ScrollabilityCache.ON; 14316 } 14317 } 14318 14319 /** 14320 * 14321 * Returns true if scrollbars will fade when this view is not scrolling 14322 * 14323 * @return true if scrollbar fading is enabled 14324 * 14325 * @attr ref android.R.styleable#View_fadeScrollbars 14326 */ 14327 public boolean isScrollbarFadingEnabled() { 14328 return mScrollCache != null && mScrollCache.fadeScrollBars; 14329 } 14330 14331 /** 14332 * 14333 * Returns the delay before scrollbars fade. 14334 * 14335 * @return the delay before scrollbars fade 14336 * 14337 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14338 */ 14339 public int getScrollBarDefaultDelayBeforeFade() { 14340 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14341 mScrollCache.scrollBarDefaultDelayBeforeFade; 14342 } 14343 14344 /** 14345 * Define the delay before scrollbars fade. 14346 * 14347 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14348 * 14349 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14350 */ 14351 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14352 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14353 } 14354 14355 /** 14356 * 14357 * Returns the scrollbar fade duration. 14358 * 14359 * @return the scrollbar fade duration 14360 * 14361 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14362 */ 14363 public int getScrollBarFadeDuration() { 14364 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14365 mScrollCache.scrollBarFadeDuration; 14366 } 14367 14368 /** 14369 * Define the scrollbar fade duration. 14370 * 14371 * @param scrollBarFadeDuration - the scrollbar fade duration 14372 * 14373 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14374 */ 14375 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14376 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14377 } 14378 14379 /** 14380 * 14381 * Returns the scrollbar size. 14382 * 14383 * @return the scrollbar size 14384 * 14385 * @attr ref android.R.styleable#View_scrollbarSize 14386 */ 14387 public int getScrollBarSize() { 14388 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14389 mScrollCache.scrollBarSize; 14390 } 14391 14392 /** 14393 * Define the scrollbar size. 14394 * 14395 * @param scrollBarSize - the scrollbar size 14396 * 14397 * @attr ref android.R.styleable#View_scrollbarSize 14398 */ 14399 public void setScrollBarSize(int scrollBarSize) { 14400 getScrollCache().scrollBarSize = scrollBarSize; 14401 } 14402 14403 /** 14404 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14405 * inset. When inset, they add to the padding of the view. And the scrollbars 14406 * can be drawn inside the padding area or on the edge of the view. For example, 14407 * if a view has a background drawable and you want to draw the scrollbars 14408 * inside the padding specified by the drawable, you can use 14409 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14410 * appear at the edge of the view, ignoring the padding, then you can use 14411 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14412 * @param style the style of the scrollbars. Should be one of 14413 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14414 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14415 * @see #SCROLLBARS_INSIDE_OVERLAY 14416 * @see #SCROLLBARS_INSIDE_INSET 14417 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14418 * @see #SCROLLBARS_OUTSIDE_INSET 14419 * 14420 * @attr ref android.R.styleable#View_scrollbarStyle 14421 */ 14422 public void setScrollBarStyle(@ScrollBarStyle int style) { 14423 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14424 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14425 computeOpaqueFlags(); 14426 resolvePadding(); 14427 } 14428 } 14429 14430 /** 14431 * <p>Returns the current scrollbar style.</p> 14432 * @return the current scrollbar style 14433 * @see #SCROLLBARS_INSIDE_OVERLAY 14434 * @see #SCROLLBARS_INSIDE_INSET 14435 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14436 * @see #SCROLLBARS_OUTSIDE_INSET 14437 * 14438 * @attr ref android.R.styleable#View_scrollbarStyle 14439 */ 14440 @ViewDebug.ExportedProperty(mapping = { 14441 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14442 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14443 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14444 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14445 }) 14446 @ScrollBarStyle 14447 public int getScrollBarStyle() { 14448 return mViewFlags & SCROLLBARS_STYLE_MASK; 14449 } 14450 14451 /** 14452 * <p>Compute the horizontal range that the horizontal scrollbar 14453 * represents.</p> 14454 * 14455 * <p>The range is expressed in arbitrary units that must be the same as the 14456 * units used by {@link #computeHorizontalScrollExtent()} and 14457 * {@link #computeHorizontalScrollOffset()}.</p> 14458 * 14459 * <p>The default range is the drawing width of this view.</p> 14460 * 14461 * @return the total horizontal range represented by the horizontal 14462 * scrollbar 14463 * 14464 * @see #computeHorizontalScrollExtent() 14465 * @see #computeHorizontalScrollOffset() 14466 * @see android.widget.ScrollBarDrawable 14467 */ 14468 protected int computeHorizontalScrollRange() { 14469 return getWidth(); 14470 } 14471 14472 /** 14473 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14474 * within the horizontal range. This value is used to compute the position 14475 * of the thumb within the scrollbar's track.</p> 14476 * 14477 * <p>The range is expressed in arbitrary units that must be the same as the 14478 * units used by {@link #computeHorizontalScrollRange()} and 14479 * {@link #computeHorizontalScrollExtent()}.</p> 14480 * 14481 * <p>The default offset is the scroll offset of this view.</p> 14482 * 14483 * @return the horizontal offset of the scrollbar's thumb 14484 * 14485 * @see #computeHorizontalScrollRange() 14486 * @see #computeHorizontalScrollExtent() 14487 * @see android.widget.ScrollBarDrawable 14488 */ 14489 protected int computeHorizontalScrollOffset() { 14490 return mScrollX; 14491 } 14492 14493 /** 14494 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14495 * within the horizontal range. This value is used to compute the length 14496 * of the thumb within the scrollbar's track.</p> 14497 * 14498 * <p>The range is expressed in arbitrary units that must be the same as the 14499 * units used by {@link #computeHorizontalScrollRange()} and 14500 * {@link #computeHorizontalScrollOffset()}.</p> 14501 * 14502 * <p>The default extent is the drawing width of this view.</p> 14503 * 14504 * @return the horizontal extent of the scrollbar's thumb 14505 * 14506 * @see #computeHorizontalScrollRange() 14507 * @see #computeHorizontalScrollOffset() 14508 * @see android.widget.ScrollBarDrawable 14509 */ 14510 protected int computeHorizontalScrollExtent() { 14511 return getWidth(); 14512 } 14513 14514 /** 14515 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14516 * 14517 * <p>The range is expressed in arbitrary units that must be the same as the 14518 * units used by {@link #computeVerticalScrollExtent()} and 14519 * {@link #computeVerticalScrollOffset()}.</p> 14520 * 14521 * @return the total vertical range represented by the vertical scrollbar 14522 * 14523 * <p>The default range is the drawing height of this view.</p> 14524 * 14525 * @see #computeVerticalScrollExtent() 14526 * @see #computeVerticalScrollOffset() 14527 * @see android.widget.ScrollBarDrawable 14528 */ 14529 protected int computeVerticalScrollRange() { 14530 return getHeight(); 14531 } 14532 14533 /** 14534 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14535 * within the horizontal range. This value is used to compute the position 14536 * of the thumb within the scrollbar's track.</p> 14537 * 14538 * <p>The range is expressed in arbitrary units that must be the same as the 14539 * units used by {@link #computeVerticalScrollRange()} and 14540 * {@link #computeVerticalScrollExtent()}.</p> 14541 * 14542 * <p>The default offset is the scroll offset of this view.</p> 14543 * 14544 * @return the vertical offset of the scrollbar's thumb 14545 * 14546 * @see #computeVerticalScrollRange() 14547 * @see #computeVerticalScrollExtent() 14548 * @see android.widget.ScrollBarDrawable 14549 */ 14550 protected int computeVerticalScrollOffset() { 14551 return mScrollY; 14552 } 14553 14554 /** 14555 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14556 * within the vertical range. This value is used to compute the length 14557 * of the thumb within the scrollbar's track.</p> 14558 * 14559 * <p>The range is expressed in arbitrary units that must be the same as the 14560 * units used by {@link #computeVerticalScrollRange()} and 14561 * {@link #computeVerticalScrollOffset()}.</p> 14562 * 14563 * <p>The default extent is the drawing height of this view.</p> 14564 * 14565 * @return the vertical extent of the scrollbar's thumb 14566 * 14567 * @see #computeVerticalScrollRange() 14568 * @see #computeVerticalScrollOffset() 14569 * @see android.widget.ScrollBarDrawable 14570 */ 14571 protected int computeVerticalScrollExtent() { 14572 return getHeight(); 14573 } 14574 14575 /** 14576 * Check if this view can be scrolled horizontally in a certain direction. 14577 * 14578 * @param direction Negative to check scrolling left, positive to check scrolling right. 14579 * @return true if this view can be scrolled in the specified direction, false otherwise. 14580 */ 14581 public boolean canScrollHorizontally(int direction) { 14582 final int offset = computeHorizontalScrollOffset(); 14583 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14584 if (range == 0) return false; 14585 if (direction < 0) { 14586 return offset > 0; 14587 } else { 14588 return offset < range - 1; 14589 } 14590 } 14591 14592 /** 14593 * Check if this view can be scrolled vertically in a certain direction. 14594 * 14595 * @param direction Negative to check scrolling up, positive to check scrolling down. 14596 * @return true if this view can be scrolled in the specified direction, false otherwise. 14597 */ 14598 public boolean canScrollVertically(int direction) { 14599 final int offset = computeVerticalScrollOffset(); 14600 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14601 if (range == 0) return false; 14602 if (direction < 0) { 14603 return offset > 0; 14604 } else { 14605 return offset < range - 1; 14606 } 14607 } 14608 14609 void getScrollIndicatorBounds(@NonNull Rect out) { 14610 out.left = mScrollX; 14611 out.right = mScrollX + mRight - mLeft; 14612 out.top = mScrollY; 14613 out.bottom = mScrollY + mBottom - mTop; 14614 } 14615 14616 private void onDrawScrollIndicators(Canvas c) { 14617 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14618 // No scroll indicators enabled. 14619 return; 14620 } 14621 14622 final Drawable dr = mScrollIndicatorDrawable; 14623 if (dr == null) { 14624 // Scroll indicators aren't supported here. 14625 return; 14626 } 14627 14628 final int h = dr.getIntrinsicHeight(); 14629 final int w = dr.getIntrinsicWidth(); 14630 final Rect rect = mAttachInfo.mTmpInvalRect; 14631 getScrollIndicatorBounds(rect); 14632 14633 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14634 final boolean canScrollUp = canScrollVertically(-1); 14635 if (canScrollUp) { 14636 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14637 dr.draw(c); 14638 } 14639 } 14640 14641 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14642 final boolean canScrollDown = canScrollVertically(1); 14643 if (canScrollDown) { 14644 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14645 dr.draw(c); 14646 } 14647 } 14648 14649 final int leftRtl; 14650 final int rightRtl; 14651 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14652 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14653 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14654 } else { 14655 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14656 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14657 } 14658 14659 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14660 if ((mPrivateFlags3 & leftMask) != 0) { 14661 final boolean canScrollLeft = canScrollHorizontally(-1); 14662 if (canScrollLeft) { 14663 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14664 dr.draw(c); 14665 } 14666 } 14667 14668 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14669 if ((mPrivateFlags3 & rightMask) != 0) { 14670 final boolean canScrollRight = canScrollHorizontally(1); 14671 if (canScrollRight) { 14672 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14673 dr.draw(c); 14674 } 14675 } 14676 } 14677 14678 private void getHorizontalScrollBarBounds(Rect bounds) { 14679 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14680 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14681 && !isVerticalScrollBarHidden(); 14682 final int size = getHorizontalScrollbarHeight(); 14683 final int verticalScrollBarGap = drawVerticalScrollBar ? 14684 getVerticalScrollbarWidth() : 0; 14685 final int width = mRight - mLeft; 14686 final int height = mBottom - mTop; 14687 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14688 bounds.left = mScrollX + (mPaddingLeft & inside); 14689 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14690 bounds.bottom = bounds.top + size; 14691 } 14692 14693 private void getVerticalScrollBarBounds(Rect bounds) { 14694 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14695 final int size = getVerticalScrollbarWidth(); 14696 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14697 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14698 verticalScrollbarPosition = isLayoutRtl() ? 14699 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14700 } 14701 final int width = mRight - mLeft; 14702 final int height = mBottom - mTop; 14703 switch (verticalScrollbarPosition) { 14704 default: 14705 case SCROLLBAR_POSITION_RIGHT: 14706 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14707 break; 14708 case SCROLLBAR_POSITION_LEFT: 14709 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14710 break; 14711 } 14712 bounds.top = mScrollY + (mPaddingTop & inside); 14713 bounds.right = bounds.left + size; 14714 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14715 } 14716 14717 /** 14718 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14719 * scrollbars are painted only if they have been awakened first.</p> 14720 * 14721 * @param canvas the canvas on which to draw the scrollbars 14722 * 14723 * @see #awakenScrollBars(int) 14724 */ 14725 protected final void onDrawScrollBars(Canvas canvas) { 14726 // scrollbars are drawn only when the animation is running 14727 final ScrollabilityCache cache = mScrollCache; 14728 if (cache != null) { 14729 14730 int state = cache.state; 14731 14732 if (state == ScrollabilityCache.OFF) { 14733 return; 14734 } 14735 14736 boolean invalidate = false; 14737 14738 if (state == ScrollabilityCache.FADING) { 14739 // We're fading -- get our fade interpolation 14740 if (cache.interpolatorValues == null) { 14741 cache.interpolatorValues = new float[1]; 14742 } 14743 14744 float[] values = cache.interpolatorValues; 14745 14746 // Stops the animation if we're done 14747 if (cache.scrollBarInterpolator.timeToValues(values) == 14748 Interpolator.Result.FREEZE_END) { 14749 cache.state = ScrollabilityCache.OFF; 14750 } else { 14751 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14752 } 14753 14754 // This will make the scroll bars inval themselves after 14755 // drawing. We only want this when we're fading so that 14756 // we prevent excessive redraws 14757 invalidate = true; 14758 } else { 14759 // We're just on -- but we may have been fading before so 14760 // reset alpha 14761 cache.scrollBar.mutate().setAlpha(255); 14762 } 14763 14764 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14765 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14766 && !isVerticalScrollBarHidden(); 14767 14768 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14769 final ScrollBarDrawable scrollBar = cache.scrollBar; 14770 14771 if (drawHorizontalScrollBar) { 14772 scrollBar.setParameters(computeHorizontalScrollRange(), 14773 computeHorizontalScrollOffset(), 14774 computeHorizontalScrollExtent(), false); 14775 final Rect bounds = cache.mScrollBarBounds; 14776 getHorizontalScrollBarBounds(bounds); 14777 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14778 bounds.right, bounds.bottom); 14779 if (invalidate) { 14780 invalidate(bounds); 14781 } 14782 } 14783 14784 if (drawVerticalScrollBar) { 14785 scrollBar.setParameters(computeVerticalScrollRange(), 14786 computeVerticalScrollOffset(), 14787 computeVerticalScrollExtent(), true); 14788 final Rect bounds = cache.mScrollBarBounds; 14789 getVerticalScrollBarBounds(bounds); 14790 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14791 bounds.right, bounds.bottom); 14792 if (invalidate) { 14793 invalidate(bounds); 14794 } 14795 } 14796 } 14797 } 14798 } 14799 14800 /** 14801 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14802 * FastScroller is visible. 14803 * @return whether to temporarily hide the vertical scrollbar 14804 * @hide 14805 */ 14806 protected boolean isVerticalScrollBarHidden() { 14807 return false; 14808 } 14809 14810 /** 14811 * <p>Draw the horizontal scrollbar if 14812 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14813 * 14814 * @param canvas the canvas on which to draw the scrollbar 14815 * @param scrollBar the scrollbar's drawable 14816 * 14817 * @see #isHorizontalScrollBarEnabled() 14818 * @see #computeHorizontalScrollRange() 14819 * @see #computeHorizontalScrollExtent() 14820 * @see #computeHorizontalScrollOffset() 14821 * @see android.widget.ScrollBarDrawable 14822 * @hide 14823 */ 14824 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14825 int l, int t, int r, int b) { 14826 scrollBar.setBounds(l, t, r, b); 14827 scrollBar.draw(canvas); 14828 } 14829 14830 /** 14831 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14832 * returns true.</p> 14833 * 14834 * @param canvas the canvas on which to draw the scrollbar 14835 * @param scrollBar the scrollbar's drawable 14836 * 14837 * @see #isVerticalScrollBarEnabled() 14838 * @see #computeVerticalScrollRange() 14839 * @see #computeVerticalScrollExtent() 14840 * @see #computeVerticalScrollOffset() 14841 * @see android.widget.ScrollBarDrawable 14842 * @hide 14843 */ 14844 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14845 int l, int t, int r, int b) { 14846 scrollBar.setBounds(l, t, r, b); 14847 scrollBar.draw(canvas); 14848 } 14849 14850 /** 14851 * Implement this to do your drawing. 14852 * 14853 * @param canvas the canvas on which the background will be drawn 14854 */ 14855 protected void onDraw(Canvas canvas) { 14856 } 14857 14858 /* 14859 * Caller is responsible for calling requestLayout if necessary. 14860 * (This allows addViewInLayout to not request a new layout.) 14861 */ 14862 void assignParent(ViewParent parent) { 14863 if (mParent == null) { 14864 mParent = parent; 14865 } else if (parent == null) { 14866 mParent = null; 14867 } else { 14868 throw new RuntimeException("view " + this + " being added, but" 14869 + " it already has a parent"); 14870 } 14871 } 14872 14873 /** 14874 * This is called when the view is attached to a window. At this point it 14875 * has a Surface and will start drawing. Note that this function is 14876 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14877 * however it may be called any time before the first onDraw -- including 14878 * before or after {@link #onMeasure(int, int)}. 14879 * 14880 * @see #onDetachedFromWindow() 14881 */ 14882 @CallSuper 14883 protected void onAttachedToWindow() { 14884 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14885 mParent.requestTransparentRegion(this); 14886 } 14887 14888 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14889 14890 jumpDrawablesToCurrentState(); 14891 14892 resetSubtreeAccessibilityStateChanged(); 14893 14894 // rebuild, since Outline not maintained while View is detached 14895 rebuildOutline(); 14896 14897 if (isFocused()) { 14898 InputMethodManager imm = InputMethodManager.peekInstance(); 14899 if (imm != null) { 14900 imm.focusIn(this); 14901 } 14902 } 14903 } 14904 14905 /** 14906 * Resolve all RTL related properties. 14907 * 14908 * @return true if resolution of RTL properties has been done 14909 * 14910 * @hide 14911 */ 14912 public boolean resolveRtlPropertiesIfNeeded() { 14913 if (!needRtlPropertiesResolution()) return false; 14914 14915 // Order is important here: LayoutDirection MUST be resolved first 14916 if (!isLayoutDirectionResolved()) { 14917 resolveLayoutDirection(); 14918 resolveLayoutParams(); 14919 } 14920 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14921 if (!isTextDirectionResolved()) { 14922 resolveTextDirection(); 14923 } 14924 if (!isTextAlignmentResolved()) { 14925 resolveTextAlignment(); 14926 } 14927 // Should resolve Drawables before Padding because we need the layout direction of the 14928 // Drawable to correctly resolve Padding. 14929 if (!areDrawablesResolved()) { 14930 resolveDrawables(); 14931 } 14932 if (!isPaddingResolved()) { 14933 resolvePadding(); 14934 } 14935 onRtlPropertiesChanged(getLayoutDirection()); 14936 return true; 14937 } 14938 14939 /** 14940 * Reset resolution of all RTL related properties. 14941 * 14942 * @hide 14943 */ 14944 public void resetRtlProperties() { 14945 resetResolvedLayoutDirection(); 14946 resetResolvedTextDirection(); 14947 resetResolvedTextAlignment(); 14948 resetResolvedPadding(); 14949 resetResolvedDrawables(); 14950 } 14951 14952 /** 14953 * @see #onScreenStateChanged(int) 14954 */ 14955 void dispatchScreenStateChanged(int screenState) { 14956 onScreenStateChanged(screenState); 14957 } 14958 14959 /** 14960 * This method is called whenever the state of the screen this view is 14961 * attached to changes. A state change will usually occurs when the screen 14962 * turns on or off (whether it happens automatically or the user does it 14963 * manually.) 14964 * 14965 * @param screenState The new state of the screen. Can be either 14966 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14967 */ 14968 public void onScreenStateChanged(int screenState) { 14969 } 14970 14971 /** 14972 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14973 */ 14974 private boolean hasRtlSupport() { 14975 return mContext.getApplicationInfo().hasRtlSupport(); 14976 } 14977 14978 /** 14979 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14980 * RTL not supported) 14981 */ 14982 private boolean isRtlCompatibilityMode() { 14983 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14984 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14985 } 14986 14987 /** 14988 * @return true if RTL properties need resolution. 14989 * 14990 */ 14991 private boolean needRtlPropertiesResolution() { 14992 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 14993 } 14994 14995 /** 14996 * Called when any RTL property (layout direction or text direction or text alignment) has 14997 * been changed. 14998 * 14999 * Subclasses need to override this method to take care of cached information that depends on the 15000 * resolved layout direction, or to inform child views that inherit their layout direction. 15001 * 15002 * The default implementation does nothing. 15003 * 15004 * @param layoutDirection the direction of the layout 15005 * 15006 * @see #LAYOUT_DIRECTION_LTR 15007 * @see #LAYOUT_DIRECTION_RTL 15008 */ 15009 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 15010 } 15011 15012 /** 15013 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 15014 * that the parent directionality can and will be resolved before its children. 15015 * 15016 * @return true if resolution has been done, false otherwise. 15017 * 15018 * @hide 15019 */ 15020 public boolean resolveLayoutDirection() { 15021 // Clear any previous layout direction resolution 15022 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15023 15024 if (hasRtlSupport()) { 15025 // Set resolved depending on layout direction 15026 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 15027 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 15028 case LAYOUT_DIRECTION_INHERIT: 15029 // We cannot resolve yet. LTR is by default and let the resolution happen again 15030 // later to get the correct resolved value 15031 if (!canResolveLayoutDirection()) return false; 15032 15033 // Parent has not yet resolved, LTR is still the default 15034 try { 15035 if (!mParent.isLayoutDirectionResolved()) return false; 15036 15037 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 15038 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15039 } 15040 } catch (AbstractMethodError e) { 15041 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15042 " does not fully implement ViewParent", e); 15043 } 15044 break; 15045 case LAYOUT_DIRECTION_RTL: 15046 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15047 break; 15048 case LAYOUT_DIRECTION_LOCALE: 15049 if((LAYOUT_DIRECTION_RTL == 15050 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 15051 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 15052 } 15053 break; 15054 default: 15055 // Nothing to do, LTR by default 15056 } 15057 } 15058 15059 // Set to resolved 15060 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15061 return true; 15062 } 15063 15064 /** 15065 * Check if layout direction resolution can be done. 15066 * 15067 * @return true if layout direction resolution can be done otherwise return false. 15068 */ 15069 public boolean canResolveLayoutDirection() { 15070 switch (getRawLayoutDirection()) { 15071 case LAYOUT_DIRECTION_INHERIT: 15072 if (mParent != null) { 15073 try { 15074 return mParent.canResolveLayoutDirection(); 15075 } catch (AbstractMethodError e) { 15076 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 15077 " does not fully implement ViewParent", e); 15078 } 15079 } 15080 return false; 15081 15082 default: 15083 return true; 15084 } 15085 } 15086 15087 /** 15088 * Reset the resolved layout direction. Layout direction will be resolved during a call to 15089 * {@link #onMeasure(int, int)}. 15090 * 15091 * @hide 15092 */ 15093 public void resetResolvedLayoutDirection() { 15094 // Reset the current resolved bits 15095 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 15096 } 15097 15098 /** 15099 * @return true if the layout direction is inherited. 15100 * 15101 * @hide 15102 */ 15103 public boolean isLayoutDirectionInherited() { 15104 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 15105 } 15106 15107 /** 15108 * @return true if layout direction has been resolved. 15109 */ 15110 public boolean isLayoutDirectionResolved() { 15111 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 15112 } 15113 15114 /** 15115 * Return if padding has been resolved 15116 * 15117 * @hide 15118 */ 15119 boolean isPaddingResolved() { 15120 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 15121 } 15122 15123 /** 15124 * Resolves padding depending on layout direction, if applicable, and 15125 * recomputes internal padding values to adjust for scroll bars. 15126 * 15127 * @hide 15128 */ 15129 public void resolvePadding() { 15130 final int resolvedLayoutDirection = getLayoutDirection(); 15131 15132 if (!isRtlCompatibilityMode()) { 15133 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 15134 // If start / end padding are defined, they will be resolved (hence overriding) to 15135 // left / right or right / left depending on the resolved layout direction. 15136 // If start / end padding are not defined, use the left / right ones. 15137 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 15138 Rect padding = sThreadLocal.get(); 15139 if (padding == null) { 15140 padding = new Rect(); 15141 sThreadLocal.set(padding); 15142 } 15143 mBackground.getPadding(padding); 15144 if (!mLeftPaddingDefined) { 15145 mUserPaddingLeftInitial = padding.left; 15146 } 15147 if (!mRightPaddingDefined) { 15148 mUserPaddingRightInitial = padding.right; 15149 } 15150 } 15151 switch (resolvedLayoutDirection) { 15152 case LAYOUT_DIRECTION_RTL: 15153 if (mUserPaddingStart != UNDEFINED_PADDING) { 15154 mUserPaddingRight = mUserPaddingStart; 15155 } else { 15156 mUserPaddingRight = mUserPaddingRightInitial; 15157 } 15158 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15159 mUserPaddingLeft = mUserPaddingEnd; 15160 } else { 15161 mUserPaddingLeft = mUserPaddingLeftInitial; 15162 } 15163 break; 15164 case LAYOUT_DIRECTION_LTR: 15165 default: 15166 if (mUserPaddingStart != UNDEFINED_PADDING) { 15167 mUserPaddingLeft = mUserPaddingStart; 15168 } else { 15169 mUserPaddingLeft = mUserPaddingLeftInitial; 15170 } 15171 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15172 mUserPaddingRight = mUserPaddingEnd; 15173 } else { 15174 mUserPaddingRight = mUserPaddingRightInitial; 15175 } 15176 } 15177 15178 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15179 } 15180 15181 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15182 onRtlPropertiesChanged(resolvedLayoutDirection); 15183 15184 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15185 } 15186 15187 /** 15188 * Reset the resolved layout direction. 15189 * 15190 * @hide 15191 */ 15192 public void resetResolvedPadding() { 15193 resetResolvedPaddingInternal(); 15194 } 15195 15196 /** 15197 * Used when we only want to reset *this* view's padding and not trigger overrides 15198 * in ViewGroup that reset children too. 15199 */ 15200 void resetResolvedPaddingInternal() { 15201 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15202 } 15203 15204 /** 15205 * This is called when the view is detached from a window. At this point it 15206 * no longer has a surface for drawing. 15207 * 15208 * @see #onAttachedToWindow() 15209 */ 15210 @CallSuper 15211 protected void onDetachedFromWindow() { 15212 } 15213 15214 /** 15215 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15216 * after onDetachedFromWindow(). 15217 * 15218 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15219 * The super method should be called at the end of the overridden method to ensure 15220 * subclasses are destroyed first 15221 * 15222 * @hide 15223 */ 15224 @CallSuper 15225 protected void onDetachedFromWindowInternal() { 15226 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15227 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15228 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 15229 15230 removeUnsetPressCallback(); 15231 removeLongPressCallback(); 15232 removePerformClickCallback(); 15233 removeSendViewScrolledAccessibilityEventCallback(); 15234 stopNestedScroll(); 15235 15236 // Anything that started animating right before detach should already 15237 // be in its final state when re-attached. 15238 jumpDrawablesToCurrentState(); 15239 15240 destroyDrawingCache(); 15241 15242 cleanupDraw(); 15243 releasePointerCapture(); 15244 mCurrentAnimation = null; 15245 } 15246 15247 private void cleanupDraw() { 15248 resetDisplayList(); 15249 if (mAttachInfo != null) { 15250 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15251 } 15252 } 15253 15254 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15255 } 15256 15257 /** 15258 * @return The number of times this view has been attached to a window 15259 */ 15260 protected int getWindowAttachCount() { 15261 return mWindowAttachCount; 15262 } 15263 15264 /** 15265 * Retrieve a unique token identifying the window this view is attached to. 15266 * @return Return the window's token for use in 15267 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15268 */ 15269 public IBinder getWindowToken() { 15270 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15271 } 15272 15273 /** 15274 * Retrieve the {@link WindowId} for the window this view is 15275 * currently attached to. 15276 */ 15277 public WindowId getWindowId() { 15278 if (mAttachInfo == null) { 15279 return null; 15280 } 15281 if (mAttachInfo.mWindowId == null) { 15282 try { 15283 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15284 mAttachInfo.mWindowToken); 15285 mAttachInfo.mWindowId = new WindowId( 15286 mAttachInfo.mIWindowId); 15287 } catch (RemoteException e) { 15288 } 15289 } 15290 return mAttachInfo.mWindowId; 15291 } 15292 15293 /** 15294 * Retrieve a unique token identifying the top-level "real" window of 15295 * the window that this view is attached to. That is, this is like 15296 * {@link #getWindowToken}, except if the window this view in is a panel 15297 * window (attached to another containing window), then the token of 15298 * the containing window is returned instead. 15299 * 15300 * @return Returns the associated window token, either 15301 * {@link #getWindowToken()} or the containing window's token. 15302 */ 15303 public IBinder getApplicationWindowToken() { 15304 AttachInfo ai = mAttachInfo; 15305 if (ai != null) { 15306 IBinder appWindowToken = ai.mPanelParentWindowToken; 15307 if (appWindowToken == null) { 15308 appWindowToken = ai.mWindowToken; 15309 } 15310 return appWindowToken; 15311 } 15312 return null; 15313 } 15314 15315 /** 15316 * Gets the logical display to which the view's window has been attached. 15317 * 15318 * @return The logical display, or null if the view is not currently attached to a window. 15319 */ 15320 public Display getDisplay() { 15321 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15322 } 15323 15324 /** 15325 * Retrieve private session object this view hierarchy is using to 15326 * communicate with the window manager. 15327 * @return the session object to communicate with the window manager 15328 */ 15329 /*package*/ IWindowSession getWindowSession() { 15330 return mAttachInfo != null ? mAttachInfo.mSession : null; 15331 } 15332 15333 /** 15334 * Return the visibility value of the least visible component passed. 15335 */ 15336 int combineVisibility(int vis1, int vis2) { 15337 // This works because VISIBLE < INVISIBLE < GONE. 15338 return Math.max(vis1, vis2); 15339 } 15340 15341 /** 15342 * @param info the {@link android.view.View.AttachInfo} to associated with 15343 * this view 15344 */ 15345 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15346 mAttachInfo = info; 15347 if (mOverlay != null) { 15348 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15349 } 15350 mWindowAttachCount++; 15351 // We will need to evaluate the drawable state at least once. 15352 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15353 if (mFloatingTreeObserver != null) { 15354 info.mTreeObserver.merge(mFloatingTreeObserver); 15355 mFloatingTreeObserver = null; 15356 } 15357 15358 registerPendingFrameMetricsObservers(); 15359 15360 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15361 mAttachInfo.mScrollContainers.add(this); 15362 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15363 } 15364 // Transfer all pending runnables. 15365 if (mRunQueue != null) { 15366 mRunQueue.executeActions(info.mHandler); 15367 mRunQueue = null; 15368 } 15369 performCollectViewAttributes(mAttachInfo, visibility); 15370 onAttachedToWindow(); 15371 15372 ListenerInfo li = mListenerInfo; 15373 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15374 li != null ? li.mOnAttachStateChangeListeners : null; 15375 if (listeners != null && listeners.size() > 0) { 15376 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15377 // perform the dispatching. The iterator is a safe guard against listeners that 15378 // could mutate the list by calling the various add/remove methods. This prevents 15379 // the array from being modified while we iterate it. 15380 for (OnAttachStateChangeListener listener : listeners) { 15381 listener.onViewAttachedToWindow(this); 15382 } 15383 } 15384 15385 int vis = info.mWindowVisibility; 15386 if (vis != GONE) { 15387 onWindowVisibilityChanged(vis); 15388 if (isShown()) { 15389 // Calling onVisibilityChanged directly here since the subtree will also 15390 // receive dispatchAttachedToWindow and this same call 15391 onVisibilityAggregated(vis == VISIBLE); 15392 } 15393 } 15394 15395 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15396 // As all views in the subtree will already receive dispatchAttachedToWindow 15397 // traversing the subtree again here is not desired. 15398 onVisibilityChanged(this, visibility); 15399 15400 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15401 // If nobody has evaluated the drawable state yet, then do it now. 15402 refreshDrawableState(); 15403 } 15404 needGlobalAttributesUpdate(false); 15405 } 15406 15407 void dispatchDetachedFromWindow() { 15408 AttachInfo info = mAttachInfo; 15409 if (info != null) { 15410 int vis = info.mWindowVisibility; 15411 if (vis != GONE) { 15412 onWindowVisibilityChanged(GONE); 15413 if (isShown()) { 15414 // Invoking onVisibilityAggregated directly here since the subtree 15415 // will also receive detached from window 15416 onVisibilityAggregated(false); 15417 } 15418 } 15419 } 15420 15421 onDetachedFromWindow(); 15422 onDetachedFromWindowInternal(); 15423 15424 InputMethodManager imm = InputMethodManager.peekInstance(); 15425 if (imm != null) { 15426 imm.onViewDetachedFromWindow(this); 15427 } 15428 15429 ListenerInfo li = mListenerInfo; 15430 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15431 li != null ? li.mOnAttachStateChangeListeners : null; 15432 if (listeners != null && listeners.size() > 0) { 15433 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15434 // perform the dispatching. The iterator is a safe guard against listeners that 15435 // could mutate the list by calling the various add/remove methods. This prevents 15436 // the array from being modified while we iterate it. 15437 for (OnAttachStateChangeListener listener : listeners) { 15438 listener.onViewDetachedFromWindow(this); 15439 } 15440 } 15441 15442 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15443 mAttachInfo.mScrollContainers.remove(this); 15444 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15445 } 15446 15447 mAttachInfo = null; 15448 if (mOverlay != null) { 15449 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15450 } 15451 } 15452 15453 /** 15454 * Cancel any deferred high-level input events that were previously posted to the event queue. 15455 * 15456 * <p>Many views post high-level events such as click handlers to the event queue 15457 * to run deferred in order to preserve a desired user experience - clearing visible 15458 * pressed states before executing, etc. This method will abort any events of this nature 15459 * that are currently in flight.</p> 15460 * 15461 * <p>Custom views that generate their own high-level deferred input events should override 15462 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15463 * 15464 * <p>This will also cancel pending input events for any child views.</p> 15465 * 15466 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15467 * This will not impact newer events posted after this call that may occur as a result of 15468 * lower-level input events still waiting in the queue. If you are trying to prevent 15469 * double-submitted events for the duration of some sort of asynchronous transaction 15470 * you should also take other steps to protect against unexpected double inputs e.g. calling 15471 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15472 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15473 */ 15474 public final void cancelPendingInputEvents() { 15475 dispatchCancelPendingInputEvents(); 15476 } 15477 15478 /** 15479 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15480 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15481 */ 15482 void dispatchCancelPendingInputEvents() { 15483 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15484 onCancelPendingInputEvents(); 15485 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15486 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15487 " did not call through to super.onCancelPendingInputEvents()"); 15488 } 15489 } 15490 15491 /** 15492 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15493 * a parent view. 15494 * 15495 * <p>This method is responsible for removing any pending high-level input events that were 15496 * posted to the event queue to run later. Custom view classes that post their own deferred 15497 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15498 * {@link android.os.Handler} should override this method, call 15499 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15500 * </p> 15501 */ 15502 public void onCancelPendingInputEvents() { 15503 removePerformClickCallback(); 15504 cancelLongPress(); 15505 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15506 } 15507 15508 /** 15509 * Store this view hierarchy's frozen state into the given container. 15510 * 15511 * @param container The SparseArray in which to save the view's state. 15512 * 15513 * @see #restoreHierarchyState(android.util.SparseArray) 15514 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15515 * @see #onSaveInstanceState() 15516 */ 15517 public void saveHierarchyState(SparseArray<Parcelable> container) { 15518 dispatchSaveInstanceState(container); 15519 } 15520 15521 /** 15522 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15523 * this view and its children. May be overridden to modify how freezing happens to a 15524 * view's children; for example, some views may want to not store state for their children. 15525 * 15526 * @param container The SparseArray in which to save the view's state. 15527 * 15528 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15529 * @see #saveHierarchyState(android.util.SparseArray) 15530 * @see #onSaveInstanceState() 15531 */ 15532 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15533 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15534 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15535 Parcelable state = onSaveInstanceState(); 15536 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15537 throw new IllegalStateException( 15538 "Derived class did not call super.onSaveInstanceState()"); 15539 } 15540 if (state != null) { 15541 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15542 // + ": " + state); 15543 container.put(mID, state); 15544 } 15545 } 15546 } 15547 15548 /** 15549 * Hook allowing a view to generate a representation of its internal state 15550 * that can later be used to create a new instance with that same state. 15551 * This state should only contain information that is not persistent or can 15552 * not be reconstructed later. For example, you will never store your 15553 * current position on screen because that will be computed again when a 15554 * new instance of the view is placed in its view hierarchy. 15555 * <p> 15556 * Some examples of things you may store here: the current cursor position 15557 * in a text view (but usually not the text itself since that is stored in a 15558 * content provider or other persistent storage), the currently selected 15559 * item in a list view. 15560 * 15561 * @return Returns a Parcelable object containing the view's current dynamic 15562 * state, or null if there is nothing interesting to save. The 15563 * default implementation returns null. 15564 * @see #onRestoreInstanceState(android.os.Parcelable) 15565 * @see #saveHierarchyState(android.util.SparseArray) 15566 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15567 * @see #setSaveEnabled(boolean) 15568 */ 15569 @CallSuper 15570 protected Parcelable onSaveInstanceState() { 15571 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15572 if (mStartActivityRequestWho != null) { 15573 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15574 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15575 return state; 15576 } 15577 return BaseSavedState.EMPTY_STATE; 15578 } 15579 15580 /** 15581 * Restore this view hierarchy's frozen state from the given container. 15582 * 15583 * @param container The SparseArray which holds previously frozen states. 15584 * 15585 * @see #saveHierarchyState(android.util.SparseArray) 15586 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15587 * @see #onRestoreInstanceState(android.os.Parcelable) 15588 */ 15589 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15590 dispatchRestoreInstanceState(container); 15591 } 15592 15593 /** 15594 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15595 * state for this view and its children. May be overridden to modify how restoring 15596 * happens to a view's children; for example, some views may want to not store state 15597 * for their children. 15598 * 15599 * @param container The SparseArray which holds previously saved state. 15600 * 15601 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15602 * @see #restoreHierarchyState(android.util.SparseArray) 15603 * @see #onRestoreInstanceState(android.os.Parcelable) 15604 */ 15605 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15606 if (mID != NO_ID) { 15607 Parcelable state = container.get(mID); 15608 if (state != null) { 15609 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15610 // + ": " + state); 15611 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15612 onRestoreInstanceState(state); 15613 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15614 throw new IllegalStateException( 15615 "Derived class did not call super.onRestoreInstanceState()"); 15616 } 15617 } 15618 } 15619 } 15620 15621 /** 15622 * Hook allowing a view to re-apply a representation of its internal state that had previously 15623 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15624 * null state. 15625 * 15626 * @param state The frozen state that had previously been returned by 15627 * {@link #onSaveInstanceState}. 15628 * 15629 * @see #onSaveInstanceState() 15630 * @see #restoreHierarchyState(android.util.SparseArray) 15631 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15632 */ 15633 @CallSuper 15634 protected void onRestoreInstanceState(Parcelable state) { 15635 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15636 if (state != null && !(state instanceof AbsSavedState)) { 15637 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15638 + "received " + state.getClass().toString() + " instead. This usually happens " 15639 + "when two views of different type have the same id in the same hierarchy. " 15640 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15641 + "other views do not use the same id."); 15642 } 15643 if (state != null && state instanceof BaseSavedState) { 15644 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15645 } 15646 } 15647 15648 /** 15649 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15650 * 15651 * @return the drawing start time in milliseconds 15652 */ 15653 public long getDrawingTime() { 15654 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15655 } 15656 15657 /** 15658 * <p>Enables or disables the duplication of the parent's state into this view. When 15659 * duplication is enabled, this view gets its drawable state from its parent rather 15660 * than from its own internal properties.</p> 15661 * 15662 * <p>Note: in the current implementation, setting this property to true after the 15663 * view was added to a ViewGroup might have no effect at all. This property should 15664 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15665 * 15666 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15667 * property is enabled, an exception will be thrown.</p> 15668 * 15669 * <p>Note: if the child view uses and updates additional states which are unknown to the 15670 * parent, these states should not be affected by this method.</p> 15671 * 15672 * @param enabled True to enable duplication of the parent's drawable state, false 15673 * to disable it. 15674 * 15675 * @see #getDrawableState() 15676 * @see #isDuplicateParentStateEnabled() 15677 */ 15678 public void setDuplicateParentStateEnabled(boolean enabled) { 15679 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15680 } 15681 15682 /** 15683 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15684 * 15685 * @return True if this view's drawable state is duplicated from the parent, 15686 * false otherwise 15687 * 15688 * @see #getDrawableState() 15689 * @see #setDuplicateParentStateEnabled(boolean) 15690 */ 15691 public boolean isDuplicateParentStateEnabled() { 15692 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15693 } 15694 15695 /** 15696 * <p>Specifies the type of layer backing this view. The layer can be 15697 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15698 * {@link #LAYER_TYPE_HARDWARE}.</p> 15699 * 15700 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15701 * instance that controls how the layer is composed on screen. The following 15702 * properties of the paint are taken into account when composing the layer:</p> 15703 * <ul> 15704 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15705 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15706 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15707 * </ul> 15708 * 15709 * <p>If this view has an alpha value set to < 1.0 by calling 15710 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15711 * by this view's alpha value.</p> 15712 * 15713 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15714 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15715 * for more information on when and how to use layers.</p> 15716 * 15717 * @param layerType The type of layer to use with this view, must be one of 15718 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15719 * {@link #LAYER_TYPE_HARDWARE} 15720 * @param paint The paint used to compose the layer. This argument is optional 15721 * and can be null. It is ignored when the layer type is 15722 * {@link #LAYER_TYPE_NONE} 15723 * 15724 * @see #getLayerType() 15725 * @see #LAYER_TYPE_NONE 15726 * @see #LAYER_TYPE_SOFTWARE 15727 * @see #LAYER_TYPE_HARDWARE 15728 * @see #setAlpha(float) 15729 * 15730 * @attr ref android.R.styleable#View_layerType 15731 */ 15732 public void setLayerType(int layerType, @Nullable Paint paint) { 15733 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15734 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15735 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15736 } 15737 15738 boolean typeChanged = mRenderNode.setLayerType(layerType); 15739 15740 if (!typeChanged) { 15741 setLayerPaint(paint); 15742 return; 15743 } 15744 15745 // Destroy any previous software drawing cache if needed 15746 if (mLayerType == LAYER_TYPE_SOFTWARE) { 15747 destroyDrawingCache(); 15748 } 15749 15750 mLayerType = layerType; 15751 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 15752 mRenderNode.setLayerPaint(mLayerPaint); 15753 15754 // draw() behaves differently if we are on a layer, so we need to 15755 // invalidate() here 15756 invalidateParentCaches(); 15757 invalidate(true); 15758 } 15759 15760 /** 15761 * Updates the {@link Paint} object used with the current layer (used only if the current 15762 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15763 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15764 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15765 * ensure that the view gets redrawn immediately. 15766 * 15767 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15768 * instance that controls how the layer is composed on screen. The following 15769 * properties of the paint are taken into account when composing the layer:</p> 15770 * <ul> 15771 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15772 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15773 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15774 * </ul> 15775 * 15776 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15777 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15778 * 15779 * @param paint The paint used to compose the layer. This argument is optional 15780 * and can be null. It is ignored when the layer type is 15781 * {@link #LAYER_TYPE_NONE} 15782 * 15783 * @see #setLayerType(int, android.graphics.Paint) 15784 */ 15785 public void setLayerPaint(@Nullable Paint paint) { 15786 int layerType = getLayerType(); 15787 if (layerType != LAYER_TYPE_NONE) { 15788 mLayerPaint = paint; 15789 if (layerType == LAYER_TYPE_HARDWARE) { 15790 if (mRenderNode.setLayerPaint(paint)) { 15791 invalidateViewProperty(false, false); 15792 } 15793 } else { 15794 invalidate(); 15795 } 15796 } 15797 } 15798 15799 /** 15800 * Indicates what type of layer is currently associated with this view. By default 15801 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15802 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15803 * for more information on the different types of layers. 15804 * 15805 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15806 * {@link #LAYER_TYPE_HARDWARE} 15807 * 15808 * @see #setLayerType(int, android.graphics.Paint) 15809 * @see #buildLayer() 15810 * @see #LAYER_TYPE_NONE 15811 * @see #LAYER_TYPE_SOFTWARE 15812 * @see #LAYER_TYPE_HARDWARE 15813 */ 15814 public int getLayerType() { 15815 return mLayerType; 15816 } 15817 15818 /** 15819 * Forces this view's layer to be created and this view to be rendered 15820 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15821 * invoking this method will have no effect. 15822 * 15823 * This method can for instance be used to render a view into its layer before 15824 * starting an animation. If this view is complex, rendering into the layer 15825 * before starting the animation will avoid skipping frames. 15826 * 15827 * @throws IllegalStateException If this view is not attached to a window 15828 * 15829 * @see #setLayerType(int, android.graphics.Paint) 15830 */ 15831 public void buildLayer() { 15832 if (mLayerType == LAYER_TYPE_NONE) return; 15833 15834 final AttachInfo attachInfo = mAttachInfo; 15835 if (attachInfo == null) { 15836 throw new IllegalStateException("This view must be attached to a window first"); 15837 } 15838 15839 if (getWidth() == 0 || getHeight() == 0) { 15840 return; 15841 } 15842 15843 switch (mLayerType) { 15844 case LAYER_TYPE_HARDWARE: 15845 updateDisplayListIfDirty(); 15846 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 15847 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 15848 } 15849 break; 15850 case LAYER_TYPE_SOFTWARE: 15851 buildDrawingCache(true); 15852 break; 15853 } 15854 } 15855 15856 /** 15857 * Destroys all hardware rendering resources. This method is invoked 15858 * when the system needs to reclaim resources. Upon execution of this 15859 * method, you should free any OpenGL resources created by the view. 15860 * 15861 * Note: you <strong>must</strong> call 15862 * <code>super.destroyHardwareResources()</code> when overriding 15863 * this method. 15864 * 15865 * @hide 15866 */ 15867 @CallSuper 15868 protected void destroyHardwareResources() { 15869 // Although the Layer will be destroyed by RenderNode, we want to release 15870 // the staging display list, which is also a signal to RenderNode that it's 15871 // safe to free its copy of the display list as it knows that we will 15872 // push an updated DisplayList if we try to draw again 15873 resetDisplayList(); 15874 } 15875 15876 /** 15877 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15878 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15879 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15880 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15881 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15882 * null.</p> 15883 * 15884 * <p>Enabling the drawing cache is similar to 15885 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15886 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15887 * drawing cache has no effect on rendering because the system uses a different mechanism 15888 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15889 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15890 * for information on how to enable software and hardware layers.</p> 15891 * 15892 * <p>This API can be used to manually generate 15893 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15894 * {@link #getDrawingCache()}.</p> 15895 * 15896 * @param enabled true to enable the drawing cache, false otherwise 15897 * 15898 * @see #isDrawingCacheEnabled() 15899 * @see #getDrawingCache() 15900 * @see #buildDrawingCache() 15901 * @see #setLayerType(int, android.graphics.Paint) 15902 */ 15903 public void setDrawingCacheEnabled(boolean enabled) { 15904 mCachingFailed = false; 15905 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15906 } 15907 15908 /** 15909 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15910 * 15911 * @return true if the drawing cache is enabled 15912 * 15913 * @see #setDrawingCacheEnabled(boolean) 15914 * @see #getDrawingCache() 15915 */ 15916 @ViewDebug.ExportedProperty(category = "drawing") 15917 public boolean isDrawingCacheEnabled() { 15918 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15919 } 15920 15921 /** 15922 * Debugging utility which recursively outputs the dirty state of a view and its 15923 * descendants. 15924 * 15925 * @hide 15926 */ 15927 @SuppressWarnings({"UnusedDeclaration"}) 15928 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15929 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15930 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15931 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15932 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15933 if (clear) { 15934 mPrivateFlags &= clearMask; 15935 } 15936 if (this instanceof ViewGroup) { 15937 ViewGroup parent = (ViewGroup) this; 15938 final int count = parent.getChildCount(); 15939 for (int i = 0; i < count; i++) { 15940 final View child = parent.getChildAt(i); 15941 child.outputDirtyFlags(indent + " ", clear, clearMask); 15942 } 15943 } 15944 } 15945 15946 /** 15947 * This method is used by ViewGroup to cause its children to restore or recreate their 15948 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15949 * to recreate its own display list, which would happen if it went through the normal 15950 * draw/dispatchDraw mechanisms. 15951 * 15952 * @hide 15953 */ 15954 protected void dispatchGetDisplayList() {} 15955 15956 /** 15957 * A view that is not attached or hardware accelerated cannot create a display list. 15958 * This method checks these conditions and returns the appropriate result. 15959 * 15960 * @return true if view has the ability to create a display list, false otherwise. 15961 * 15962 * @hide 15963 */ 15964 public boolean canHaveDisplayList() { 15965 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15966 } 15967 15968 /** 15969 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15970 * @hide 15971 */ 15972 @NonNull 15973 public RenderNode updateDisplayListIfDirty() { 15974 final RenderNode renderNode = mRenderNode; 15975 if (!canHaveDisplayList()) { 15976 // can't populate RenderNode, don't try 15977 return renderNode; 15978 } 15979 15980 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15981 || !renderNode.isValid() 15982 || (mRecreateDisplayList)) { 15983 // Don't need to recreate the display list, just need to tell our 15984 // children to restore/recreate theirs 15985 if (renderNode.isValid() 15986 && !mRecreateDisplayList) { 15987 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15988 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15989 dispatchGetDisplayList(); 15990 15991 return renderNode; // no work needed 15992 } 15993 15994 // If we got here, we're recreating it. Mark it as such to ensure that 15995 // we copy in child display lists into ours in drawChild() 15996 mRecreateDisplayList = true; 15997 15998 int width = mRight - mLeft; 15999 int height = mBottom - mTop; 16000 int layerType = getLayerType(); 16001 16002 final DisplayListCanvas canvas = renderNode.start(width, height); 16003 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 16004 16005 try { 16006 if (layerType == LAYER_TYPE_SOFTWARE) { 16007 buildDrawingCache(true); 16008 Bitmap cache = getDrawingCache(true); 16009 if (cache != null) { 16010 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 16011 } 16012 } else { 16013 computeScroll(); 16014 16015 canvas.translate(-mScrollX, -mScrollY); 16016 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16017 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16018 16019 // Fast path for layouts with no backgrounds 16020 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16021 dispatchDraw(canvas); 16022 if (mOverlay != null && !mOverlay.isEmpty()) { 16023 mOverlay.getOverlayView().draw(canvas); 16024 } 16025 } else { 16026 draw(canvas); 16027 } 16028 } 16029 } finally { 16030 renderNode.end(canvas); 16031 setDisplayListProperties(renderNode); 16032 } 16033 } else { 16034 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 16035 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16036 } 16037 return renderNode; 16038 } 16039 16040 private void resetDisplayList() { 16041 if (mRenderNode.isValid()) { 16042 mRenderNode.discardDisplayList(); 16043 } 16044 16045 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 16046 mBackgroundRenderNode.discardDisplayList(); 16047 } 16048 } 16049 16050 /** 16051 * Called when the passed RenderNode is removed from the draw tree 16052 * @hide 16053 */ 16054 public void onRenderNodeDetached(RenderNode renderNode) { 16055 if (renderNode == mRenderNode && mRenderNodeDetachedCallback != null) { 16056 mRenderNodeDetachedCallback.run(); 16057 } 16058 } 16059 16060 /** 16061 * Set callback for functor detach. Exposed to WebView through WebViewDelegate. 16062 * Should not be used otherwise. 16063 * @hide 16064 */ 16065 public final Runnable setRenderNodeDetachedCallback(@Nullable Runnable callback) { 16066 Runnable oldCallback = mRenderNodeDetachedCallback; 16067 mRenderNodeDetachedCallback = callback; 16068 return oldCallback; 16069 } 16070 16071 /** 16072 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 16073 * 16074 * @return A non-scaled bitmap representing this view or null if cache is disabled. 16075 * 16076 * @see #getDrawingCache(boolean) 16077 */ 16078 public Bitmap getDrawingCache() { 16079 return getDrawingCache(false); 16080 } 16081 16082 /** 16083 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 16084 * is null when caching is disabled. If caching is enabled and the cache is not ready, 16085 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 16086 * draw from the cache when the cache is enabled. To benefit from the cache, you must 16087 * request the drawing cache by calling this method and draw it on screen if the 16088 * returned bitmap is not null.</p> 16089 * 16090 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16091 * this method will create a bitmap of the same size as this view. Because this bitmap 16092 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16093 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16094 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16095 * size than the view. This implies that your application must be able to handle this 16096 * size.</p> 16097 * 16098 * @param autoScale Indicates whether the generated bitmap should be scaled based on 16099 * the current density of the screen when the application is in compatibility 16100 * mode. 16101 * 16102 * @return A bitmap representing this view or null if cache is disabled. 16103 * 16104 * @see #setDrawingCacheEnabled(boolean) 16105 * @see #isDrawingCacheEnabled() 16106 * @see #buildDrawingCache(boolean) 16107 * @see #destroyDrawingCache() 16108 */ 16109 public Bitmap getDrawingCache(boolean autoScale) { 16110 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 16111 return null; 16112 } 16113 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 16114 buildDrawingCache(autoScale); 16115 } 16116 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 16117 } 16118 16119 /** 16120 * <p>Frees the resources used by the drawing cache. If you call 16121 * {@link #buildDrawingCache()} manually without calling 16122 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16123 * should cleanup the cache with this method afterwards.</p> 16124 * 16125 * @see #setDrawingCacheEnabled(boolean) 16126 * @see #buildDrawingCache() 16127 * @see #getDrawingCache() 16128 */ 16129 public void destroyDrawingCache() { 16130 if (mDrawingCache != null) { 16131 mDrawingCache.recycle(); 16132 mDrawingCache = null; 16133 } 16134 if (mUnscaledDrawingCache != null) { 16135 mUnscaledDrawingCache.recycle(); 16136 mUnscaledDrawingCache = null; 16137 } 16138 } 16139 16140 /** 16141 * Setting a solid background color for the drawing cache's bitmaps will improve 16142 * performance and memory usage. Note, though that this should only be used if this 16143 * view will always be drawn on top of a solid color. 16144 * 16145 * @param color The background color to use for the drawing cache's bitmap 16146 * 16147 * @see #setDrawingCacheEnabled(boolean) 16148 * @see #buildDrawingCache() 16149 * @see #getDrawingCache() 16150 */ 16151 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 16152 if (color != mDrawingCacheBackgroundColor) { 16153 mDrawingCacheBackgroundColor = color; 16154 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 16155 } 16156 } 16157 16158 /** 16159 * @see #setDrawingCacheBackgroundColor(int) 16160 * 16161 * @return The background color to used for the drawing cache's bitmap 16162 */ 16163 @ColorInt 16164 public int getDrawingCacheBackgroundColor() { 16165 return mDrawingCacheBackgroundColor; 16166 } 16167 16168 /** 16169 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 16170 * 16171 * @see #buildDrawingCache(boolean) 16172 */ 16173 public void buildDrawingCache() { 16174 buildDrawingCache(false); 16175 } 16176 16177 /** 16178 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 16179 * 16180 * <p>If you call {@link #buildDrawingCache()} manually without calling 16181 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 16182 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 16183 * 16184 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 16185 * this method will create a bitmap of the same size as this view. Because this bitmap 16186 * will be drawn scaled by the parent ViewGroup, the result on screen might show 16187 * scaling artifacts. To avoid such artifacts, you should call this method by setting 16188 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 16189 * size than the view. This implies that your application must be able to handle this 16190 * size.</p> 16191 * 16192 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16193 * you do not need the drawing cache bitmap, calling this method will increase memory 16194 * usage and cause the view to be rendered in software once, thus negatively impacting 16195 * performance.</p> 16196 * 16197 * @see #getDrawingCache() 16198 * @see #destroyDrawingCache() 16199 */ 16200 public void buildDrawingCache(boolean autoScale) { 16201 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16202 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16203 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16204 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16205 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16206 } 16207 try { 16208 buildDrawingCacheImpl(autoScale); 16209 } finally { 16210 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16211 } 16212 } 16213 } 16214 16215 /** 16216 * private, internal implementation of buildDrawingCache, used to enable tracing 16217 */ 16218 private void buildDrawingCacheImpl(boolean autoScale) { 16219 mCachingFailed = false; 16220 16221 int width = mRight - mLeft; 16222 int height = mBottom - mTop; 16223 16224 final AttachInfo attachInfo = mAttachInfo; 16225 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16226 16227 if (autoScale && scalingRequired) { 16228 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16229 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16230 } 16231 16232 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16233 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16234 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16235 16236 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16237 final long drawingCacheSize = 16238 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16239 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16240 if (width > 0 && height > 0) { 16241 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16242 + " too large to fit into a software layer (or drawing cache), needs " 16243 + projectedBitmapSize + " bytes, only " 16244 + drawingCacheSize + " available"); 16245 } 16246 destroyDrawingCache(); 16247 mCachingFailed = true; 16248 return; 16249 } 16250 16251 boolean clear = true; 16252 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16253 16254 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16255 Bitmap.Config quality; 16256 if (!opaque) { 16257 // Never pick ARGB_4444 because it looks awful 16258 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16259 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16260 case DRAWING_CACHE_QUALITY_AUTO: 16261 case DRAWING_CACHE_QUALITY_LOW: 16262 case DRAWING_CACHE_QUALITY_HIGH: 16263 default: 16264 quality = Bitmap.Config.ARGB_8888; 16265 break; 16266 } 16267 } else { 16268 // Optimization for translucent windows 16269 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16270 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16271 } 16272 16273 // Try to cleanup memory 16274 if (bitmap != null) bitmap.recycle(); 16275 16276 try { 16277 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16278 width, height, quality); 16279 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16280 if (autoScale) { 16281 mDrawingCache = bitmap; 16282 } else { 16283 mUnscaledDrawingCache = bitmap; 16284 } 16285 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16286 } catch (OutOfMemoryError e) { 16287 // If there is not enough memory to create the bitmap cache, just 16288 // ignore the issue as bitmap caches are not required to draw the 16289 // view hierarchy 16290 if (autoScale) { 16291 mDrawingCache = null; 16292 } else { 16293 mUnscaledDrawingCache = null; 16294 } 16295 mCachingFailed = true; 16296 return; 16297 } 16298 16299 clear = drawingCacheBackgroundColor != 0; 16300 } 16301 16302 Canvas canvas; 16303 if (attachInfo != null) { 16304 canvas = attachInfo.mCanvas; 16305 if (canvas == null) { 16306 canvas = new Canvas(); 16307 } 16308 canvas.setBitmap(bitmap); 16309 // Temporarily clobber the cached Canvas in case one of our children 16310 // is also using a drawing cache. Without this, the children would 16311 // steal the canvas by attaching their own bitmap to it and bad, bad 16312 // thing would happen (invisible views, corrupted drawings, etc.) 16313 attachInfo.mCanvas = null; 16314 } else { 16315 // This case should hopefully never or seldom happen 16316 canvas = new Canvas(bitmap); 16317 } 16318 16319 if (clear) { 16320 bitmap.eraseColor(drawingCacheBackgroundColor); 16321 } 16322 16323 computeScroll(); 16324 final int restoreCount = canvas.save(); 16325 16326 if (autoScale && scalingRequired) { 16327 final float scale = attachInfo.mApplicationScale; 16328 canvas.scale(scale, scale); 16329 } 16330 16331 canvas.translate(-mScrollX, -mScrollY); 16332 16333 mPrivateFlags |= PFLAG_DRAWN; 16334 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16335 mLayerType != LAYER_TYPE_NONE) { 16336 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16337 } 16338 16339 // Fast path for layouts with no backgrounds 16340 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16341 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16342 dispatchDraw(canvas); 16343 if (mOverlay != null && !mOverlay.isEmpty()) { 16344 mOverlay.getOverlayView().draw(canvas); 16345 } 16346 } else { 16347 draw(canvas); 16348 } 16349 16350 canvas.restoreToCount(restoreCount); 16351 canvas.setBitmap(null); 16352 16353 if (attachInfo != null) { 16354 // Restore the cached Canvas for our siblings 16355 attachInfo.mCanvas = canvas; 16356 } 16357 } 16358 16359 /** 16360 * Create a snapshot of the view into a bitmap. We should probably make 16361 * some form of this public, but should think about the API. 16362 * 16363 * @hide 16364 */ 16365 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16366 int width = mRight - mLeft; 16367 int height = mBottom - mTop; 16368 16369 final AttachInfo attachInfo = mAttachInfo; 16370 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16371 width = (int) ((width * scale) + 0.5f); 16372 height = (int) ((height * scale) + 0.5f); 16373 16374 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16375 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16376 if (bitmap == null) { 16377 throw new OutOfMemoryError(); 16378 } 16379 16380 Resources resources = getResources(); 16381 if (resources != null) { 16382 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16383 } 16384 16385 Canvas canvas; 16386 if (attachInfo != null) { 16387 canvas = attachInfo.mCanvas; 16388 if (canvas == null) { 16389 canvas = new Canvas(); 16390 } 16391 canvas.setBitmap(bitmap); 16392 // Temporarily clobber the cached Canvas in case one of our children 16393 // is also using a drawing cache. Without this, the children would 16394 // steal the canvas by attaching their own bitmap to it and bad, bad 16395 // things would happen (invisible views, corrupted drawings, etc.) 16396 attachInfo.mCanvas = null; 16397 } else { 16398 // This case should hopefully never or seldom happen 16399 canvas = new Canvas(bitmap); 16400 } 16401 16402 if ((backgroundColor & 0xff000000) != 0) { 16403 bitmap.eraseColor(backgroundColor); 16404 } 16405 16406 computeScroll(); 16407 final int restoreCount = canvas.save(); 16408 canvas.scale(scale, scale); 16409 canvas.translate(-mScrollX, -mScrollY); 16410 16411 // Temporarily remove the dirty mask 16412 int flags = mPrivateFlags; 16413 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16414 16415 // Fast path for layouts with no backgrounds 16416 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16417 dispatchDraw(canvas); 16418 if (mOverlay != null && !mOverlay.isEmpty()) { 16419 mOverlay.getOverlayView().draw(canvas); 16420 } 16421 } else { 16422 draw(canvas); 16423 } 16424 16425 mPrivateFlags = flags; 16426 16427 canvas.restoreToCount(restoreCount); 16428 canvas.setBitmap(null); 16429 16430 if (attachInfo != null) { 16431 // Restore the cached Canvas for our siblings 16432 attachInfo.mCanvas = canvas; 16433 } 16434 16435 return bitmap; 16436 } 16437 16438 /** 16439 * Indicates whether this View is currently in edit mode. A View is usually 16440 * in edit mode when displayed within a developer tool. For instance, if 16441 * this View is being drawn by a visual user interface builder, this method 16442 * should return true. 16443 * 16444 * Subclasses should check the return value of this method to provide 16445 * different behaviors if their normal behavior might interfere with the 16446 * host environment. For instance: the class spawns a thread in its 16447 * constructor, the drawing code relies on device-specific features, etc. 16448 * 16449 * This method is usually checked in the drawing code of custom widgets. 16450 * 16451 * @return True if this View is in edit mode, false otherwise. 16452 */ 16453 public boolean isInEditMode() { 16454 return false; 16455 } 16456 16457 /** 16458 * If the View draws content inside its padding and enables fading edges, 16459 * it needs to support padding offsets. Padding offsets are added to the 16460 * fading edges to extend the length of the fade so that it covers pixels 16461 * drawn inside the padding. 16462 * 16463 * Subclasses of this class should override this method if they need 16464 * to draw content inside the padding. 16465 * 16466 * @return True if padding offset must be applied, false otherwise. 16467 * 16468 * @see #getLeftPaddingOffset() 16469 * @see #getRightPaddingOffset() 16470 * @see #getTopPaddingOffset() 16471 * @see #getBottomPaddingOffset() 16472 * 16473 * @since CURRENT 16474 */ 16475 protected boolean isPaddingOffsetRequired() { 16476 return false; 16477 } 16478 16479 /** 16480 * Amount by which to extend the left fading region. Called only when 16481 * {@link #isPaddingOffsetRequired()} returns true. 16482 * 16483 * @return The left padding offset in pixels. 16484 * 16485 * @see #isPaddingOffsetRequired() 16486 * 16487 * @since CURRENT 16488 */ 16489 protected int getLeftPaddingOffset() { 16490 return 0; 16491 } 16492 16493 /** 16494 * Amount by which to extend the right fading region. Called only when 16495 * {@link #isPaddingOffsetRequired()} returns true. 16496 * 16497 * @return The right padding offset in pixels. 16498 * 16499 * @see #isPaddingOffsetRequired() 16500 * 16501 * @since CURRENT 16502 */ 16503 protected int getRightPaddingOffset() { 16504 return 0; 16505 } 16506 16507 /** 16508 * Amount by which to extend the top fading region. Called only when 16509 * {@link #isPaddingOffsetRequired()} returns true. 16510 * 16511 * @return The top padding offset in pixels. 16512 * 16513 * @see #isPaddingOffsetRequired() 16514 * 16515 * @since CURRENT 16516 */ 16517 protected int getTopPaddingOffset() { 16518 return 0; 16519 } 16520 16521 /** 16522 * Amount by which to extend the bottom fading region. Called only when 16523 * {@link #isPaddingOffsetRequired()} returns true. 16524 * 16525 * @return The bottom padding offset in pixels. 16526 * 16527 * @see #isPaddingOffsetRequired() 16528 * 16529 * @since CURRENT 16530 */ 16531 protected int getBottomPaddingOffset() { 16532 return 0; 16533 } 16534 16535 /** 16536 * @hide 16537 * @param offsetRequired 16538 */ 16539 protected int getFadeTop(boolean offsetRequired) { 16540 int top = mPaddingTop; 16541 if (offsetRequired) top += getTopPaddingOffset(); 16542 return top; 16543 } 16544 16545 /** 16546 * @hide 16547 * @param offsetRequired 16548 */ 16549 protected int getFadeHeight(boolean offsetRequired) { 16550 int padding = mPaddingTop; 16551 if (offsetRequired) padding += getTopPaddingOffset(); 16552 return mBottom - mTop - mPaddingBottom - padding; 16553 } 16554 16555 /** 16556 * <p>Indicates whether this view is attached to a hardware accelerated 16557 * window or not.</p> 16558 * 16559 * <p>Even if this method returns true, it does not mean that every call 16560 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16561 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16562 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16563 * window is hardware accelerated, 16564 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16565 * return false, and this method will return true.</p> 16566 * 16567 * @return True if the view is attached to a window and the window is 16568 * hardware accelerated; false in any other case. 16569 */ 16570 @ViewDebug.ExportedProperty(category = "drawing") 16571 public boolean isHardwareAccelerated() { 16572 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16573 } 16574 16575 /** 16576 * Sets a rectangular area on this view to which the view will be clipped 16577 * when it is drawn. Setting the value to null will remove the clip bounds 16578 * and the view will draw normally, using its full bounds. 16579 * 16580 * @param clipBounds The rectangular area, in the local coordinates of 16581 * this view, to which future drawing operations will be clipped. 16582 */ 16583 public void setClipBounds(Rect clipBounds) { 16584 if (clipBounds == mClipBounds 16585 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16586 return; 16587 } 16588 if (clipBounds != null) { 16589 if (mClipBounds == null) { 16590 mClipBounds = new Rect(clipBounds); 16591 } else { 16592 mClipBounds.set(clipBounds); 16593 } 16594 } else { 16595 mClipBounds = null; 16596 } 16597 mRenderNode.setClipBounds(mClipBounds); 16598 invalidateViewProperty(false, false); 16599 } 16600 16601 /** 16602 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16603 * 16604 * @return A copy of the current clip bounds if clip bounds are set, 16605 * otherwise null. 16606 */ 16607 public Rect getClipBounds() { 16608 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16609 } 16610 16611 16612 /** 16613 * Populates an output rectangle with the clip bounds of the view, 16614 * returning {@code true} if successful or {@code false} if the view's 16615 * clip bounds are {@code null}. 16616 * 16617 * @param outRect rectangle in which to place the clip bounds of the view 16618 * @return {@code true} if successful or {@code false} if the view's 16619 * clip bounds are {@code null} 16620 */ 16621 public boolean getClipBounds(Rect outRect) { 16622 if (mClipBounds != null) { 16623 outRect.set(mClipBounds); 16624 return true; 16625 } 16626 return false; 16627 } 16628 16629 /** 16630 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16631 * case of an active Animation being run on the view. 16632 */ 16633 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16634 Animation a, boolean scalingRequired) { 16635 Transformation invalidationTransform; 16636 final int flags = parent.mGroupFlags; 16637 final boolean initialized = a.isInitialized(); 16638 if (!initialized) { 16639 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16640 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16641 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16642 onAnimationStart(); 16643 } 16644 16645 final Transformation t = parent.getChildTransformation(); 16646 boolean more = a.getTransformation(drawingTime, t, 1f); 16647 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16648 if (parent.mInvalidationTransformation == null) { 16649 parent.mInvalidationTransformation = new Transformation(); 16650 } 16651 invalidationTransform = parent.mInvalidationTransformation; 16652 a.getTransformation(drawingTime, invalidationTransform, 1f); 16653 } else { 16654 invalidationTransform = t; 16655 } 16656 16657 if (more) { 16658 if (!a.willChangeBounds()) { 16659 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16660 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16661 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16662 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16663 // The child need to draw an animation, potentially offscreen, so 16664 // make sure we do not cancel invalidate requests 16665 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16666 parent.invalidate(mLeft, mTop, mRight, mBottom); 16667 } 16668 } else { 16669 if (parent.mInvalidateRegion == null) { 16670 parent.mInvalidateRegion = new RectF(); 16671 } 16672 final RectF region = parent.mInvalidateRegion; 16673 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16674 invalidationTransform); 16675 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 16680 final int left = mLeft + (int) region.left; 16681 final int top = mTop + (int) region.top; 16682 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16683 top + (int) (region.height() + .5f)); 16684 } 16685 } 16686 return more; 16687 } 16688 16689 /** 16690 * This method is called by getDisplayList() when a display list is recorded for a View. 16691 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16692 */ 16693 void setDisplayListProperties(RenderNode renderNode) { 16694 if (renderNode != null) { 16695 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 16696 renderNode.setClipToBounds(mParent instanceof ViewGroup 16697 && ((ViewGroup) mParent).getClipChildren()); 16698 16699 float alpha = 1; 16700 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16701 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16702 ViewGroup parentVG = (ViewGroup) mParent; 16703 final Transformation t = parentVG.getChildTransformation(); 16704 if (parentVG.getChildStaticTransformation(this, t)) { 16705 final int transformType = t.getTransformationType(); 16706 if (transformType != Transformation.TYPE_IDENTITY) { 16707 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16708 alpha = t.getAlpha(); 16709 } 16710 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16711 renderNode.setStaticMatrix(t.getMatrix()); 16712 } 16713 } 16714 } 16715 } 16716 if (mTransformationInfo != null) { 16717 alpha *= getFinalAlpha(); 16718 if (alpha < 1) { 16719 final int multipliedAlpha = (int) (255 * alpha); 16720 if (onSetAlpha(multipliedAlpha)) { 16721 alpha = 1; 16722 } 16723 } 16724 renderNode.setAlpha(alpha); 16725 } else if (alpha < 1) { 16726 renderNode.setAlpha(alpha); 16727 } 16728 } 16729 } 16730 16731 /** 16732 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16733 * 16734 * This is where the View specializes rendering behavior based on layer type, 16735 * and hardware acceleration. 16736 */ 16737 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16738 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16739 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16740 * 16741 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16742 * HW accelerated, it can't handle drawing RenderNodes. 16743 */ 16744 boolean drawingWithRenderNode = mAttachInfo != null 16745 && mAttachInfo.mHardwareAccelerated 16746 && hardwareAcceleratedCanvas; 16747 16748 boolean more = false; 16749 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16750 final int parentFlags = parent.mGroupFlags; 16751 16752 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16753 parent.getChildTransformation().clear(); 16754 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16755 } 16756 16757 Transformation transformToApply = null; 16758 boolean concatMatrix = false; 16759 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16760 final Animation a = getAnimation(); 16761 if (a != null) { 16762 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16763 concatMatrix = a.willChangeTransformationMatrix(); 16764 if (concatMatrix) { 16765 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16766 } 16767 transformToApply = parent.getChildTransformation(); 16768 } else { 16769 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16770 // No longer animating: clear out old animation matrix 16771 mRenderNode.setAnimationMatrix(null); 16772 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16773 } 16774 if (!drawingWithRenderNode 16775 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16776 final Transformation t = parent.getChildTransformation(); 16777 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16778 if (hasTransform) { 16779 final int transformType = t.getTransformationType(); 16780 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16781 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16782 } 16783 } 16784 } 16785 16786 concatMatrix |= !childHasIdentityMatrix; 16787 16788 // Sets the flag as early as possible to allow draw() implementations 16789 // to call invalidate() successfully when doing animations 16790 mPrivateFlags |= PFLAG_DRAWN; 16791 16792 if (!concatMatrix && 16793 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16794 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16795 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16796 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16797 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16798 return more; 16799 } 16800 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16801 16802 if (hardwareAcceleratedCanvas) { 16803 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16804 // retain the flag's value temporarily in the mRecreateDisplayList flag 16805 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16806 mPrivateFlags &= ~PFLAG_INVALIDATED; 16807 } 16808 16809 RenderNode renderNode = null; 16810 Bitmap cache = null; 16811 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16812 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16813 if (layerType != LAYER_TYPE_NONE) { 16814 // If not drawing with RenderNode, treat HW layers as SW 16815 layerType = LAYER_TYPE_SOFTWARE; 16816 buildDrawingCache(true); 16817 } 16818 cache = getDrawingCache(true); 16819 } 16820 16821 if (drawingWithRenderNode) { 16822 // Delay getting the display list until animation-driven alpha values are 16823 // set up and possibly passed on to the view 16824 renderNode = updateDisplayListIfDirty(); 16825 if (!renderNode.isValid()) { 16826 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16827 // to getDisplayList(), the display list will be marked invalid and we should not 16828 // try to use it again. 16829 renderNode = null; 16830 drawingWithRenderNode = false; 16831 } 16832 } 16833 16834 int sx = 0; 16835 int sy = 0; 16836 if (!drawingWithRenderNode) { 16837 computeScroll(); 16838 sx = mScrollX; 16839 sy = mScrollY; 16840 } 16841 16842 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16843 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16844 16845 int restoreTo = -1; 16846 if (!drawingWithRenderNode || transformToApply != null) { 16847 restoreTo = canvas.save(); 16848 } 16849 if (offsetForScroll) { 16850 canvas.translate(mLeft - sx, mTop - sy); 16851 } else { 16852 if (!drawingWithRenderNode) { 16853 canvas.translate(mLeft, mTop); 16854 } 16855 if (scalingRequired) { 16856 if (drawingWithRenderNode) { 16857 // TODO: Might not need this if we put everything inside the DL 16858 restoreTo = canvas.save(); 16859 } 16860 // mAttachInfo cannot be null, otherwise scalingRequired == false 16861 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16862 canvas.scale(scale, scale); 16863 } 16864 } 16865 16866 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16867 if (transformToApply != null 16868 || alpha < 1 16869 || !hasIdentityMatrix() 16870 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16871 if (transformToApply != null || !childHasIdentityMatrix) { 16872 int transX = 0; 16873 int transY = 0; 16874 16875 if (offsetForScroll) { 16876 transX = -sx; 16877 transY = -sy; 16878 } 16879 16880 if (transformToApply != null) { 16881 if (concatMatrix) { 16882 if (drawingWithRenderNode) { 16883 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16884 } else { 16885 // Undo the scroll translation, apply the transformation matrix, 16886 // then redo the scroll translate to get the correct result. 16887 canvas.translate(-transX, -transY); 16888 canvas.concat(transformToApply.getMatrix()); 16889 canvas.translate(transX, transY); 16890 } 16891 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16892 } 16893 16894 float transformAlpha = transformToApply.getAlpha(); 16895 if (transformAlpha < 1) { 16896 alpha *= transformAlpha; 16897 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16898 } 16899 } 16900 16901 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16902 canvas.translate(-transX, -transY); 16903 canvas.concat(getMatrix()); 16904 canvas.translate(transX, transY); 16905 } 16906 } 16907 16908 // Deal with alpha if it is or used to be <1 16909 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16910 if (alpha < 1) { 16911 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16912 } else { 16913 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16914 } 16915 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16916 if (!drawingWithDrawingCache) { 16917 final int multipliedAlpha = (int) (255 * alpha); 16918 if (!onSetAlpha(multipliedAlpha)) { 16919 if (drawingWithRenderNode) { 16920 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16921 } else if (layerType == LAYER_TYPE_NONE) { 16922 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16923 multipliedAlpha); 16924 } 16925 } else { 16926 // Alpha is handled by the child directly, clobber the layer's alpha 16927 mPrivateFlags |= PFLAG_ALPHA_SET; 16928 } 16929 } 16930 } 16931 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16932 onSetAlpha(255); 16933 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16934 } 16935 16936 if (!drawingWithRenderNode) { 16937 // apply clips directly, since RenderNode won't do it for this draw 16938 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16939 if (offsetForScroll) { 16940 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16941 } else { 16942 if (!scalingRequired || cache == null) { 16943 canvas.clipRect(0, 0, getWidth(), getHeight()); 16944 } else { 16945 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16946 } 16947 } 16948 } 16949 16950 if (mClipBounds != null) { 16951 // clip bounds ignore scroll 16952 canvas.clipRect(mClipBounds); 16953 } 16954 } 16955 16956 if (!drawingWithDrawingCache) { 16957 if (drawingWithRenderNode) { 16958 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16959 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16960 } else { 16961 // Fast path for layouts with no backgrounds 16962 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16963 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16964 dispatchDraw(canvas); 16965 } else { 16966 draw(canvas); 16967 } 16968 } 16969 } else if (cache != null) { 16970 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16971 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 16972 // no layer paint, use temporary paint to draw bitmap 16973 Paint cachePaint = parent.mCachePaint; 16974 if (cachePaint == null) { 16975 cachePaint = new Paint(); 16976 cachePaint.setDither(false); 16977 parent.mCachePaint = cachePaint; 16978 } 16979 cachePaint.setAlpha((int) (alpha * 255)); 16980 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16981 } else { 16982 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16983 int layerPaintAlpha = mLayerPaint.getAlpha(); 16984 if (alpha < 1) { 16985 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 16986 } 16987 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 16988 if (alpha < 1) { 16989 mLayerPaint.setAlpha(layerPaintAlpha); 16990 } 16991 } 16992 } 16993 16994 if (restoreTo >= 0) { 16995 canvas.restoreToCount(restoreTo); 16996 } 16997 16998 if (a != null && !more) { 16999 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 17000 onSetAlpha(255); 17001 } 17002 parent.finishAnimatingView(this, a); 17003 } 17004 17005 if (more && hardwareAcceleratedCanvas) { 17006 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 17007 // alpha animations should cause the child to recreate its display list 17008 invalidate(true); 17009 } 17010 } 17011 17012 mRecreateDisplayList = false; 17013 17014 return more; 17015 } 17016 17017 /** 17018 * Manually render this view (and all of its children) to the given Canvas. 17019 * The view must have already done a full layout before this function is 17020 * called. When implementing a view, implement 17021 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 17022 * If you do need to override this method, call the superclass version. 17023 * 17024 * @param canvas The Canvas to which the View is rendered. 17025 */ 17026 @CallSuper 17027 public void draw(Canvas canvas) { 17028 final int privateFlags = mPrivateFlags; 17029 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 17030 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 17031 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 17032 17033 /* 17034 * Draw traversal performs several drawing steps which must be executed 17035 * in the appropriate order: 17036 * 17037 * 1. Draw the background 17038 * 2. If necessary, save the canvas' layers to prepare for fading 17039 * 3. Draw view's content 17040 * 4. Draw children 17041 * 5. If necessary, draw the fading edges and restore layers 17042 * 6. Draw decorations (scrollbars for instance) 17043 */ 17044 17045 // Step 1, draw the background, if needed 17046 int saveCount; 17047 17048 if (!dirtyOpaque) { 17049 drawBackground(canvas); 17050 } 17051 17052 // skip step 2 & 5 if possible (common case) 17053 final int viewFlags = mViewFlags; 17054 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 17055 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 17056 if (!verticalEdges && !horizontalEdges) { 17057 // Step 3, draw the content 17058 if (!dirtyOpaque) onDraw(canvas); 17059 17060 // Step 4, draw the children 17061 dispatchDraw(canvas); 17062 17063 // Overlay is part of the content and draws beneath Foreground 17064 if (mOverlay != null && !mOverlay.isEmpty()) { 17065 mOverlay.getOverlayView().dispatchDraw(canvas); 17066 } 17067 17068 // Step 6, draw decorations (foreground, scrollbars) 17069 onDrawForeground(canvas); 17070 17071 // we're done... 17072 return; 17073 } 17074 17075 /* 17076 * Here we do the full fledged routine... 17077 * (this is an uncommon case where speed matters less, 17078 * this is why we repeat some of the tests that have been 17079 * done above) 17080 */ 17081 17082 boolean drawTop = false; 17083 boolean drawBottom = false; 17084 boolean drawLeft = false; 17085 boolean drawRight = false; 17086 17087 float topFadeStrength = 0.0f; 17088 float bottomFadeStrength = 0.0f; 17089 float leftFadeStrength = 0.0f; 17090 float rightFadeStrength = 0.0f; 17091 17092 // Step 2, save the canvas' layers 17093 int paddingLeft = mPaddingLeft; 17094 17095 final boolean offsetRequired = isPaddingOffsetRequired(); 17096 if (offsetRequired) { 17097 paddingLeft += getLeftPaddingOffset(); 17098 } 17099 17100 int left = mScrollX + paddingLeft; 17101 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 17102 int top = mScrollY + getFadeTop(offsetRequired); 17103 int bottom = top + getFadeHeight(offsetRequired); 17104 17105 if (offsetRequired) { 17106 right += getRightPaddingOffset(); 17107 bottom += getBottomPaddingOffset(); 17108 } 17109 17110 final ScrollabilityCache scrollabilityCache = mScrollCache; 17111 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 17112 int length = (int) fadeHeight; 17113 17114 // clip the fade length if top and bottom fades overlap 17115 // overlapping fades produce odd-looking artifacts 17116 if (verticalEdges && (top + length > bottom - length)) { 17117 length = (bottom - top) / 2; 17118 } 17119 17120 // also clip horizontal fades if necessary 17121 if (horizontalEdges && (left + length > right - length)) { 17122 length = (right - left) / 2; 17123 } 17124 17125 if (verticalEdges) { 17126 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 17127 drawTop = topFadeStrength * fadeHeight > 1.0f; 17128 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 17129 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 17130 } 17131 17132 if (horizontalEdges) { 17133 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 17134 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 17135 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 17136 drawRight = rightFadeStrength * fadeHeight > 1.0f; 17137 } 17138 17139 saveCount = canvas.getSaveCount(); 17140 17141 int solidColor = getSolidColor(); 17142 if (solidColor == 0) { 17143 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 17144 17145 if (drawTop) { 17146 canvas.saveLayer(left, top, right, top + length, null, flags); 17147 } 17148 17149 if (drawBottom) { 17150 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 17151 } 17152 17153 if (drawLeft) { 17154 canvas.saveLayer(left, top, left + length, bottom, null, flags); 17155 } 17156 17157 if (drawRight) { 17158 canvas.saveLayer(right - length, top, right, bottom, null, flags); 17159 } 17160 } else { 17161 scrollabilityCache.setFadeColor(solidColor); 17162 } 17163 17164 // Step 3, draw the content 17165 if (!dirtyOpaque) onDraw(canvas); 17166 17167 // Step 4, draw the children 17168 dispatchDraw(canvas); 17169 17170 // Step 5, draw the fade effect and restore layers 17171 final Paint p = scrollabilityCache.paint; 17172 final Matrix matrix = scrollabilityCache.matrix; 17173 final Shader fade = scrollabilityCache.shader; 17174 17175 if (drawTop) { 17176 matrix.setScale(1, fadeHeight * topFadeStrength); 17177 matrix.postTranslate(left, top); 17178 fade.setLocalMatrix(matrix); 17179 p.setShader(fade); 17180 canvas.drawRect(left, top, right, top + length, p); 17181 } 17182 17183 if (drawBottom) { 17184 matrix.setScale(1, fadeHeight * bottomFadeStrength); 17185 matrix.postRotate(180); 17186 matrix.postTranslate(left, bottom); 17187 fade.setLocalMatrix(matrix); 17188 p.setShader(fade); 17189 canvas.drawRect(left, bottom - length, right, bottom, p); 17190 } 17191 17192 if (drawLeft) { 17193 matrix.setScale(1, fadeHeight * leftFadeStrength); 17194 matrix.postRotate(-90); 17195 matrix.postTranslate(left, top); 17196 fade.setLocalMatrix(matrix); 17197 p.setShader(fade); 17198 canvas.drawRect(left, top, left + length, bottom, p); 17199 } 17200 17201 if (drawRight) { 17202 matrix.setScale(1, fadeHeight * rightFadeStrength); 17203 matrix.postRotate(90); 17204 matrix.postTranslate(right, top); 17205 fade.setLocalMatrix(matrix); 17206 p.setShader(fade); 17207 canvas.drawRect(right - length, top, right, bottom, p); 17208 } 17209 17210 canvas.restoreToCount(saveCount); 17211 17212 // Overlay is part of the content and draws beneath Foreground 17213 if (mOverlay != null && !mOverlay.isEmpty()) { 17214 mOverlay.getOverlayView().dispatchDraw(canvas); 17215 } 17216 17217 // Step 6, draw decorations (foreground, scrollbars) 17218 onDrawForeground(canvas); 17219 } 17220 17221 /** 17222 * Draws the background onto the specified canvas. 17223 * 17224 * @param canvas Canvas on which to draw the background 17225 */ 17226 private void drawBackground(Canvas canvas) { 17227 final Drawable background = mBackground; 17228 if (background == null) { 17229 return; 17230 } 17231 17232 setBackgroundBounds(); 17233 17234 // Attempt to use a display list if requested. 17235 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17236 && mAttachInfo.mHardwareRenderer != null) { 17237 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17238 17239 final RenderNode renderNode = mBackgroundRenderNode; 17240 if (renderNode != null && renderNode.isValid()) { 17241 setBackgroundRenderNodeProperties(renderNode); 17242 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17243 return; 17244 } 17245 } 17246 17247 final int scrollX = mScrollX; 17248 final int scrollY = mScrollY; 17249 if ((scrollX | scrollY) == 0) { 17250 background.draw(canvas); 17251 } else { 17252 canvas.translate(scrollX, scrollY); 17253 background.draw(canvas); 17254 canvas.translate(-scrollX, -scrollY); 17255 } 17256 } 17257 17258 /** 17259 * Sets the correct background bounds and rebuilds the outline, if needed. 17260 * <p/> 17261 * This is called by LayoutLib. 17262 */ 17263 void setBackgroundBounds() { 17264 if (mBackgroundSizeChanged && mBackground != null) { 17265 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17266 mBackgroundSizeChanged = false; 17267 rebuildOutline(); 17268 } 17269 } 17270 17271 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17272 renderNode.setTranslationX(mScrollX); 17273 renderNode.setTranslationY(mScrollY); 17274 } 17275 17276 /** 17277 * Creates a new display list or updates the existing display list for the 17278 * specified Drawable. 17279 * 17280 * @param drawable Drawable for which to create a display list 17281 * @param renderNode Existing RenderNode, or {@code null} 17282 * @return A valid display list for the specified drawable 17283 */ 17284 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17285 if (renderNode == null) { 17286 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17287 } 17288 17289 final Rect bounds = drawable.getBounds(); 17290 final int width = bounds.width(); 17291 final int height = bounds.height(); 17292 final DisplayListCanvas canvas = renderNode.start(width, height); 17293 17294 // Reverse left/top translation done by drawable canvas, which will 17295 // instead be applied by rendernode's LTRB bounds below. This way, the 17296 // drawable's bounds match with its rendernode bounds and its content 17297 // will lie within those bounds in the rendernode tree. 17298 canvas.translate(-bounds.left, -bounds.top); 17299 17300 try { 17301 drawable.draw(canvas); 17302 } finally { 17303 renderNode.end(canvas); 17304 } 17305 17306 // Set up drawable properties that are view-independent. 17307 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17308 renderNode.setProjectBackwards(drawable.isProjected()); 17309 renderNode.setProjectionReceiver(true); 17310 renderNode.setClipToBounds(false); 17311 return renderNode; 17312 } 17313 17314 /** 17315 * Returns the overlay for this view, creating it if it does not yet exist. 17316 * Adding drawables to the overlay will cause them to be displayed whenever 17317 * the view itself is redrawn. Objects in the overlay should be actively 17318 * managed: remove them when they should not be displayed anymore. The 17319 * overlay will always have the same size as its host view. 17320 * 17321 * <p>Note: Overlays do not currently work correctly with {@link 17322 * SurfaceView} or {@link TextureView}; contents in overlays for these 17323 * types of views may not display correctly.</p> 17324 * 17325 * @return The ViewOverlay object for this view. 17326 * @see ViewOverlay 17327 */ 17328 public ViewOverlay getOverlay() { 17329 if (mOverlay == null) { 17330 mOverlay = new ViewOverlay(mContext, this); 17331 } 17332 return mOverlay; 17333 } 17334 17335 /** 17336 * Override this if your view is known to always be drawn on top of a solid color background, 17337 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17338 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17339 * should be set to 0xFF. 17340 * 17341 * @see #setVerticalFadingEdgeEnabled(boolean) 17342 * @see #setHorizontalFadingEdgeEnabled(boolean) 17343 * 17344 * @return The known solid color background for this view, or 0 if the color may vary 17345 */ 17346 @ViewDebug.ExportedProperty(category = "drawing") 17347 @ColorInt 17348 public int getSolidColor() { 17349 return 0; 17350 } 17351 17352 /** 17353 * Build a human readable string representation of the specified view flags. 17354 * 17355 * @param flags the view flags to convert to a string 17356 * @return a String representing the supplied flags 17357 */ 17358 private static String printFlags(int flags) { 17359 String output = ""; 17360 int numFlags = 0; 17361 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17362 output += "TAKES_FOCUS"; 17363 numFlags++; 17364 } 17365 17366 switch (flags & VISIBILITY_MASK) { 17367 case INVISIBLE: 17368 if (numFlags > 0) { 17369 output += " "; 17370 } 17371 output += "INVISIBLE"; 17372 // USELESS HERE numFlags++; 17373 break; 17374 case GONE: 17375 if (numFlags > 0) { 17376 output += " "; 17377 } 17378 output += "GONE"; 17379 // USELESS HERE numFlags++; 17380 break; 17381 default: 17382 break; 17383 } 17384 return output; 17385 } 17386 17387 /** 17388 * Build a human readable string representation of the specified private 17389 * view flags. 17390 * 17391 * @param privateFlags the private view flags to convert to a string 17392 * @return a String representing the supplied flags 17393 */ 17394 private static String printPrivateFlags(int privateFlags) { 17395 String output = ""; 17396 int numFlags = 0; 17397 17398 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17399 output += "WANTS_FOCUS"; 17400 numFlags++; 17401 } 17402 17403 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17404 if (numFlags > 0) { 17405 output += " "; 17406 } 17407 output += "FOCUSED"; 17408 numFlags++; 17409 } 17410 17411 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17412 if (numFlags > 0) { 17413 output += " "; 17414 } 17415 output += "SELECTED"; 17416 numFlags++; 17417 } 17418 17419 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17420 if (numFlags > 0) { 17421 output += " "; 17422 } 17423 output += "IS_ROOT_NAMESPACE"; 17424 numFlags++; 17425 } 17426 17427 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17428 if (numFlags > 0) { 17429 output += " "; 17430 } 17431 output += "HAS_BOUNDS"; 17432 numFlags++; 17433 } 17434 17435 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17436 if (numFlags > 0) { 17437 output += " "; 17438 } 17439 output += "DRAWN"; 17440 // USELESS HERE numFlags++; 17441 } 17442 return output; 17443 } 17444 17445 /** 17446 * <p>Indicates whether or not this view's layout will be requested during 17447 * the next hierarchy layout pass.</p> 17448 * 17449 * @return true if the layout will be forced during next layout pass 17450 */ 17451 public boolean isLayoutRequested() { 17452 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17453 } 17454 17455 /** 17456 * Return true if o is a ViewGroup that is laying out using optical bounds. 17457 * @hide 17458 */ 17459 public static boolean isLayoutModeOptical(Object o) { 17460 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17461 } 17462 17463 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17464 Insets parentInsets = mParent instanceof View ? 17465 ((View) mParent).getOpticalInsets() : Insets.NONE; 17466 Insets childInsets = getOpticalInsets(); 17467 return setFrame( 17468 left + parentInsets.left - childInsets.left, 17469 top + parentInsets.top - childInsets.top, 17470 right + parentInsets.left + childInsets.right, 17471 bottom + parentInsets.top + childInsets.bottom); 17472 } 17473 17474 /** 17475 * Assign a size and position to a view and all of its 17476 * descendants 17477 * 17478 * <p>This is the second phase of the layout mechanism. 17479 * (The first is measuring). In this phase, each parent calls 17480 * layout on all of its children to position them. 17481 * This is typically done using the child measurements 17482 * that were stored in the measure pass().</p> 17483 * 17484 * <p>Derived classes should not override this method. 17485 * Derived classes with children should override 17486 * onLayout. In that method, they should 17487 * call layout on each of their children.</p> 17488 * 17489 * @param l Left position, relative to parent 17490 * @param t Top position, relative to parent 17491 * @param r Right position, relative to parent 17492 * @param b Bottom position, relative to parent 17493 */ 17494 @SuppressWarnings({"unchecked"}) 17495 public void layout(int l, int t, int r, int b) { 17496 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17497 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17498 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17499 } 17500 17501 int oldL = mLeft; 17502 int oldT = mTop; 17503 int oldB = mBottom; 17504 int oldR = mRight; 17505 17506 boolean changed = isLayoutModeOptical(mParent) ? 17507 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17508 17509 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17510 onLayout(changed, l, t, r, b); 17511 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17512 17513 ListenerInfo li = mListenerInfo; 17514 if (li != null && li.mOnLayoutChangeListeners != null) { 17515 ArrayList<OnLayoutChangeListener> listenersCopy = 17516 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17517 int numListeners = listenersCopy.size(); 17518 for (int i = 0; i < numListeners; ++i) { 17519 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17520 } 17521 } 17522 } 17523 17524 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17525 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17526 } 17527 17528 /** 17529 * Called from layout when this view should 17530 * assign a size and position to each of its children. 17531 * 17532 * Derived classes with children should override 17533 * this method and call layout on each of 17534 * their children. 17535 * @param changed This is a new size or position for this view 17536 * @param left Left position, relative to parent 17537 * @param top Top position, relative to parent 17538 * @param right Right position, relative to parent 17539 * @param bottom Bottom position, relative to parent 17540 */ 17541 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17542 } 17543 17544 /** 17545 * Assign a size and position to this view. 17546 * 17547 * This is called from layout. 17548 * 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 * @return true if the new size and position are different than the 17554 * previous ones 17555 * {@hide} 17556 */ 17557 protected boolean setFrame(int left, int top, int right, int bottom) { 17558 boolean changed = false; 17559 17560 if (DBG) { 17561 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17562 + right + "," + bottom + ")"); 17563 } 17564 17565 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17566 changed = true; 17567 17568 // Remember our drawn bit 17569 int drawn = mPrivateFlags & PFLAG_DRAWN; 17570 17571 int oldWidth = mRight - mLeft; 17572 int oldHeight = mBottom - mTop; 17573 int newWidth = right - left; 17574 int newHeight = bottom - top; 17575 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17576 17577 // Invalidate our old position 17578 invalidate(sizeChanged); 17579 17580 mLeft = left; 17581 mTop = top; 17582 mRight = right; 17583 mBottom = bottom; 17584 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17585 17586 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17587 17588 17589 if (sizeChanged) { 17590 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17591 } 17592 17593 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17594 // If we are visible, force the DRAWN bit to on so that 17595 // this invalidate will go through (at least to our parent). 17596 // This is because someone may have invalidated this view 17597 // before this call to setFrame came in, thereby clearing 17598 // the DRAWN bit. 17599 mPrivateFlags |= PFLAG_DRAWN; 17600 invalidate(sizeChanged); 17601 // parent display list may need to be recreated based on a change in the bounds 17602 // of any child 17603 invalidateParentCaches(); 17604 } 17605 17606 // Reset drawn bit to original value (invalidate turns it off) 17607 mPrivateFlags |= drawn; 17608 17609 mBackgroundSizeChanged = true; 17610 if (mForegroundInfo != null) { 17611 mForegroundInfo.mBoundsChanged = true; 17612 } 17613 17614 notifySubtreeAccessibilityStateChangedIfNeeded(); 17615 } 17616 return changed; 17617 } 17618 17619 /** 17620 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17621 * @hide 17622 */ 17623 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17624 setFrame(left, top, right, bottom); 17625 } 17626 17627 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17628 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17629 if (mOverlay != null) { 17630 mOverlay.getOverlayView().setRight(newWidth); 17631 mOverlay.getOverlayView().setBottom(newHeight); 17632 } 17633 rebuildOutline(); 17634 } 17635 17636 /** 17637 * Finalize inflating a view from XML. This is called as the last phase 17638 * of inflation, after all child views have been added. 17639 * 17640 * <p>Even if the subclass overrides onFinishInflate, they should always be 17641 * sure to call the super method, so that we get called. 17642 */ 17643 @CallSuper 17644 protected void onFinishInflate() { 17645 } 17646 17647 /** 17648 * Returns the resources associated with this view. 17649 * 17650 * @return Resources object. 17651 */ 17652 public Resources getResources() { 17653 return mResources; 17654 } 17655 17656 /** 17657 * Invalidates the specified Drawable. 17658 * 17659 * @param drawable the drawable to invalidate 17660 */ 17661 @Override 17662 public void invalidateDrawable(@NonNull Drawable drawable) { 17663 if (verifyDrawable(drawable)) { 17664 final Rect dirty = drawable.getDirtyBounds(); 17665 final int scrollX = mScrollX; 17666 final int scrollY = mScrollY; 17667 17668 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17669 dirty.right + scrollX, dirty.bottom + scrollY); 17670 rebuildOutline(); 17671 } 17672 } 17673 17674 /** 17675 * Schedules an action on a drawable to occur at a specified time. 17676 * 17677 * @param who the recipient of the action 17678 * @param what the action to run on the drawable 17679 * @param when the time at which the action must occur. Uses the 17680 * {@link SystemClock#uptimeMillis} timebase. 17681 */ 17682 @Override 17683 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 17684 if (verifyDrawable(who) && what != null) { 17685 final long delay = when - SystemClock.uptimeMillis(); 17686 if (mAttachInfo != null) { 17687 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17688 Choreographer.CALLBACK_ANIMATION, what, who, 17689 Choreographer.subtractFrameDelay(delay)); 17690 } else { 17691 // Postpone the runnable until we know 17692 // on which thread it needs to run. 17693 getRunQueue().postDelayed(what, delay); 17694 } 17695 } 17696 } 17697 17698 /** 17699 * Cancels a scheduled action on a drawable. 17700 * 17701 * @param who the recipient of the action 17702 * @param what the action to cancel 17703 */ 17704 @Override 17705 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 17706 if (verifyDrawable(who) && what != null) { 17707 if (mAttachInfo != null) { 17708 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17709 Choreographer.CALLBACK_ANIMATION, what, who); 17710 } 17711 getRunQueue().removeCallbacks(what); 17712 } 17713 } 17714 17715 /** 17716 * Unschedule any events associated with the given Drawable. This can be 17717 * used when selecting a new Drawable into a view, so that the previous 17718 * one is completely unscheduled. 17719 * 17720 * @param who The Drawable to unschedule. 17721 * 17722 * @see #drawableStateChanged 17723 */ 17724 public void unscheduleDrawable(Drawable who) { 17725 if (mAttachInfo != null && who != null) { 17726 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17727 Choreographer.CALLBACK_ANIMATION, null, who); 17728 } 17729 } 17730 17731 /** 17732 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17733 * that the View directionality can and will be resolved before its Drawables. 17734 * 17735 * Will call {@link View#onResolveDrawables} when resolution is done. 17736 * 17737 * @hide 17738 */ 17739 protected void resolveDrawables() { 17740 // Drawables resolution may need to happen before resolving the layout direction (which is 17741 // done only during the measure() call). 17742 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17743 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17744 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17745 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17746 // direction to be resolved as its resolved value will be the same as its raw value. 17747 if (!isLayoutDirectionResolved() && 17748 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17749 return; 17750 } 17751 17752 final int layoutDirection = isLayoutDirectionResolved() ? 17753 getLayoutDirection() : getRawLayoutDirection(); 17754 17755 if (mBackground != null) { 17756 mBackground.setLayoutDirection(layoutDirection); 17757 } 17758 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17759 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17760 } 17761 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17762 onResolveDrawables(layoutDirection); 17763 } 17764 17765 boolean areDrawablesResolved() { 17766 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17767 } 17768 17769 /** 17770 * Called when layout direction has been resolved. 17771 * 17772 * The default implementation does nothing. 17773 * 17774 * @param layoutDirection The resolved layout direction. 17775 * 17776 * @see #LAYOUT_DIRECTION_LTR 17777 * @see #LAYOUT_DIRECTION_RTL 17778 * 17779 * @hide 17780 */ 17781 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17782 } 17783 17784 /** 17785 * @hide 17786 */ 17787 protected void resetResolvedDrawables() { 17788 resetResolvedDrawablesInternal(); 17789 } 17790 17791 void resetResolvedDrawablesInternal() { 17792 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17793 } 17794 17795 /** 17796 * If your view subclass is displaying its own Drawable objects, it should 17797 * override this function and return true for any Drawable it is 17798 * displaying. This allows animations for those drawables to be 17799 * scheduled. 17800 * 17801 * <p>Be sure to call through to the super class when overriding this 17802 * function. 17803 * 17804 * @param who The Drawable to verify. Return true if it is one you are 17805 * displaying, else return the result of calling through to the 17806 * super class. 17807 * 17808 * @return boolean If true than the Drawable is being displayed in the 17809 * view; else false and it is not allowed to animate. 17810 * 17811 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17812 * @see #drawableStateChanged() 17813 */ 17814 @CallSuper 17815 protected boolean verifyDrawable(@NonNull Drawable who) { 17816 // Avoid verifying the scroll bar drawable so that we don't end up in 17817 // an invalidation loop. This effectively prevents the scroll bar 17818 // drawable from triggering invalidations and scheduling runnables. 17819 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17820 } 17821 17822 /** 17823 * This function is called whenever the state of the view changes in such 17824 * a way that it impacts the state of drawables being shown. 17825 * <p> 17826 * If the View has a StateListAnimator, it will also be called to run necessary state 17827 * change animations. 17828 * <p> 17829 * Be sure to call through to the superclass when overriding this function. 17830 * 17831 * @see Drawable#setState(int[]) 17832 */ 17833 @CallSuper 17834 protected void drawableStateChanged() { 17835 final int[] state = getDrawableState(); 17836 boolean changed = false; 17837 17838 final Drawable bg = mBackground; 17839 if (bg != null && bg.isStateful()) { 17840 changed |= bg.setState(state); 17841 } 17842 17843 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17844 if (fg != null && fg.isStateful()) { 17845 changed |= fg.setState(state); 17846 } 17847 17848 if (mScrollCache != null) { 17849 final Drawable scrollBar = mScrollCache.scrollBar; 17850 if (scrollBar != null && scrollBar.isStateful()) { 17851 changed |= scrollBar.setState(state) 17852 && mScrollCache.state != ScrollabilityCache.OFF; 17853 } 17854 } 17855 17856 if (mStateListAnimator != null) { 17857 mStateListAnimator.setState(state); 17858 } 17859 17860 if (changed) { 17861 invalidate(); 17862 } 17863 } 17864 17865 /** 17866 * This function is called whenever the view hotspot changes and needs to 17867 * be propagated to drawables or child views managed by the view. 17868 * <p> 17869 * Dispatching to child views is handled by 17870 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17871 * <p> 17872 * Be sure to call through to the superclass when overriding this function. 17873 * 17874 * @param x hotspot x coordinate 17875 * @param y hotspot y coordinate 17876 */ 17877 @CallSuper 17878 public void drawableHotspotChanged(float x, float y) { 17879 if (mBackground != null) { 17880 mBackground.setHotspot(x, y); 17881 } 17882 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17883 mForegroundInfo.mDrawable.setHotspot(x, y); 17884 } 17885 17886 dispatchDrawableHotspotChanged(x, y); 17887 } 17888 17889 /** 17890 * Dispatches drawableHotspotChanged to all of this View's children. 17891 * 17892 * @param x hotspot x coordinate 17893 * @param y hotspot y coordinate 17894 * @see #drawableHotspotChanged(float, float) 17895 */ 17896 public void dispatchDrawableHotspotChanged(float x, float y) { 17897 } 17898 17899 /** 17900 * Call this to force a view to update its drawable state. This will cause 17901 * drawableStateChanged to be called on this view. Views that are interested 17902 * in the new state should call getDrawableState. 17903 * 17904 * @see #drawableStateChanged 17905 * @see #getDrawableState 17906 */ 17907 public void refreshDrawableState() { 17908 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17909 drawableStateChanged(); 17910 17911 ViewParent parent = mParent; 17912 if (parent != null) { 17913 parent.childDrawableStateChanged(this); 17914 } 17915 } 17916 17917 /** 17918 * Return an array of resource IDs of the drawable states representing the 17919 * current state of the view. 17920 * 17921 * @return The current drawable state 17922 * 17923 * @see Drawable#setState(int[]) 17924 * @see #drawableStateChanged() 17925 * @see #onCreateDrawableState(int) 17926 */ 17927 public final int[] getDrawableState() { 17928 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17929 return mDrawableState; 17930 } else { 17931 mDrawableState = onCreateDrawableState(0); 17932 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17933 return mDrawableState; 17934 } 17935 } 17936 17937 /** 17938 * Generate the new {@link android.graphics.drawable.Drawable} state for 17939 * this view. This is called by the view 17940 * system when the cached Drawable state is determined to be invalid. To 17941 * retrieve the current state, you should use {@link #getDrawableState}. 17942 * 17943 * @param extraSpace if non-zero, this is the number of extra entries you 17944 * would like in the returned array in which you can place your own 17945 * states. 17946 * 17947 * @return Returns an array holding the current {@link Drawable} state of 17948 * the view. 17949 * 17950 * @see #mergeDrawableStates(int[], int[]) 17951 */ 17952 protected int[] onCreateDrawableState(int extraSpace) { 17953 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17954 mParent instanceof View) { 17955 return ((View) mParent).onCreateDrawableState(extraSpace); 17956 } 17957 17958 int[] drawableState; 17959 17960 int privateFlags = mPrivateFlags; 17961 17962 int viewStateIndex = 0; 17963 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17964 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17965 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17966 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17967 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17968 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17969 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17970 ThreadedRenderer.isAvailable()) { 17971 // This is set if HW acceleration is requested, even if the current 17972 // process doesn't allow it. This is just to allow app preview 17973 // windows to better match their app. 17974 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17975 } 17976 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17977 17978 final int privateFlags2 = mPrivateFlags2; 17979 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17980 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17981 } 17982 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17983 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17984 } 17985 17986 drawableState = StateSet.get(viewStateIndex); 17987 17988 //noinspection ConstantIfStatement 17989 if (false) { 17990 Log.i("View", "drawableStateIndex=" + viewStateIndex); 17991 Log.i("View", toString() 17992 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 17993 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 17994 + " fo=" + hasFocus() 17995 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 17996 + " wf=" + hasWindowFocus() 17997 + ": " + Arrays.toString(drawableState)); 17998 } 17999 18000 if (extraSpace == 0) { 18001 return drawableState; 18002 } 18003 18004 final int[] fullState; 18005 if (drawableState != null) { 18006 fullState = new int[drawableState.length + extraSpace]; 18007 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 18008 } else { 18009 fullState = new int[extraSpace]; 18010 } 18011 18012 return fullState; 18013 } 18014 18015 /** 18016 * Merge your own state values in <var>additionalState</var> into the base 18017 * state values <var>baseState</var> that were returned by 18018 * {@link #onCreateDrawableState(int)}. 18019 * 18020 * @param baseState The base state values returned by 18021 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 18022 * own additional state values. 18023 * 18024 * @param additionalState The additional state values you would like 18025 * added to <var>baseState</var>; this array is not modified. 18026 * 18027 * @return As a convenience, the <var>baseState</var> array you originally 18028 * passed into the function is returned. 18029 * 18030 * @see #onCreateDrawableState(int) 18031 */ 18032 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 18033 final int N = baseState.length; 18034 int i = N - 1; 18035 while (i >= 0 && baseState[i] == 0) { 18036 i--; 18037 } 18038 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 18039 return baseState; 18040 } 18041 18042 /** 18043 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 18044 * on all Drawable objects associated with this view. 18045 * <p> 18046 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 18047 * attached to this view. 18048 */ 18049 @CallSuper 18050 public void jumpDrawablesToCurrentState() { 18051 if (mBackground != null) { 18052 mBackground.jumpToCurrentState(); 18053 } 18054 if (mStateListAnimator != null) { 18055 mStateListAnimator.jumpToCurrentState(); 18056 } 18057 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 18058 mForegroundInfo.mDrawable.jumpToCurrentState(); 18059 } 18060 } 18061 18062 /** 18063 * Sets the background color for this view. 18064 * @param color the color of the background 18065 */ 18066 @RemotableViewMethod 18067 public void setBackgroundColor(@ColorInt int color) { 18068 if (mBackground instanceof ColorDrawable) { 18069 ((ColorDrawable) mBackground.mutate()).setColor(color); 18070 computeOpaqueFlags(); 18071 mBackgroundResource = 0; 18072 } else { 18073 setBackground(new ColorDrawable(color)); 18074 } 18075 } 18076 18077 /** 18078 * Set the background to a given resource. The resource should refer to 18079 * a Drawable object or 0 to remove the background. 18080 * @param resid The identifier of the resource. 18081 * 18082 * @attr ref android.R.styleable#View_background 18083 */ 18084 @RemotableViewMethod 18085 public void setBackgroundResource(@DrawableRes int resid) { 18086 if (resid != 0 && resid == mBackgroundResource) { 18087 return; 18088 } 18089 18090 Drawable d = null; 18091 if (resid != 0) { 18092 d = mContext.getDrawable(resid); 18093 } 18094 setBackground(d); 18095 18096 mBackgroundResource = resid; 18097 } 18098 18099 /** 18100 * Set the background to a given Drawable, or remove the background. If the 18101 * background has padding, this View's padding is set to the background's 18102 * padding. However, when a background is removed, this View's padding isn't 18103 * touched. If setting the padding is desired, please use 18104 * {@link #setPadding(int, int, int, int)}. 18105 * 18106 * @param background The Drawable to use as the background, or null to remove the 18107 * background 18108 */ 18109 public void setBackground(Drawable background) { 18110 //noinspection deprecation 18111 setBackgroundDrawable(background); 18112 } 18113 18114 /** 18115 * @deprecated use {@link #setBackground(Drawable)} instead 18116 */ 18117 @Deprecated 18118 public void setBackgroundDrawable(Drawable background) { 18119 computeOpaqueFlags(); 18120 18121 if (background == mBackground) { 18122 return; 18123 } 18124 18125 boolean requestLayout = false; 18126 18127 mBackgroundResource = 0; 18128 18129 /* 18130 * Regardless of whether we're setting a new background or not, we want 18131 * to clear the previous drawable. setVisible first while we still have the callback set. 18132 */ 18133 if (mBackground != null) { 18134 if (isAttachedToWindow()) { 18135 mBackground.setVisible(false, false); 18136 } 18137 mBackground.setCallback(null); 18138 unscheduleDrawable(mBackground); 18139 } 18140 18141 if (background != null) { 18142 Rect padding = sThreadLocal.get(); 18143 if (padding == null) { 18144 padding = new Rect(); 18145 sThreadLocal.set(padding); 18146 } 18147 resetResolvedDrawablesInternal(); 18148 background.setLayoutDirection(getLayoutDirection()); 18149 if (background.getPadding(padding)) { 18150 resetResolvedPaddingInternal(); 18151 switch (background.getLayoutDirection()) { 18152 case LAYOUT_DIRECTION_RTL: 18153 mUserPaddingLeftInitial = padding.right; 18154 mUserPaddingRightInitial = padding.left; 18155 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 18156 break; 18157 case LAYOUT_DIRECTION_LTR: 18158 default: 18159 mUserPaddingLeftInitial = padding.left; 18160 mUserPaddingRightInitial = padding.right; 18161 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 18162 } 18163 mLeftPaddingDefined = false; 18164 mRightPaddingDefined = false; 18165 } 18166 18167 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 18168 // if it has a different minimum size, we should layout again 18169 if (mBackground == null 18170 || mBackground.getMinimumHeight() != background.getMinimumHeight() 18171 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 18172 requestLayout = true; 18173 } 18174 18175 // Set mBackground before we set this as the callback and start making other 18176 // background drawable state change calls. In particular, the setVisible call below 18177 // can result in drawables attempting to start animations or otherwise invalidate, 18178 // which requires the view set as the callback (us) to recognize the drawable as 18179 // belonging to it as per verifyDrawable. 18180 mBackground = background; 18181 if (background.isStateful()) { 18182 background.setState(getDrawableState()); 18183 } 18184 if (isAttachedToWindow()) { 18185 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18186 } 18187 18188 applyBackgroundTint(); 18189 18190 // Set callback last, since the view may still be initializing. 18191 background.setCallback(this); 18192 18193 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18194 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18195 requestLayout = true; 18196 } 18197 } else { 18198 /* Remove the background */ 18199 mBackground = null; 18200 if ((mViewFlags & WILL_NOT_DRAW) != 0 18201 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 18202 mPrivateFlags |= PFLAG_SKIP_DRAW; 18203 } 18204 18205 /* 18206 * When the background is set, we try to apply its padding to this 18207 * View. When the background is removed, we don't touch this View's 18208 * padding. This is noted in the Javadocs. Hence, we don't need to 18209 * requestLayout(), the invalidate() below is sufficient. 18210 */ 18211 18212 // The old background's minimum size could have affected this 18213 // View's layout, so let's requestLayout 18214 requestLayout = true; 18215 } 18216 18217 computeOpaqueFlags(); 18218 18219 if (requestLayout) { 18220 requestLayout(); 18221 } 18222 18223 mBackgroundSizeChanged = true; 18224 invalidate(true); 18225 invalidateOutline(); 18226 } 18227 18228 /** 18229 * Gets the background drawable 18230 * 18231 * @return The drawable used as the background for this view, if any. 18232 * 18233 * @see #setBackground(Drawable) 18234 * 18235 * @attr ref android.R.styleable#View_background 18236 */ 18237 public Drawable getBackground() { 18238 return mBackground; 18239 } 18240 18241 /** 18242 * Applies a tint to the background drawable. Does not modify the current tint 18243 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18244 * <p> 18245 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18246 * mutate the drawable and apply the specified tint and tint mode using 18247 * {@link Drawable#setTintList(ColorStateList)}. 18248 * 18249 * @param tint the tint to apply, may be {@code null} to clear tint 18250 * 18251 * @attr ref android.R.styleable#View_backgroundTint 18252 * @see #getBackgroundTintList() 18253 * @see Drawable#setTintList(ColorStateList) 18254 */ 18255 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18256 if (mBackgroundTint == null) { 18257 mBackgroundTint = new TintInfo(); 18258 } 18259 mBackgroundTint.mTintList = tint; 18260 mBackgroundTint.mHasTintList = true; 18261 18262 applyBackgroundTint(); 18263 } 18264 18265 /** 18266 * Return the tint applied to the background drawable, if specified. 18267 * 18268 * @return the tint applied to the background drawable 18269 * @attr ref android.R.styleable#View_backgroundTint 18270 * @see #setBackgroundTintList(ColorStateList) 18271 */ 18272 @Nullable 18273 public ColorStateList getBackgroundTintList() { 18274 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18275 } 18276 18277 /** 18278 * Specifies the blending mode used to apply the tint specified by 18279 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18280 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18281 * 18282 * @param tintMode the blending mode used to apply the tint, may be 18283 * {@code null} to clear tint 18284 * @attr ref android.R.styleable#View_backgroundTintMode 18285 * @see #getBackgroundTintMode() 18286 * @see Drawable#setTintMode(PorterDuff.Mode) 18287 */ 18288 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18289 if (mBackgroundTint == null) { 18290 mBackgroundTint = new TintInfo(); 18291 } 18292 mBackgroundTint.mTintMode = tintMode; 18293 mBackgroundTint.mHasTintMode = true; 18294 18295 applyBackgroundTint(); 18296 } 18297 18298 /** 18299 * Return the blending mode used to apply the tint to the background 18300 * drawable, if specified. 18301 * 18302 * @return the blending mode used to apply the tint to the background 18303 * drawable 18304 * @attr ref android.R.styleable#View_backgroundTintMode 18305 * @see #setBackgroundTintMode(PorterDuff.Mode) 18306 */ 18307 @Nullable 18308 public PorterDuff.Mode getBackgroundTintMode() { 18309 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18310 } 18311 18312 private void applyBackgroundTint() { 18313 if (mBackground != null && mBackgroundTint != null) { 18314 final TintInfo tintInfo = mBackgroundTint; 18315 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18316 mBackground = mBackground.mutate(); 18317 18318 if (tintInfo.mHasTintList) { 18319 mBackground.setTintList(tintInfo.mTintList); 18320 } 18321 18322 if (tintInfo.mHasTintMode) { 18323 mBackground.setTintMode(tintInfo.mTintMode); 18324 } 18325 18326 // The drawable (or one of its children) may not have been 18327 // stateful before applying the tint, so let's try again. 18328 if (mBackground.isStateful()) { 18329 mBackground.setState(getDrawableState()); 18330 } 18331 } 18332 } 18333 } 18334 18335 /** 18336 * Returns the drawable used as the foreground of this View. The 18337 * foreground drawable, if non-null, is always drawn on top of the view's content. 18338 * 18339 * @return a Drawable or null if no foreground was set 18340 * 18341 * @see #onDrawForeground(Canvas) 18342 */ 18343 public Drawable getForeground() { 18344 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18345 } 18346 18347 /** 18348 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18349 * 18350 * @param foreground the Drawable to be drawn on top of the children 18351 * 18352 * @attr ref android.R.styleable#View_foreground 18353 */ 18354 public void setForeground(Drawable foreground) { 18355 if (mForegroundInfo == null) { 18356 if (foreground == null) { 18357 // Nothing to do. 18358 return; 18359 } 18360 mForegroundInfo = new ForegroundInfo(); 18361 } 18362 18363 if (foreground == mForegroundInfo.mDrawable) { 18364 // Nothing to do 18365 return; 18366 } 18367 18368 if (mForegroundInfo.mDrawable != null) { 18369 if (isAttachedToWindow()) { 18370 mForegroundInfo.mDrawable.setVisible(false, false); 18371 } 18372 mForegroundInfo.mDrawable.setCallback(null); 18373 unscheduleDrawable(mForegroundInfo.mDrawable); 18374 } 18375 18376 mForegroundInfo.mDrawable = foreground; 18377 mForegroundInfo.mBoundsChanged = true; 18378 if (foreground != null) { 18379 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18380 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18381 } 18382 foreground.setLayoutDirection(getLayoutDirection()); 18383 if (foreground.isStateful()) { 18384 foreground.setState(getDrawableState()); 18385 } 18386 applyForegroundTint(); 18387 if (isAttachedToWindow()) { 18388 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 18389 } 18390 // Set callback last, since the view may still be initializing. 18391 foreground.setCallback(this); 18392 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18393 mPrivateFlags |= PFLAG_SKIP_DRAW; 18394 } 18395 requestLayout(); 18396 invalidate(); 18397 } 18398 18399 /** 18400 * Magic bit used to support features of framework-internal window decor implementation details. 18401 * This used to live exclusively in FrameLayout. 18402 * 18403 * @return true if the foreground should draw inside the padding region or false 18404 * if it should draw inset by the view's padding 18405 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18406 */ 18407 public boolean isForegroundInsidePadding() { 18408 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18409 } 18410 18411 /** 18412 * Describes how the foreground is positioned. 18413 * 18414 * @return foreground gravity. 18415 * 18416 * @see #setForegroundGravity(int) 18417 * 18418 * @attr ref android.R.styleable#View_foregroundGravity 18419 */ 18420 public int getForegroundGravity() { 18421 return mForegroundInfo != null ? mForegroundInfo.mGravity 18422 : Gravity.START | Gravity.TOP; 18423 } 18424 18425 /** 18426 * Describes how the foreground is positioned. Defaults to START and TOP. 18427 * 18428 * @param gravity see {@link android.view.Gravity} 18429 * 18430 * @see #getForegroundGravity() 18431 * 18432 * @attr ref android.R.styleable#View_foregroundGravity 18433 */ 18434 public void setForegroundGravity(int gravity) { 18435 if (mForegroundInfo == null) { 18436 mForegroundInfo = new ForegroundInfo(); 18437 } 18438 18439 if (mForegroundInfo.mGravity != gravity) { 18440 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18441 gravity |= Gravity.START; 18442 } 18443 18444 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18445 gravity |= Gravity.TOP; 18446 } 18447 18448 mForegroundInfo.mGravity = gravity; 18449 requestLayout(); 18450 } 18451 } 18452 18453 /** 18454 * Applies a tint to the foreground drawable. Does not modify the current tint 18455 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18456 * <p> 18457 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18458 * mutate the drawable and apply the specified tint and tint mode using 18459 * {@link Drawable#setTintList(ColorStateList)}. 18460 * 18461 * @param tint the tint to apply, may be {@code null} to clear tint 18462 * 18463 * @attr ref android.R.styleable#View_foregroundTint 18464 * @see #getForegroundTintList() 18465 * @see Drawable#setTintList(ColorStateList) 18466 */ 18467 public void setForegroundTintList(@Nullable ColorStateList tint) { 18468 if (mForegroundInfo == null) { 18469 mForegroundInfo = new ForegroundInfo(); 18470 } 18471 if (mForegroundInfo.mTintInfo == null) { 18472 mForegroundInfo.mTintInfo = new TintInfo(); 18473 } 18474 mForegroundInfo.mTintInfo.mTintList = tint; 18475 mForegroundInfo.mTintInfo.mHasTintList = true; 18476 18477 applyForegroundTint(); 18478 } 18479 18480 /** 18481 * Return the tint applied to the foreground drawable, if specified. 18482 * 18483 * @return the tint applied to the foreground drawable 18484 * @attr ref android.R.styleable#View_foregroundTint 18485 * @see #setForegroundTintList(ColorStateList) 18486 */ 18487 @Nullable 18488 public ColorStateList getForegroundTintList() { 18489 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18490 ? mForegroundInfo.mTintInfo.mTintList : null; 18491 } 18492 18493 /** 18494 * Specifies the blending mode used to apply the tint specified by 18495 * {@link #setForegroundTintList(ColorStateList)}} to the background 18496 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18497 * 18498 * @param tintMode the blending mode used to apply the tint, may be 18499 * {@code null} to clear tint 18500 * @attr ref android.R.styleable#View_foregroundTintMode 18501 * @see #getForegroundTintMode() 18502 * @see Drawable#setTintMode(PorterDuff.Mode) 18503 */ 18504 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18505 if (mForegroundInfo == null) { 18506 mForegroundInfo = new ForegroundInfo(); 18507 } 18508 if (mForegroundInfo.mTintInfo == null) { 18509 mForegroundInfo.mTintInfo = new TintInfo(); 18510 } 18511 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18512 mForegroundInfo.mTintInfo.mHasTintMode = true; 18513 18514 applyForegroundTint(); 18515 } 18516 18517 /** 18518 * Return the blending mode used to apply the tint to the foreground 18519 * drawable, if specified. 18520 * 18521 * @return the blending mode used to apply the tint to the foreground 18522 * drawable 18523 * @attr ref android.R.styleable#View_foregroundTintMode 18524 * @see #setForegroundTintMode(PorterDuff.Mode) 18525 */ 18526 @Nullable 18527 public PorterDuff.Mode getForegroundTintMode() { 18528 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18529 ? mForegroundInfo.mTintInfo.mTintMode : null; 18530 } 18531 18532 private void applyForegroundTint() { 18533 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18534 && mForegroundInfo.mTintInfo != null) { 18535 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18536 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18537 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18538 18539 if (tintInfo.mHasTintList) { 18540 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18541 } 18542 18543 if (tintInfo.mHasTintMode) { 18544 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18545 } 18546 18547 // The drawable (or one of its children) may not have been 18548 // stateful before applying the tint, so let's try again. 18549 if (mForegroundInfo.mDrawable.isStateful()) { 18550 mForegroundInfo.mDrawable.setState(getDrawableState()); 18551 } 18552 } 18553 } 18554 } 18555 18556 /** 18557 * Draw any foreground content for this view. 18558 * 18559 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18560 * drawable or other view-specific decorations. The foreground is drawn on top of the 18561 * primary view content.</p> 18562 * 18563 * @param canvas canvas to draw into 18564 */ 18565 public void onDrawForeground(Canvas canvas) { 18566 onDrawScrollIndicators(canvas); 18567 onDrawScrollBars(canvas); 18568 18569 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18570 if (foreground != null) { 18571 if (mForegroundInfo.mBoundsChanged) { 18572 mForegroundInfo.mBoundsChanged = false; 18573 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18574 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18575 18576 if (mForegroundInfo.mInsidePadding) { 18577 selfBounds.set(0, 0, getWidth(), getHeight()); 18578 } else { 18579 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18580 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18581 } 18582 18583 final int ld = getLayoutDirection(); 18584 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18585 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18586 foreground.setBounds(overlayBounds); 18587 } 18588 18589 foreground.draw(canvas); 18590 } 18591 } 18592 18593 /** 18594 * Sets the padding. The view may add on the space required to display 18595 * the scrollbars, depending on the style and visibility of the scrollbars. 18596 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18597 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18598 * from the values set in this call. 18599 * 18600 * @attr ref android.R.styleable#View_padding 18601 * @attr ref android.R.styleable#View_paddingBottom 18602 * @attr ref android.R.styleable#View_paddingLeft 18603 * @attr ref android.R.styleable#View_paddingRight 18604 * @attr ref android.R.styleable#View_paddingTop 18605 * @param left the left padding in pixels 18606 * @param top the top padding in pixels 18607 * @param right the right padding in pixels 18608 * @param bottom the bottom padding in pixels 18609 */ 18610 public void setPadding(int left, int top, int right, int bottom) { 18611 resetResolvedPaddingInternal(); 18612 18613 mUserPaddingStart = UNDEFINED_PADDING; 18614 mUserPaddingEnd = UNDEFINED_PADDING; 18615 18616 mUserPaddingLeftInitial = left; 18617 mUserPaddingRightInitial = right; 18618 18619 mLeftPaddingDefined = true; 18620 mRightPaddingDefined = true; 18621 18622 internalSetPadding(left, top, right, bottom); 18623 } 18624 18625 /** 18626 * @hide 18627 */ 18628 protected void internalSetPadding(int left, int top, int right, int bottom) { 18629 mUserPaddingLeft = left; 18630 mUserPaddingRight = right; 18631 mUserPaddingBottom = bottom; 18632 18633 final int viewFlags = mViewFlags; 18634 boolean changed = false; 18635 18636 // Common case is there are no scroll bars. 18637 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18638 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18639 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18640 ? 0 : getVerticalScrollbarWidth(); 18641 switch (mVerticalScrollbarPosition) { 18642 case SCROLLBAR_POSITION_DEFAULT: 18643 if (isLayoutRtl()) { 18644 left += offset; 18645 } else { 18646 right += offset; 18647 } 18648 break; 18649 case SCROLLBAR_POSITION_RIGHT: 18650 right += offset; 18651 break; 18652 case SCROLLBAR_POSITION_LEFT: 18653 left += offset; 18654 break; 18655 } 18656 } 18657 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18658 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18659 ? 0 : getHorizontalScrollbarHeight(); 18660 } 18661 } 18662 18663 if (mPaddingLeft != left) { 18664 changed = true; 18665 mPaddingLeft = left; 18666 } 18667 if (mPaddingTop != top) { 18668 changed = true; 18669 mPaddingTop = top; 18670 } 18671 if (mPaddingRight != right) { 18672 changed = true; 18673 mPaddingRight = right; 18674 } 18675 if (mPaddingBottom != bottom) { 18676 changed = true; 18677 mPaddingBottom = bottom; 18678 } 18679 18680 if (changed) { 18681 requestLayout(); 18682 invalidateOutline(); 18683 } 18684 } 18685 18686 /** 18687 * Sets the relative padding. The view may add on the space required to display 18688 * the scrollbars, depending on the style and visibility of the scrollbars. 18689 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18690 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18691 * from the values set in this call. 18692 * 18693 * @attr ref android.R.styleable#View_padding 18694 * @attr ref android.R.styleable#View_paddingBottom 18695 * @attr ref android.R.styleable#View_paddingStart 18696 * @attr ref android.R.styleable#View_paddingEnd 18697 * @attr ref android.R.styleable#View_paddingTop 18698 * @param start the start padding in pixels 18699 * @param top the top padding in pixels 18700 * @param end the end padding in pixels 18701 * @param bottom the bottom padding in pixels 18702 */ 18703 public void setPaddingRelative(int start, int top, int end, int bottom) { 18704 resetResolvedPaddingInternal(); 18705 18706 mUserPaddingStart = start; 18707 mUserPaddingEnd = end; 18708 mLeftPaddingDefined = true; 18709 mRightPaddingDefined = true; 18710 18711 switch(getLayoutDirection()) { 18712 case LAYOUT_DIRECTION_RTL: 18713 mUserPaddingLeftInitial = end; 18714 mUserPaddingRightInitial = start; 18715 internalSetPadding(end, top, start, bottom); 18716 break; 18717 case LAYOUT_DIRECTION_LTR: 18718 default: 18719 mUserPaddingLeftInitial = start; 18720 mUserPaddingRightInitial = end; 18721 internalSetPadding(start, top, end, bottom); 18722 } 18723 } 18724 18725 /** 18726 * Returns the top padding of this view. 18727 * 18728 * @return the top padding in pixels 18729 */ 18730 public int getPaddingTop() { 18731 return mPaddingTop; 18732 } 18733 18734 /** 18735 * Returns the bottom padding of this view. If there are inset and enabled 18736 * scrollbars, this value may include the space required to display the 18737 * scrollbars as well. 18738 * 18739 * @return the bottom padding in pixels 18740 */ 18741 public int getPaddingBottom() { 18742 return mPaddingBottom; 18743 } 18744 18745 /** 18746 * Returns the left padding of this view. If there are inset and enabled 18747 * scrollbars, this value may include the space required to display the 18748 * scrollbars as well. 18749 * 18750 * @return the left padding in pixels 18751 */ 18752 public int getPaddingLeft() { 18753 if (!isPaddingResolved()) { 18754 resolvePadding(); 18755 } 18756 return mPaddingLeft; 18757 } 18758 18759 /** 18760 * Returns the start padding of this view depending on its resolved layout direction. 18761 * If there are inset and enabled scrollbars, this value may include the space 18762 * required to display the scrollbars as well. 18763 * 18764 * @return the start padding in pixels 18765 */ 18766 public int getPaddingStart() { 18767 if (!isPaddingResolved()) { 18768 resolvePadding(); 18769 } 18770 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18771 mPaddingRight : mPaddingLeft; 18772 } 18773 18774 /** 18775 * Returns the right padding of this view. If there are inset and enabled 18776 * scrollbars, this value may include the space required to display the 18777 * scrollbars as well. 18778 * 18779 * @return the right padding in pixels 18780 */ 18781 public int getPaddingRight() { 18782 if (!isPaddingResolved()) { 18783 resolvePadding(); 18784 } 18785 return mPaddingRight; 18786 } 18787 18788 /** 18789 * Returns the end padding of this view depending on its resolved layout direction. 18790 * If there are inset and enabled scrollbars, this value may include the space 18791 * required to display the scrollbars as well. 18792 * 18793 * @return the end padding in pixels 18794 */ 18795 public int getPaddingEnd() { 18796 if (!isPaddingResolved()) { 18797 resolvePadding(); 18798 } 18799 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18800 mPaddingLeft : mPaddingRight; 18801 } 18802 18803 /** 18804 * Return if the padding has been set through relative values 18805 * {@link #setPaddingRelative(int, int, int, int)} or through 18806 * @attr ref android.R.styleable#View_paddingStart or 18807 * @attr ref android.R.styleable#View_paddingEnd 18808 * 18809 * @return true if the padding is relative or false if it is not. 18810 */ 18811 public boolean isPaddingRelative() { 18812 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18813 } 18814 18815 Insets computeOpticalInsets() { 18816 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18817 } 18818 18819 /** 18820 * @hide 18821 */ 18822 public void resetPaddingToInitialValues() { 18823 if (isRtlCompatibilityMode()) { 18824 mPaddingLeft = mUserPaddingLeftInitial; 18825 mPaddingRight = mUserPaddingRightInitial; 18826 return; 18827 } 18828 if (isLayoutRtl()) { 18829 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18830 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18831 } else { 18832 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18833 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18834 } 18835 } 18836 18837 /** 18838 * @hide 18839 */ 18840 public Insets getOpticalInsets() { 18841 if (mLayoutInsets == null) { 18842 mLayoutInsets = computeOpticalInsets(); 18843 } 18844 return mLayoutInsets; 18845 } 18846 18847 /** 18848 * Set this view's optical insets. 18849 * 18850 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18851 * property. Views that compute their own optical insets should call it as part of measurement. 18852 * This method does not request layout. If you are setting optical insets outside of 18853 * measure/layout itself you will want to call requestLayout() yourself. 18854 * </p> 18855 * @hide 18856 */ 18857 public void setOpticalInsets(Insets insets) { 18858 mLayoutInsets = insets; 18859 } 18860 18861 /** 18862 * Changes the selection state of this view. A view can be selected or not. 18863 * Note that selection is not the same as focus. Views are typically 18864 * selected in the context of an AdapterView like ListView or GridView; 18865 * the selected view is the view that is highlighted. 18866 * 18867 * @param selected true if the view must be selected, false otherwise 18868 */ 18869 public void setSelected(boolean selected) { 18870 //noinspection DoubleNegation 18871 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18872 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18873 if (!selected) resetPressedState(); 18874 invalidate(true); 18875 refreshDrawableState(); 18876 dispatchSetSelected(selected); 18877 if (selected) { 18878 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18879 } else { 18880 notifyViewAccessibilityStateChangedIfNeeded( 18881 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18882 } 18883 } 18884 } 18885 18886 /** 18887 * Dispatch setSelected to all of this View's children. 18888 * 18889 * @see #setSelected(boolean) 18890 * 18891 * @param selected The new selected state 18892 */ 18893 protected void dispatchSetSelected(boolean selected) { 18894 } 18895 18896 /** 18897 * Indicates the selection state of this view. 18898 * 18899 * @return true if the view is selected, false otherwise 18900 */ 18901 @ViewDebug.ExportedProperty 18902 public boolean isSelected() { 18903 return (mPrivateFlags & PFLAG_SELECTED) != 0; 18904 } 18905 18906 /** 18907 * Changes the activated state of this view. A view can be activated or not. 18908 * Note that activation is not the same as selection. Selection is 18909 * a transient property, representing the view (hierarchy) the user is 18910 * currently interacting with. Activation is a longer-term state that the 18911 * user can move views in and out of. For example, in a list view with 18912 * single or multiple selection enabled, the views in the current selection 18913 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18914 * here.) The activated state is propagated down to children of the view it 18915 * is set on. 18916 * 18917 * @param activated true if the view must be activated, false otherwise 18918 */ 18919 public void setActivated(boolean activated) { 18920 //noinspection DoubleNegation 18921 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18922 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18923 invalidate(true); 18924 refreshDrawableState(); 18925 dispatchSetActivated(activated); 18926 } 18927 } 18928 18929 /** 18930 * Dispatch setActivated to all of this View's children. 18931 * 18932 * @see #setActivated(boolean) 18933 * 18934 * @param activated The new activated state 18935 */ 18936 protected void dispatchSetActivated(boolean activated) { 18937 } 18938 18939 /** 18940 * Indicates the activation state of this view. 18941 * 18942 * @return true if the view is activated, false otherwise 18943 */ 18944 @ViewDebug.ExportedProperty 18945 public boolean isActivated() { 18946 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18947 } 18948 18949 /** 18950 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18951 * observer can be used to get notifications when global events, like 18952 * layout, happen. 18953 * 18954 * The returned ViewTreeObserver observer is not guaranteed to remain 18955 * valid for the lifetime of this View. If the caller of this method keeps 18956 * a long-lived reference to ViewTreeObserver, it should always check for 18957 * the return value of {@link ViewTreeObserver#isAlive()}. 18958 * 18959 * @return The ViewTreeObserver for this view's hierarchy. 18960 */ 18961 public ViewTreeObserver getViewTreeObserver() { 18962 if (mAttachInfo != null) { 18963 return mAttachInfo.mTreeObserver; 18964 } 18965 if (mFloatingTreeObserver == null) { 18966 mFloatingTreeObserver = new ViewTreeObserver(); 18967 } 18968 return mFloatingTreeObserver; 18969 } 18970 18971 /** 18972 * <p>Finds the topmost view in the current view hierarchy.</p> 18973 * 18974 * @return the topmost view containing this view 18975 */ 18976 public View getRootView() { 18977 if (mAttachInfo != null) { 18978 final View v = mAttachInfo.mRootView; 18979 if (v != null) { 18980 return v; 18981 } 18982 } 18983 18984 View parent = this; 18985 18986 while (parent.mParent != null && parent.mParent instanceof View) { 18987 parent = (View) parent.mParent; 18988 } 18989 18990 return parent; 18991 } 18992 18993 /** 18994 * Transforms a motion event from view-local coordinates to on-screen 18995 * coordinates. 18996 * 18997 * @param ev the view-local motion event 18998 * @return false if the transformation could not be applied 18999 * @hide 19000 */ 19001 public boolean toGlobalMotionEvent(MotionEvent ev) { 19002 final AttachInfo info = mAttachInfo; 19003 if (info == null) { 19004 return false; 19005 } 19006 19007 final Matrix m = info.mTmpMatrix; 19008 m.set(Matrix.IDENTITY_MATRIX); 19009 transformMatrixToGlobal(m); 19010 ev.transform(m); 19011 return true; 19012 } 19013 19014 /** 19015 * Transforms a motion event from on-screen coordinates to view-local 19016 * coordinates. 19017 * 19018 * @param ev the on-screen motion event 19019 * @return false if the transformation could not be applied 19020 * @hide 19021 */ 19022 public boolean toLocalMotionEvent(MotionEvent ev) { 19023 final AttachInfo info = mAttachInfo; 19024 if (info == null) { 19025 return false; 19026 } 19027 19028 final Matrix m = info.mTmpMatrix; 19029 m.set(Matrix.IDENTITY_MATRIX); 19030 transformMatrixToLocal(m); 19031 ev.transform(m); 19032 return true; 19033 } 19034 19035 /** 19036 * Modifies the input matrix such that it maps view-local coordinates to 19037 * on-screen coordinates. 19038 * 19039 * @param m input matrix to modify 19040 * @hide 19041 */ 19042 public void transformMatrixToGlobal(Matrix m) { 19043 final ViewParent parent = mParent; 19044 if (parent instanceof View) { 19045 final View vp = (View) parent; 19046 vp.transformMatrixToGlobal(m); 19047 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 19048 } else if (parent instanceof ViewRootImpl) { 19049 final ViewRootImpl vr = (ViewRootImpl) parent; 19050 vr.transformMatrixToGlobal(m); 19051 m.preTranslate(0, -vr.mCurScrollY); 19052 } 19053 19054 m.preTranslate(mLeft, mTop); 19055 19056 if (!hasIdentityMatrix()) { 19057 m.preConcat(getMatrix()); 19058 } 19059 } 19060 19061 /** 19062 * Modifies the input matrix such that it maps on-screen coordinates to 19063 * view-local coordinates. 19064 * 19065 * @param m input matrix to modify 19066 * @hide 19067 */ 19068 public void transformMatrixToLocal(Matrix m) { 19069 final ViewParent parent = mParent; 19070 if (parent instanceof View) { 19071 final View vp = (View) parent; 19072 vp.transformMatrixToLocal(m); 19073 m.postTranslate(vp.mScrollX, vp.mScrollY); 19074 } else if (parent instanceof ViewRootImpl) { 19075 final ViewRootImpl vr = (ViewRootImpl) parent; 19076 vr.transformMatrixToLocal(m); 19077 m.postTranslate(0, vr.mCurScrollY); 19078 } 19079 19080 m.postTranslate(-mLeft, -mTop); 19081 19082 if (!hasIdentityMatrix()) { 19083 m.postConcat(getInverseMatrix()); 19084 } 19085 } 19086 19087 /** 19088 * @hide 19089 */ 19090 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 19091 @ViewDebug.IntToString(from = 0, to = "x"), 19092 @ViewDebug.IntToString(from = 1, to = "y") 19093 }) 19094 public int[] getLocationOnScreen() { 19095 int[] location = new int[2]; 19096 getLocationOnScreen(location); 19097 return location; 19098 } 19099 19100 /** 19101 * <p>Computes the coordinates of this view on the screen. The argument 19102 * must be an array of two integers. After the method returns, the array 19103 * contains the x and y location in that order.</p> 19104 * 19105 * @param outLocation an array of two integers in which to hold the coordinates 19106 */ 19107 public void getLocationOnScreen(@Size(2) int[] outLocation) { 19108 getLocationInWindow(outLocation); 19109 19110 final AttachInfo info = mAttachInfo; 19111 if (info != null) { 19112 outLocation[0] += info.mWindowLeft; 19113 outLocation[1] += info.mWindowTop; 19114 } 19115 } 19116 19117 /** 19118 * <p>Computes the coordinates of this view in its window. The argument 19119 * must be an array of two integers. After the method returns, the array 19120 * contains the x and y location in that order.</p> 19121 * 19122 * @param outLocation an array of two integers in which to hold the coordinates 19123 */ 19124 public void getLocationInWindow(@Size(2) int[] outLocation) { 19125 if (outLocation == null || outLocation.length < 2) { 19126 throw new IllegalArgumentException("outLocation must be an array of two integers"); 19127 } 19128 19129 outLocation[0] = 0; 19130 outLocation[1] = 0; 19131 19132 transformFromViewToWindowSpace(outLocation); 19133 } 19134 19135 /** @hide */ 19136 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 19137 if (inOutLocation == null || inOutLocation.length < 2) { 19138 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 19139 } 19140 19141 if (mAttachInfo == null) { 19142 // When the view is not attached to a window, this method does not make sense 19143 inOutLocation[0] = inOutLocation[1] = 0; 19144 return; 19145 } 19146 19147 float position[] = mAttachInfo.mTmpTransformLocation; 19148 position[0] = inOutLocation[0]; 19149 position[1] = inOutLocation[1]; 19150 19151 if (!hasIdentityMatrix()) { 19152 getMatrix().mapPoints(position); 19153 } 19154 19155 position[0] += mLeft; 19156 position[1] += mTop; 19157 19158 ViewParent viewParent = mParent; 19159 while (viewParent instanceof View) { 19160 final View view = (View) viewParent; 19161 19162 position[0] -= view.mScrollX; 19163 position[1] -= view.mScrollY; 19164 19165 if (!view.hasIdentityMatrix()) { 19166 view.getMatrix().mapPoints(position); 19167 } 19168 19169 position[0] += view.mLeft; 19170 position[1] += view.mTop; 19171 19172 viewParent = view.mParent; 19173 } 19174 19175 if (viewParent instanceof ViewRootImpl) { 19176 // *cough* 19177 final ViewRootImpl vr = (ViewRootImpl) viewParent; 19178 position[1] -= vr.mCurScrollY; 19179 } 19180 19181 inOutLocation[0] = Math.round(position[0]); 19182 inOutLocation[1] = Math.round(position[1]); 19183 } 19184 19185 /** 19186 * {@hide} 19187 * @param id the id of the view to be found 19188 * @return the view of the specified id, null if cannot be found 19189 */ 19190 protected View findViewTraversal(@IdRes int id) { 19191 if (id == mID) { 19192 return this; 19193 } 19194 return null; 19195 } 19196 19197 /** 19198 * {@hide} 19199 * @param tag the tag of the view to be found 19200 * @return the view of specified tag, null if cannot be found 19201 */ 19202 protected View findViewWithTagTraversal(Object tag) { 19203 if (tag != null && tag.equals(mTag)) { 19204 return this; 19205 } 19206 return null; 19207 } 19208 19209 /** 19210 * {@hide} 19211 * @param predicate The predicate to evaluate. 19212 * @param childToSkip If not null, ignores this child during the recursive traversal. 19213 * @return The first view that matches the predicate or null. 19214 */ 19215 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19216 if (predicate.apply(this)) { 19217 return this; 19218 } 19219 return null; 19220 } 19221 19222 /** 19223 * Look for a child view with the given id. If this view has the given 19224 * id, return this view. 19225 * 19226 * @param id The id to search for. 19227 * @return The view that has the given id in the hierarchy or null 19228 */ 19229 @Nullable 19230 public final View findViewById(@IdRes int id) { 19231 if (id < 0) { 19232 return null; 19233 } 19234 return findViewTraversal(id); 19235 } 19236 19237 /** 19238 * Finds a view by its unuque and stable accessibility id. 19239 * 19240 * @param accessibilityId The searched accessibility id. 19241 * @return The found view. 19242 */ 19243 final View findViewByAccessibilityId(int accessibilityId) { 19244 if (accessibilityId < 0) { 19245 return null; 19246 } 19247 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19248 if (view != null) { 19249 return view.includeForAccessibility() ? view : null; 19250 } 19251 return null; 19252 } 19253 19254 /** 19255 * Performs the traversal to find a view by its unuque and stable accessibility id. 19256 * 19257 * <strong>Note:</strong>This method does not stop at the root namespace 19258 * boundary since the user can touch the screen at an arbitrary location 19259 * potentially crossing the root namespace bounday which will send an 19260 * accessibility event to accessibility services and they should be able 19261 * to obtain the event source. Also accessibility ids are guaranteed to be 19262 * unique in the window. 19263 * 19264 * @param accessibilityId The accessibility id. 19265 * @return The found view. 19266 * 19267 * @hide 19268 */ 19269 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19270 if (getAccessibilityViewId() == accessibilityId) { 19271 return this; 19272 } 19273 return null; 19274 } 19275 19276 /** 19277 * Look for a child view with the given tag. If this view has the given 19278 * tag, return this view. 19279 * 19280 * @param tag The tag to search for, using "tag.equals(getTag())". 19281 * @return The View that has the given tag in the hierarchy or null 19282 */ 19283 public final View findViewWithTag(Object tag) { 19284 if (tag == null) { 19285 return null; 19286 } 19287 return findViewWithTagTraversal(tag); 19288 } 19289 19290 /** 19291 * {@hide} 19292 * Look for a child view that matches the specified predicate. 19293 * If this view matches the predicate, return this view. 19294 * 19295 * @param predicate The predicate to evaluate. 19296 * @return The first view that matches the predicate or null. 19297 */ 19298 public final View findViewByPredicate(Predicate<View> predicate) { 19299 return findViewByPredicateTraversal(predicate, null); 19300 } 19301 19302 /** 19303 * {@hide} 19304 * Look for a child view that matches the specified predicate, 19305 * starting with the specified view and its descendents and then 19306 * recusively searching the ancestors and siblings of that view 19307 * until this view is reached. 19308 * 19309 * This method is useful in cases where the predicate does not match 19310 * a single unique view (perhaps multiple views use the same id) 19311 * and we are trying to find the view that is "closest" in scope to the 19312 * starting view. 19313 * 19314 * @param start The view to start from. 19315 * @param predicate The predicate to evaluate. 19316 * @return The first view that matches the predicate or null. 19317 */ 19318 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19319 View childToSkip = null; 19320 for (;;) { 19321 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19322 if (view != null || start == this) { 19323 return view; 19324 } 19325 19326 ViewParent parent = start.getParent(); 19327 if (parent == null || !(parent instanceof View)) { 19328 return null; 19329 } 19330 19331 childToSkip = start; 19332 start = (View) parent; 19333 } 19334 } 19335 19336 /** 19337 * Sets the identifier for this view. The identifier does not have to be 19338 * unique in this view's hierarchy. The identifier should be a positive 19339 * number. 19340 * 19341 * @see #NO_ID 19342 * @see #getId() 19343 * @see #findViewById(int) 19344 * 19345 * @param id a number used to identify the view 19346 * 19347 * @attr ref android.R.styleable#View_id 19348 */ 19349 public void setId(@IdRes int id) { 19350 mID = id; 19351 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19352 mID = generateViewId(); 19353 } 19354 } 19355 19356 /** 19357 * {@hide} 19358 * 19359 * @param isRoot true if the view belongs to the root namespace, false 19360 * otherwise 19361 */ 19362 public void setIsRootNamespace(boolean isRoot) { 19363 if (isRoot) { 19364 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19365 } else { 19366 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19367 } 19368 } 19369 19370 /** 19371 * {@hide} 19372 * 19373 * @return true if the view belongs to the root namespace, false otherwise 19374 */ 19375 public boolean isRootNamespace() { 19376 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19377 } 19378 19379 /** 19380 * Returns this view's identifier. 19381 * 19382 * @return a positive integer used to identify the view or {@link #NO_ID} 19383 * if the view has no ID 19384 * 19385 * @see #setId(int) 19386 * @see #findViewById(int) 19387 * @attr ref android.R.styleable#View_id 19388 */ 19389 @IdRes 19390 @ViewDebug.CapturedViewProperty 19391 public int getId() { 19392 return mID; 19393 } 19394 19395 /** 19396 * Returns this view's tag. 19397 * 19398 * @return the Object stored in this view as a tag, or {@code null} if not 19399 * set 19400 * 19401 * @see #setTag(Object) 19402 * @see #getTag(int) 19403 */ 19404 @ViewDebug.ExportedProperty 19405 public Object getTag() { 19406 return mTag; 19407 } 19408 19409 /** 19410 * Sets the tag associated with this view. A tag can be used to mark 19411 * a view in its hierarchy and does not have to be unique within the 19412 * hierarchy. Tags can also be used to store data within a view without 19413 * resorting to another data structure. 19414 * 19415 * @param tag an Object to tag the view with 19416 * 19417 * @see #getTag() 19418 * @see #setTag(int, Object) 19419 */ 19420 public void setTag(final Object tag) { 19421 mTag = tag; 19422 } 19423 19424 /** 19425 * Returns the tag associated with this view and the specified key. 19426 * 19427 * @param key The key identifying the tag 19428 * 19429 * @return the Object stored in this view as a tag, or {@code null} if not 19430 * set 19431 * 19432 * @see #setTag(int, Object) 19433 * @see #getTag() 19434 */ 19435 public Object getTag(int key) { 19436 if (mKeyedTags != null) return mKeyedTags.get(key); 19437 return null; 19438 } 19439 19440 /** 19441 * Sets a tag associated with this view and a key. A tag can be used 19442 * to mark a view in its hierarchy and does not have to be unique within 19443 * the hierarchy. Tags can also be used to store data within a view 19444 * without resorting to another data structure. 19445 * 19446 * The specified key should be an id declared in the resources of the 19447 * application to ensure it is unique (see the <a 19448 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19449 * Keys identified as belonging to 19450 * the Android framework or not associated with any package will cause 19451 * an {@link IllegalArgumentException} to be thrown. 19452 * 19453 * @param key The key identifying the tag 19454 * @param tag An Object to tag the view with 19455 * 19456 * @throws IllegalArgumentException If they specified key is not valid 19457 * 19458 * @see #setTag(Object) 19459 * @see #getTag(int) 19460 */ 19461 public void setTag(int key, final Object tag) { 19462 // If the package id is 0x00 or 0x01, it's either an undefined package 19463 // or a framework id 19464 if ((key >>> 24) < 2) { 19465 throw new IllegalArgumentException("The key must be an application-specific " 19466 + "resource id."); 19467 } 19468 19469 setKeyedTag(key, tag); 19470 } 19471 19472 /** 19473 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19474 * framework id. 19475 * 19476 * @hide 19477 */ 19478 public void setTagInternal(int key, Object tag) { 19479 if ((key >>> 24) != 0x1) { 19480 throw new IllegalArgumentException("The key must be a framework-specific " 19481 + "resource id."); 19482 } 19483 19484 setKeyedTag(key, tag); 19485 } 19486 19487 private void setKeyedTag(int key, Object tag) { 19488 if (mKeyedTags == null) { 19489 mKeyedTags = new SparseArray<Object>(2); 19490 } 19491 19492 mKeyedTags.put(key, tag); 19493 } 19494 19495 /** 19496 * Prints information about this view in the log output, with the tag 19497 * {@link #VIEW_LOG_TAG}. 19498 * 19499 * @hide 19500 */ 19501 public void debug() { 19502 debug(0); 19503 } 19504 19505 /** 19506 * Prints information about this view in the log output, with the tag 19507 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19508 * indentation defined by the <code>depth</code>. 19509 * 19510 * @param depth the indentation level 19511 * 19512 * @hide 19513 */ 19514 protected void debug(int depth) { 19515 String output = debugIndent(depth - 1); 19516 19517 output += "+ " + this; 19518 int id = getId(); 19519 if (id != -1) { 19520 output += " (id=" + id + ")"; 19521 } 19522 Object tag = getTag(); 19523 if (tag != null) { 19524 output += " (tag=" + tag + ")"; 19525 } 19526 Log.d(VIEW_LOG_TAG, output); 19527 19528 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19529 output = debugIndent(depth) + " FOCUSED"; 19530 Log.d(VIEW_LOG_TAG, output); 19531 } 19532 19533 output = debugIndent(depth); 19534 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19535 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19536 + "} "; 19537 Log.d(VIEW_LOG_TAG, output); 19538 19539 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19540 || mPaddingBottom != 0) { 19541 output = debugIndent(depth); 19542 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19543 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19544 Log.d(VIEW_LOG_TAG, output); 19545 } 19546 19547 output = debugIndent(depth); 19548 output += "mMeasureWidth=" + mMeasuredWidth + 19549 " mMeasureHeight=" + mMeasuredHeight; 19550 Log.d(VIEW_LOG_TAG, output); 19551 19552 output = debugIndent(depth); 19553 if (mLayoutParams == null) { 19554 output += "BAD! no layout params"; 19555 } else { 19556 output = mLayoutParams.debug(output); 19557 } 19558 Log.d(VIEW_LOG_TAG, output); 19559 19560 output = debugIndent(depth); 19561 output += "flags={"; 19562 output += View.printFlags(mViewFlags); 19563 output += "}"; 19564 Log.d(VIEW_LOG_TAG, output); 19565 19566 output = debugIndent(depth); 19567 output += "privateFlags={"; 19568 output += View.printPrivateFlags(mPrivateFlags); 19569 output += "}"; 19570 Log.d(VIEW_LOG_TAG, output); 19571 } 19572 19573 /** 19574 * Creates a string of whitespaces used for indentation. 19575 * 19576 * @param depth the indentation level 19577 * @return a String containing (depth * 2 + 3) * 2 white spaces 19578 * 19579 * @hide 19580 */ 19581 protected static String debugIndent(int depth) { 19582 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19583 for (int i = 0; i < (depth * 2) + 3; i++) { 19584 spaces.append(' ').append(' '); 19585 } 19586 return spaces.toString(); 19587 } 19588 19589 /** 19590 * <p>Return the offset of the widget's text baseline from the widget's top 19591 * boundary. If this widget does not support baseline alignment, this 19592 * method returns -1. </p> 19593 * 19594 * @return the offset of the baseline within the widget's bounds or -1 19595 * if baseline alignment is not supported 19596 */ 19597 @ViewDebug.ExportedProperty(category = "layout") 19598 public int getBaseline() { 19599 return -1; 19600 } 19601 19602 /** 19603 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19604 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19605 * a layout pass. 19606 * 19607 * @return whether the view hierarchy is currently undergoing a layout pass 19608 */ 19609 public boolean isInLayout() { 19610 ViewRootImpl viewRoot = getViewRootImpl(); 19611 return (viewRoot != null && viewRoot.isInLayout()); 19612 } 19613 19614 /** 19615 * Call this when something has changed which has invalidated the 19616 * layout of this view. This will schedule a layout pass of the view 19617 * tree. This should not be called while the view hierarchy is currently in a layout 19618 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19619 * end of the current layout pass (and then layout will run again) or after the current 19620 * frame is drawn and the next layout occurs. 19621 * 19622 * <p>Subclasses which override this method should call the superclass method to 19623 * handle possible request-during-layout errors correctly.</p> 19624 */ 19625 @CallSuper 19626 public void requestLayout() { 19627 if (mMeasureCache != null) mMeasureCache.clear(); 19628 19629 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19630 // Only trigger request-during-layout logic if this is the view requesting it, 19631 // not the views in its parent hierarchy 19632 ViewRootImpl viewRoot = getViewRootImpl(); 19633 if (viewRoot != null && viewRoot.isInLayout()) { 19634 if (!viewRoot.requestLayoutDuringLayout(this)) { 19635 return; 19636 } 19637 } 19638 mAttachInfo.mViewRequestingLayout = this; 19639 } 19640 19641 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19642 mPrivateFlags |= PFLAG_INVALIDATED; 19643 19644 if (mParent != null && !mParent.isLayoutRequested()) { 19645 mParent.requestLayout(); 19646 } 19647 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19648 mAttachInfo.mViewRequestingLayout = null; 19649 } 19650 } 19651 19652 /** 19653 * Forces this view to be laid out during the next layout pass. 19654 * This method does not call requestLayout() or forceLayout() 19655 * on the parent. 19656 */ 19657 public void forceLayout() { 19658 if (mMeasureCache != null) mMeasureCache.clear(); 19659 19660 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19661 mPrivateFlags |= PFLAG_INVALIDATED; 19662 } 19663 19664 /** 19665 * <p> 19666 * This is called to find out how big a view should be. The parent 19667 * supplies constraint information in the width and height parameters. 19668 * </p> 19669 * 19670 * <p> 19671 * The actual measurement work of a view is performed in 19672 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19673 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19674 * </p> 19675 * 19676 * 19677 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19678 * parent 19679 * @param heightMeasureSpec Vertical space requirements as imposed by the 19680 * parent 19681 * 19682 * @see #onMeasure(int, int) 19683 */ 19684 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19685 boolean optical = isLayoutModeOptical(this); 19686 if (optical != isLayoutModeOptical(mParent)) { 19687 Insets insets = getOpticalInsets(); 19688 int oWidth = insets.left + insets.right; 19689 int oHeight = insets.top + insets.bottom; 19690 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19691 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19692 } 19693 19694 // Suppress sign extension for the low bytes 19695 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19696 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19697 19698 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19699 19700 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19701 // already measured as the correct size. In API 23 and below, this 19702 // extra pass is required to make LinearLayout re-distribute weight. 19703 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19704 || heightMeasureSpec != mOldHeightMeasureSpec; 19705 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19706 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19707 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19708 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19709 final boolean needsLayout = specChanged 19710 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19711 19712 if (forceLayout || needsLayout) { 19713 // first clears the measured dimension flag 19714 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19715 19716 resolveRtlPropertiesIfNeeded(); 19717 19718 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19719 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19720 // measure ourselves, this should set the measured dimension flag back 19721 onMeasure(widthMeasureSpec, heightMeasureSpec); 19722 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19723 } else { 19724 long value = mMeasureCache.valueAt(cacheIndex); 19725 // Casting a long to int drops the high 32 bits, no mask needed 19726 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19727 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19728 } 19729 19730 // flag not set, setMeasuredDimension() was not invoked, we raise 19731 // an exception to warn the developer 19732 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19733 throw new IllegalStateException("View with id " + getId() + ": " 19734 + getClass().getName() + "#onMeasure() did not set the" 19735 + " measured dimension by calling" 19736 + " setMeasuredDimension()"); 19737 } 19738 19739 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19740 } 19741 19742 mOldWidthMeasureSpec = widthMeasureSpec; 19743 mOldHeightMeasureSpec = heightMeasureSpec; 19744 19745 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19746 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19747 } 19748 19749 /** 19750 * <p> 19751 * Measure the view and its content to determine the measured width and the 19752 * measured height. This method is invoked by {@link #measure(int, int)} and 19753 * should be overridden by subclasses to provide accurate and efficient 19754 * measurement of their contents. 19755 * </p> 19756 * 19757 * <p> 19758 * <strong>CONTRACT:</strong> When overriding this method, you 19759 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19760 * measured width and height of this view. Failure to do so will trigger an 19761 * <code>IllegalStateException</code>, thrown by 19762 * {@link #measure(int, int)}. Calling the superclass' 19763 * {@link #onMeasure(int, int)} is a valid use. 19764 * </p> 19765 * 19766 * <p> 19767 * The base class implementation of measure defaults to the background size, 19768 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19769 * override {@link #onMeasure(int, int)} to provide better measurements of 19770 * their content. 19771 * </p> 19772 * 19773 * <p> 19774 * If this method is overridden, it is the subclass's responsibility to make 19775 * sure the measured height and width are at least the view's minimum height 19776 * and width ({@link #getSuggestedMinimumHeight()} and 19777 * {@link #getSuggestedMinimumWidth()}). 19778 * </p> 19779 * 19780 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19781 * The requirements are encoded with 19782 * {@link android.view.View.MeasureSpec}. 19783 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19784 * The requirements are encoded with 19785 * {@link android.view.View.MeasureSpec}. 19786 * 19787 * @see #getMeasuredWidth() 19788 * @see #getMeasuredHeight() 19789 * @see #setMeasuredDimension(int, int) 19790 * @see #getSuggestedMinimumHeight() 19791 * @see #getSuggestedMinimumWidth() 19792 * @see android.view.View.MeasureSpec#getMode(int) 19793 * @see android.view.View.MeasureSpec#getSize(int) 19794 */ 19795 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19796 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19797 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19798 } 19799 19800 /** 19801 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19802 * measured width and measured height. Failing to do so will trigger an 19803 * exception at measurement time.</p> 19804 * 19805 * @param measuredWidth The measured width of this view. May be a complex 19806 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19807 * {@link #MEASURED_STATE_TOO_SMALL}. 19808 * @param measuredHeight The measured height of this view. May be a complex 19809 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19810 * {@link #MEASURED_STATE_TOO_SMALL}. 19811 */ 19812 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19813 boolean optical = isLayoutModeOptical(this); 19814 if (optical != isLayoutModeOptical(mParent)) { 19815 Insets insets = getOpticalInsets(); 19816 int opticalWidth = insets.left + insets.right; 19817 int opticalHeight = insets.top + insets.bottom; 19818 19819 measuredWidth += optical ? opticalWidth : -opticalWidth; 19820 measuredHeight += optical ? opticalHeight : -opticalHeight; 19821 } 19822 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19823 } 19824 19825 /** 19826 * Sets the measured dimension without extra processing for things like optical bounds. 19827 * Useful for reapplying consistent values that have already been cooked with adjustments 19828 * for optical bounds, etc. such as those from the measurement cache. 19829 * 19830 * @param measuredWidth The measured width of this view. May be a complex 19831 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19832 * {@link #MEASURED_STATE_TOO_SMALL}. 19833 * @param measuredHeight The measured height of this view. May be a complex 19834 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19835 * {@link #MEASURED_STATE_TOO_SMALL}. 19836 */ 19837 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19838 mMeasuredWidth = measuredWidth; 19839 mMeasuredHeight = measuredHeight; 19840 19841 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19842 } 19843 19844 /** 19845 * Merge two states as returned by {@link #getMeasuredState()}. 19846 * @param curState The current state as returned from a view or the result 19847 * of combining multiple views. 19848 * @param newState The new view state to combine. 19849 * @return Returns a new integer reflecting the combination of the two 19850 * states. 19851 */ 19852 public static int combineMeasuredStates(int curState, int newState) { 19853 return curState | newState; 19854 } 19855 19856 /** 19857 * Version of {@link #resolveSizeAndState(int, int, int)} 19858 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19859 */ 19860 public static int resolveSize(int size, int measureSpec) { 19861 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19862 } 19863 19864 /** 19865 * Utility to reconcile a desired size and state, with constraints imposed 19866 * by a MeasureSpec. Will take the desired size, unless a different size 19867 * is imposed by the constraints. The returned value is a compound integer, 19868 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19869 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19870 * resulting size is smaller than the size the view wants to be. 19871 * 19872 * @param size How big the view wants to be. 19873 * @param measureSpec Constraints imposed by the parent. 19874 * @param childMeasuredState Size information bit mask for the view's 19875 * children. 19876 * @return Size information bit mask as defined by 19877 * {@link #MEASURED_SIZE_MASK} and 19878 * {@link #MEASURED_STATE_TOO_SMALL}. 19879 */ 19880 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19881 final int specMode = MeasureSpec.getMode(measureSpec); 19882 final int specSize = MeasureSpec.getSize(measureSpec); 19883 final int result; 19884 switch (specMode) { 19885 case MeasureSpec.AT_MOST: 19886 if (specSize < size) { 19887 result = specSize | MEASURED_STATE_TOO_SMALL; 19888 } else { 19889 result = size; 19890 } 19891 break; 19892 case MeasureSpec.EXACTLY: 19893 result = specSize; 19894 break; 19895 case MeasureSpec.UNSPECIFIED: 19896 default: 19897 result = size; 19898 } 19899 return result | (childMeasuredState & MEASURED_STATE_MASK); 19900 } 19901 19902 /** 19903 * Utility to return a default size. Uses the supplied size if the 19904 * MeasureSpec imposed no constraints. Will get larger if allowed 19905 * by the MeasureSpec. 19906 * 19907 * @param size Default size for this view 19908 * @param measureSpec Constraints imposed by the parent 19909 * @return The size this view should be. 19910 */ 19911 public static int getDefaultSize(int size, int measureSpec) { 19912 int result = size; 19913 int specMode = MeasureSpec.getMode(measureSpec); 19914 int specSize = MeasureSpec.getSize(measureSpec); 19915 19916 switch (specMode) { 19917 case MeasureSpec.UNSPECIFIED: 19918 result = size; 19919 break; 19920 case MeasureSpec.AT_MOST: 19921 case MeasureSpec.EXACTLY: 19922 result = specSize; 19923 break; 19924 } 19925 return result; 19926 } 19927 19928 /** 19929 * Returns the suggested minimum height that the view should use. This 19930 * returns the maximum of the view's minimum height 19931 * and the background's minimum height 19932 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19933 * <p> 19934 * When being used in {@link #onMeasure(int, int)}, the caller should still 19935 * ensure the returned height is within the requirements of the parent. 19936 * 19937 * @return The suggested minimum height of the view. 19938 */ 19939 protected int getSuggestedMinimumHeight() { 19940 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19941 19942 } 19943 19944 /** 19945 * Returns the suggested minimum width that the view should use. This 19946 * returns the maximum of the view's minimum width 19947 * and the background's minimum width 19948 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19949 * <p> 19950 * When being used in {@link #onMeasure(int, int)}, the caller should still 19951 * ensure the returned width is within the requirements of the parent. 19952 * 19953 * @return The suggested minimum width of the view. 19954 */ 19955 protected int getSuggestedMinimumWidth() { 19956 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19957 } 19958 19959 /** 19960 * Returns the minimum height of the view. 19961 * 19962 * @return the minimum height the view will try to be. 19963 * 19964 * @see #setMinimumHeight(int) 19965 * 19966 * @attr ref android.R.styleable#View_minHeight 19967 */ 19968 public int getMinimumHeight() { 19969 return mMinHeight; 19970 } 19971 19972 /** 19973 * Sets the minimum height of the view. It is not guaranteed the view will 19974 * be able to achieve this minimum height (for example, if its parent layout 19975 * constrains it with less available height). 19976 * 19977 * @param minHeight The minimum height the view will try to be. 19978 * 19979 * @see #getMinimumHeight() 19980 * 19981 * @attr ref android.R.styleable#View_minHeight 19982 */ 19983 @RemotableViewMethod 19984 public void setMinimumHeight(int minHeight) { 19985 mMinHeight = minHeight; 19986 requestLayout(); 19987 } 19988 19989 /** 19990 * Returns the minimum width of the view. 19991 * 19992 * @return the minimum width the view will try to be. 19993 * 19994 * @see #setMinimumWidth(int) 19995 * 19996 * @attr ref android.R.styleable#View_minWidth 19997 */ 19998 public int getMinimumWidth() { 19999 return mMinWidth; 20000 } 20001 20002 /** 20003 * Sets the minimum width of the view. It is not guaranteed the view will 20004 * be able to achieve this minimum width (for example, if its parent layout 20005 * constrains it with less available width). 20006 * 20007 * @param minWidth The minimum width the view will try to be. 20008 * 20009 * @see #getMinimumWidth() 20010 * 20011 * @attr ref android.R.styleable#View_minWidth 20012 */ 20013 public void setMinimumWidth(int minWidth) { 20014 mMinWidth = minWidth; 20015 requestLayout(); 20016 20017 } 20018 20019 /** 20020 * Get the animation currently associated with this view. 20021 * 20022 * @return The animation that is currently playing or 20023 * scheduled to play for this view. 20024 */ 20025 public Animation getAnimation() { 20026 return mCurrentAnimation; 20027 } 20028 20029 /** 20030 * Start the specified animation now. 20031 * 20032 * @param animation the animation to start now 20033 */ 20034 public void startAnimation(Animation animation) { 20035 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 20036 setAnimation(animation); 20037 invalidateParentCaches(); 20038 invalidate(true); 20039 } 20040 20041 /** 20042 * Cancels any animations for this view. 20043 */ 20044 public void clearAnimation() { 20045 if (mCurrentAnimation != null) { 20046 mCurrentAnimation.detach(); 20047 } 20048 mCurrentAnimation = null; 20049 invalidateParentIfNeeded(); 20050 } 20051 20052 /** 20053 * Sets the next animation to play for this view. 20054 * If you want the animation to play immediately, use 20055 * {@link #startAnimation(android.view.animation.Animation)} instead. 20056 * This method provides allows fine-grained 20057 * control over the start time and invalidation, but you 20058 * must make sure that 1) the animation has a start time set, and 20059 * 2) the view's parent (which controls animations on its children) 20060 * will be invalidated when the animation is supposed to 20061 * start. 20062 * 20063 * @param animation The next animation, or null. 20064 */ 20065 public void setAnimation(Animation animation) { 20066 mCurrentAnimation = animation; 20067 20068 if (animation != null) { 20069 // If the screen is off assume the animation start time is now instead of 20070 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 20071 // would cause the animation to start when the screen turns back on 20072 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 20073 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 20074 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 20075 } 20076 animation.reset(); 20077 } 20078 } 20079 20080 /** 20081 * Invoked by a parent ViewGroup to notify the start of the animation 20082 * currently associated with this view. If you override this method, 20083 * always call super.onAnimationStart(); 20084 * 20085 * @see #setAnimation(android.view.animation.Animation) 20086 * @see #getAnimation() 20087 */ 20088 @CallSuper 20089 protected void onAnimationStart() { 20090 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 20091 } 20092 20093 /** 20094 * Invoked by a parent ViewGroup to notify the end of the animation 20095 * currently associated with this view. If you override this method, 20096 * always call super.onAnimationEnd(); 20097 * 20098 * @see #setAnimation(android.view.animation.Animation) 20099 * @see #getAnimation() 20100 */ 20101 @CallSuper 20102 protected void onAnimationEnd() { 20103 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 20104 } 20105 20106 /** 20107 * Invoked if there is a Transform that involves alpha. Subclass that can 20108 * draw themselves with the specified alpha should return true, and then 20109 * respect that alpha when their onDraw() is called. If this returns false 20110 * then the view may be redirected to draw into an offscreen buffer to 20111 * fulfill the request, which will look fine, but may be slower than if the 20112 * subclass handles it internally. The default implementation returns false. 20113 * 20114 * @param alpha The alpha (0..255) to apply to the view's drawing 20115 * @return true if the view can draw with the specified alpha. 20116 */ 20117 protected boolean onSetAlpha(int alpha) { 20118 return false; 20119 } 20120 20121 /** 20122 * This is used by the RootView to perform an optimization when 20123 * the view hierarchy contains one or several SurfaceView. 20124 * SurfaceView is always considered transparent, but its children are not, 20125 * therefore all View objects remove themselves from the global transparent 20126 * region (passed as a parameter to this function). 20127 * 20128 * @param region The transparent region for this ViewAncestor (window). 20129 * 20130 * @return Returns true if the effective visibility of the view at this 20131 * point is opaque, regardless of the transparent region; returns false 20132 * if it is possible for underlying windows to be seen behind the view. 20133 * 20134 * {@hide} 20135 */ 20136 public boolean gatherTransparentRegion(Region region) { 20137 final AttachInfo attachInfo = mAttachInfo; 20138 if (region != null && attachInfo != null) { 20139 final int pflags = mPrivateFlags; 20140 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 20141 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 20142 // remove it from the transparent region. 20143 final int[] location = attachInfo.mTransparentLocation; 20144 getLocationInWindow(location); 20145 region.op(location[0], location[1], location[0] + mRight - mLeft, 20146 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 20147 } else { 20148 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 20149 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 20150 // the background drawable's non-transparent parts from this transparent region. 20151 applyDrawableToTransparentRegion(mBackground, region); 20152 } 20153 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20154 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 20155 // Similarly, we remove the foreground drawable's non-transparent parts. 20156 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 20157 } 20158 } 20159 } 20160 return true; 20161 } 20162 20163 /** 20164 * Play a sound effect for this view. 20165 * 20166 * <p>The framework will play sound effects for some built in actions, such as 20167 * clicking, but you may wish to play these effects in your widget, 20168 * for instance, for internal navigation. 20169 * 20170 * <p>The sound effect will only be played if sound effects are enabled by the user, and 20171 * {@link #isSoundEffectsEnabled()} is true. 20172 * 20173 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 20174 */ 20175 public void playSoundEffect(int soundConstant) { 20176 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 20177 return; 20178 } 20179 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 20180 } 20181 20182 /** 20183 * BZZZTT!!1! 20184 * 20185 * <p>Provide haptic feedback to the user for this view. 20186 * 20187 * <p>The framework will provide haptic feedback for some built in actions, 20188 * such as long presses, but you may wish to provide feedback for your 20189 * own widget. 20190 * 20191 * <p>The feedback will only be performed if 20192 * {@link #isHapticFeedbackEnabled()} is true. 20193 * 20194 * @param feedbackConstant One of the constants defined in 20195 * {@link HapticFeedbackConstants} 20196 */ 20197 public boolean performHapticFeedback(int feedbackConstant) { 20198 return performHapticFeedback(feedbackConstant, 0); 20199 } 20200 20201 /** 20202 * BZZZTT!!1! 20203 * 20204 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 20205 * 20206 * @param feedbackConstant One of the constants defined in 20207 * {@link HapticFeedbackConstants} 20208 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 20209 */ 20210 public boolean performHapticFeedback(int feedbackConstant, int flags) { 20211 if (mAttachInfo == null) { 20212 return false; 20213 } 20214 //noinspection SimplifiableIfStatement 20215 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20216 && !isHapticFeedbackEnabled()) { 20217 return false; 20218 } 20219 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20220 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20221 } 20222 20223 /** 20224 * Request that the visibility of the status bar or other screen/window 20225 * decorations be changed. 20226 * 20227 * <p>This method is used to put the over device UI into temporary modes 20228 * where the user's attention is focused more on the application content, 20229 * by dimming or hiding surrounding system affordances. This is typically 20230 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20231 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20232 * to be placed behind the action bar (and with these flags other system 20233 * affordances) so that smooth transitions between hiding and showing them 20234 * can be done. 20235 * 20236 * <p>Two representative examples of the use of system UI visibility is 20237 * implementing a content browsing application (like a magazine reader) 20238 * and a video playing application. 20239 * 20240 * <p>The first code shows a typical implementation of a View in a content 20241 * browsing application. In this implementation, the application goes 20242 * into a content-oriented mode by hiding the status bar and action bar, 20243 * and putting the navigation elements into lights out mode. The user can 20244 * then interact with content while in this mode. Such an application should 20245 * provide an easy way for the user to toggle out of the mode (such as to 20246 * check information in the status bar or access notifications). In the 20247 * implementation here, this is done simply by tapping on the content. 20248 * 20249 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20250 * content} 20251 * 20252 * <p>This second code sample shows a typical implementation of a View 20253 * in a video playing application. In this situation, while the video is 20254 * playing the application would like to go into a complete full-screen mode, 20255 * to use as much of the display as possible for the video. When in this state 20256 * the user can not interact with the application; the system intercepts 20257 * touching on the screen to pop the UI out of full screen mode. See 20258 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20259 * 20260 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20261 * content} 20262 * 20263 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20264 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20265 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20266 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20267 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20268 */ 20269 public void setSystemUiVisibility(int visibility) { 20270 if (visibility != mSystemUiVisibility) { 20271 mSystemUiVisibility = visibility; 20272 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20273 mParent.recomputeViewAttributes(this); 20274 } 20275 } 20276 } 20277 20278 /** 20279 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20280 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20281 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20282 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20283 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20284 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20285 */ 20286 public int getSystemUiVisibility() { 20287 return mSystemUiVisibility; 20288 } 20289 20290 /** 20291 * Returns the current system UI visibility that is currently set for 20292 * the entire window. This is the combination of the 20293 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20294 * views in the window. 20295 */ 20296 public int getWindowSystemUiVisibility() { 20297 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20298 } 20299 20300 /** 20301 * Override to find out when the window's requested system UI visibility 20302 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20303 * This is different from the callbacks received through 20304 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20305 * in that this is only telling you about the local request of the window, 20306 * not the actual values applied by the system. 20307 */ 20308 public void onWindowSystemUiVisibilityChanged(int visible) { 20309 } 20310 20311 /** 20312 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20313 * the view hierarchy. 20314 */ 20315 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20316 onWindowSystemUiVisibilityChanged(visible); 20317 } 20318 20319 /** 20320 * Set a listener to receive callbacks when the visibility of the system bar changes. 20321 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20322 */ 20323 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20324 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20325 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20326 mParent.recomputeViewAttributes(this); 20327 } 20328 } 20329 20330 /** 20331 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20332 * the view hierarchy. 20333 */ 20334 public void dispatchSystemUiVisibilityChanged(int visibility) { 20335 ListenerInfo li = mListenerInfo; 20336 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20337 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20338 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20339 } 20340 } 20341 20342 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20343 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20344 if (val != mSystemUiVisibility) { 20345 setSystemUiVisibility(val); 20346 return true; 20347 } 20348 return false; 20349 } 20350 20351 /** @hide */ 20352 public void setDisabledSystemUiVisibility(int flags) { 20353 if (mAttachInfo != null) { 20354 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20355 mAttachInfo.mDisabledSystemUiVisibility = flags; 20356 if (mParent != null) { 20357 mParent.recomputeViewAttributes(this); 20358 } 20359 } 20360 } 20361 } 20362 20363 /** 20364 * Creates an image that the system displays during the drag and drop 20365 * operation. This is called a "drag shadow". The default implementation 20366 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20367 * appearance as the given View. The default also positions the center of the drag shadow 20368 * directly under the touch point. If no View is provided (the constructor with no parameters 20369 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20370 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20371 * default is an invisible drag shadow. 20372 * <p> 20373 * You are not required to use the View you provide to the constructor as the basis of the 20374 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20375 * anything you want as the drag shadow. 20376 * </p> 20377 * <p> 20378 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20379 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20380 * size and position of the drag shadow. It uses this data to construct a 20381 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20382 * so that your application can draw the shadow image in the Canvas. 20383 * </p> 20384 * 20385 * <div class="special reference"> 20386 * <h3>Developer Guides</h3> 20387 * <p>For a guide to implementing drag and drop features, read the 20388 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20389 * </div> 20390 */ 20391 public static class DragShadowBuilder { 20392 private final WeakReference<View> mView; 20393 20394 /** 20395 * Constructs a shadow image builder based on a View. By default, the resulting drag 20396 * shadow will have the same appearance and dimensions as the View, with the touch point 20397 * over the center of the View. 20398 * @param view A View. Any View in scope can be used. 20399 */ 20400 public DragShadowBuilder(View view) { 20401 mView = new WeakReference<View>(view); 20402 } 20403 20404 /** 20405 * Construct a shadow builder object with no associated View. This 20406 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20407 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20408 * to supply the drag shadow's dimensions and appearance without 20409 * reference to any View object. If they are not overridden, then the result is an 20410 * invisible drag shadow. 20411 */ 20412 public DragShadowBuilder() { 20413 mView = new WeakReference<View>(null); 20414 } 20415 20416 /** 20417 * Returns the View object that had been passed to the 20418 * {@link #View.DragShadowBuilder(View)} 20419 * constructor. If that View parameter was {@code null} or if the 20420 * {@link #View.DragShadowBuilder()} 20421 * constructor was used to instantiate the builder object, this method will return 20422 * null. 20423 * 20424 * @return The View object associate with this builder object. 20425 */ 20426 @SuppressWarnings({"JavadocReference"}) 20427 final public View getView() { 20428 return mView.get(); 20429 } 20430 20431 /** 20432 * Provides the metrics for the shadow image. These include the dimensions of 20433 * the shadow image, and the point within that shadow that should 20434 * be centered under the touch location while dragging. 20435 * <p> 20436 * The default implementation sets the dimensions of the shadow to be the 20437 * same as the dimensions of the View itself and centers the shadow under 20438 * the touch point. 20439 * </p> 20440 * 20441 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 20442 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20443 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20444 * image. 20445 * 20446 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 20447 * shadow image that should be underneath the touch point during the drag and drop 20448 * operation. Your application must set {@link android.graphics.Point#x} to the 20449 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20450 */ 20451 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 20452 final View view = mView.get(); 20453 if (view != null) { 20454 outShadowSize.set(view.getWidth(), view.getHeight()); 20455 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 20456 } else { 20457 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20458 } 20459 } 20460 20461 /** 20462 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20463 * based on the dimensions it received from the 20464 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20465 * 20466 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20467 */ 20468 public void onDrawShadow(Canvas canvas) { 20469 final View view = mView.get(); 20470 if (view != null) { 20471 view.draw(canvas); 20472 } else { 20473 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20474 } 20475 } 20476 } 20477 20478 /** 20479 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20480 * startDragAndDrop()} for newer platform versions. 20481 */ 20482 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20483 Object myLocalState, int flags) { 20484 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20485 } 20486 20487 /** 20488 * Starts a drag and drop operation. When your application calls this method, it passes a 20489 * {@link android.view.View.DragShadowBuilder} object to the system. The 20490 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20491 * to get metrics for the drag shadow, and then calls the object's 20492 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20493 * <p> 20494 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20495 * drag events to all the View objects in your application that are currently visible. It does 20496 * this either by calling the View object's drag listener (an implementation of 20497 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20498 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20499 * Both are passed a {@link android.view.DragEvent} object that has a 20500 * {@link android.view.DragEvent#getAction()} value of 20501 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20502 * </p> 20503 * <p> 20504 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20505 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20506 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20507 * to the View the user selected for dragging. 20508 * </p> 20509 * @param data A {@link android.content.ClipData} object pointing to the data to be 20510 * transferred by the drag and drop operation. 20511 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20512 * drag shadow. 20513 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20514 * drop operation. This Object is put into every DragEvent object sent by the system during the 20515 * current drag. 20516 * <p> 20517 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20518 * to the target Views. For example, it can contain flags that differentiate between a 20519 * a copy operation and a move operation. 20520 * </p> 20521 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 20522 * so the parameter should be set to 0. 20523 * @return {@code true} if the method completes successfully, or 20524 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20525 * do a drag, and so no drag operation is in progress. 20526 */ 20527 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20528 Object myLocalState, int flags) { 20529 if (ViewDebug.DEBUG_DRAG) { 20530 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20531 } 20532 boolean okay = false; 20533 20534 Point shadowSize = new Point(); 20535 Point shadowTouchPoint = new Point(); 20536 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20537 20538 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20539 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20540 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20541 } 20542 20543 if (ViewDebug.DEBUG_DRAG) { 20544 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20545 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20546 } 20547 if (mAttachInfo.mDragSurface != null) { 20548 mAttachInfo.mDragSurface.release(); 20549 } 20550 mAttachInfo.mDragSurface = new Surface(); 20551 try { 20552 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20553 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20554 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20555 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20556 if (mAttachInfo.mDragToken != null) { 20557 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20558 try { 20559 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20560 shadowBuilder.onDrawShadow(canvas); 20561 } finally { 20562 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20563 } 20564 20565 final ViewRootImpl root = getViewRootImpl(); 20566 20567 // Cache the local state object for delivery with DragEvents 20568 root.setLocalDragState(myLocalState); 20569 20570 // repurpose 'shadowSize' for the last touch point 20571 root.getLastTouchPoint(shadowSize); 20572 20573 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20574 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20575 shadowTouchPoint.x, shadowTouchPoint.y, data); 20576 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20577 } 20578 } catch (Exception e) { 20579 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20580 mAttachInfo.mDragSurface.destroy(); 20581 mAttachInfo.mDragSurface = null; 20582 } 20583 20584 return okay; 20585 } 20586 20587 /** 20588 * Cancels an ongoing drag and drop operation. 20589 * <p> 20590 * A {@link android.view.DragEvent} object with 20591 * {@link android.view.DragEvent#getAction()} value of 20592 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20593 * {@link android.view.DragEvent#getResult()} value of {@code false} 20594 * will be sent to every 20595 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20596 * even if they are not currently visible. 20597 * </p> 20598 * <p> 20599 * This method can be called on any View in the same window as the View on which 20600 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20601 * was called. 20602 * </p> 20603 */ 20604 public final void cancelDragAndDrop() { 20605 if (ViewDebug.DEBUG_DRAG) { 20606 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20607 } 20608 if (mAttachInfo.mDragToken != null) { 20609 try { 20610 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20611 } catch (Exception e) { 20612 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20613 } 20614 mAttachInfo.mDragToken = null; 20615 } else { 20616 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20617 } 20618 } 20619 20620 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20621 if (ViewDebug.DEBUG_DRAG) { 20622 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20623 } 20624 if (mAttachInfo.mDragToken != null) { 20625 try { 20626 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20627 try { 20628 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20629 shadowBuilder.onDrawShadow(canvas); 20630 } finally { 20631 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20632 } 20633 } catch (Exception e) { 20634 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20635 } 20636 } else { 20637 Log.e(VIEW_LOG_TAG, "No active drag"); 20638 } 20639 } 20640 20641 /** 20642 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20643 * between {startX, startY} and the new cursor positon. 20644 * @param startX horizontal coordinate where the move started. 20645 * @param startY vertical coordinate where the move started. 20646 * @return whether moving was started successfully. 20647 * @hide 20648 */ 20649 public final boolean startMovingTask(float startX, float startY) { 20650 if (ViewDebug.DEBUG_POSITIONING) { 20651 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20652 } 20653 try { 20654 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20655 } catch (RemoteException e) { 20656 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20657 } 20658 return false; 20659 } 20660 20661 /** 20662 * Handles drag events sent by the system following a call to 20663 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20664 * startDragAndDrop()}. 20665 *<p> 20666 * When the system calls this method, it passes a 20667 * {@link android.view.DragEvent} object. A call to 20668 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20669 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20670 * operation. 20671 * @param event The {@link android.view.DragEvent} sent by the system. 20672 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20673 * in DragEvent, indicating the type of drag event represented by this object. 20674 * @return {@code true} if the method was successful, otherwise {@code false}. 20675 * <p> 20676 * The method should return {@code true} in response to an action type of 20677 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20678 * operation. 20679 * </p> 20680 * <p> 20681 * The method should also return {@code true} in response to an action type of 20682 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20683 * {@code false} if it didn't. 20684 * </p> 20685 */ 20686 public boolean onDragEvent(DragEvent event) { 20687 return false; 20688 } 20689 20690 /** 20691 * Detects if this View is enabled and has a drag event listener. 20692 * If both are true, then it calls the drag event listener with the 20693 * {@link android.view.DragEvent} it received. If the drag event listener returns 20694 * {@code true}, then dispatchDragEvent() returns {@code true}. 20695 * <p> 20696 * For all other cases, the method calls the 20697 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20698 * method and returns its result. 20699 * </p> 20700 * <p> 20701 * This ensures that a drag event is always consumed, even if the View does not have a drag 20702 * event listener. However, if the View has a listener and the listener returns true, then 20703 * onDragEvent() is not called. 20704 * </p> 20705 */ 20706 public boolean dispatchDragEvent(DragEvent event) { 20707 ListenerInfo li = mListenerInfo; 20708 //noinspection SimplifiableIfStatement 20709 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20710 && li.mOnDragListener.onDrag(this, event)) { 20711 return true; 20712 } 20713 return onDragEvent(event); 20714 } 20715 20716 boolean canAcceptDrag() { 20717 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20718 } 20719 20720 /** 20721 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20722 * it is ever exposed at all. 20723 * @hide 20724 */ 20725 public void onCloseSystemDialogs(String reason) { 20726 } 20727 20728 /** 20729 * Given a Drawable whose bounds have been set to draw into this view, 20730 * update a Region being computed for 20731 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20732 * that any non-transparent parts of the Drawable are removed from the 20733 * given transparent region. 20734 * 20735 * @param dr The Drawable whose transparency is to be applied to the region. 20736 * @param region A Region holding the current transparency information, 20737 * where any parts of the region that are set are considered to be 20738 * transparent. On return, this region will be modified to have the 20739 * transparency information reduced by the corresponding parts of the 20740 * Drawable that are not transparent. 20741 * {@hide} 20742 */ 20743 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20744 if (DBG) { 20745 Log.i("View", "Getting transparent region for: " + this); 20746 } 20747 final Region r = dr.getTransparentRegion(); 20748 final Rect db = dr.getBounds(); 20749 final AttachInfo attachInfo = mAttachInfo; 20750 if (r != null && attachInfo != null) { 20751 final int w = getRight()-getLeft(); 20752 final int h = getBottom()-getTop(); 20753 if (db.left > 0) { 20754 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20755 r.op(0, 0, db.left, h, Region.Op.UNION); 20756 } 20757 if (db.right < w) { 20758 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20759 r.op(db.right, 0, w, h, Region.Op.UNION); 20760 } 20761 if (db.top > 0) { 20762 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20763 r.op(0, 0, w, db.top, Region.Op.UNION); 20764 } 20765 if (db.bottom < h) { 20766 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20767 r.op(0, db.bottom, w, h, Region.Op.UNION); 20768 } 20769 final int[] location = attachInfo.mTransparentLocation; 20770 getLocationInWindow(location); 20771 r.translate(location[0], location[1]); 20772 region.op(r, Region.Op.INTERSECT); 20773 } else { 20774 region.op(db, Region.Op.DIFFERENCE); 20775 } 20776 } 20777 20778 private void checkForLongClick(int delayOffset, float x, float y) { 20779 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20780 mHasPerformedLongPress = false; 20781 20782 if (mPendingCheckForLongPress == null) { 20783 mPendingCheckForLongPress = new CheckForLongPress(); 20784 } 20785 mPendingCheckForLongPress.setAnchor(x, y); 20786 mPendingCheckForLongPress.rememberWindowAttachCount(); 20787 postDelayed(mPendingCheckForLongPress, 20788 ViewConfiguration.getLongPressTimeout() - delayOffset); 20789 } 20790 } 20791 20792 /** 20793 * Inflate a view from an XML resource. This convenience method wraps the {@link 20794 * LayoutInflater} class, which provides a full range of options for view inflation. 20795 * 20796 * @param context The Context object for your activity or application. 20797 * @param resource The resource ID to inflate 20798 * @param root A view group that will be the parent. Used to properly inflate the 20799 * layout_* parameters. 20800 * @see LayoutInflater 20801 */ 20802 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20803 LayoutInflater factory = LayoutInflater.from(context); 20804 return factory.inflate(resource, root); 20805 } 20806 20807 /** 20808 * Scroll the view with standard behavior for scrolling beyond the normal 20809 * content boundaries. Views that call this method should override 20810 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 20811 * results of an over-scroll operation. 20812 * 20813 * Views can use this method to handle any touch or fling-based scrolling. 20814 * 20815 * @param deltaX Change in X in pixels 20816 * @param deltaY Change in Y in pixels 20817 * @param scrollX Current X scroll value in pixels before applying deltaX 20818 * @param scrollY Current Y scroll value in pixels before applying deltaY 20819 * @param scrollRangeX Maximum content scroll range along the X axis 20820 * @param scrollRangeY Maximum content scroll range along the Y axis 20821 * @param maxOverScrollX Number of pixels to overscroll by in either direction 20822 * along the X axis. 20823 * @param maxOverScrollY Number of pixels to overscroll by in either direction 20824 * along the Y axis. 20825 * @param isTouchEvent true if this scroll operation is the result of a touch event. 20826 * @return true if scrolling was clamped to an over-scroll boundary along either 20827 * axis, false otherwise. 20828 */ 20829 @SuppressWarnings({"UnusedParameters"}) 20830 protected boolean overScrollBy(int deltaX, int deltaY, 20831 int scrollX, int scrollY, 20832 int scrollRangeX, int scrollRangeY, 20833 int maxOverScrollX, int maxOverScrollY, 20834 boolean isTouchEvent) { 20835 final int overScrollMode = mOverScrollMode; 20836 final boolean canScrollHorizontal = 20837 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 20838 final boolean canScrollVertical = 20839 computeVerticalScrollRange() > computeVerticalScrollExtent(); 20840 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 20841 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 20842 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 20843 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 20844 20845 int newScrollX = scrollX + deltaX; 20846 if (!overScrollHorizontal) { 20847 maxOverScrollX = 0; 20848 } 20849 20850 int newScrollY = scrollY + deltaY; 20851 if (!overScrollVertical) { 20852 maxOverScrollY = 0; 20853 } 20854 20855 // Clamp values if at the limits and record 20856 final int left = -maxOverScrollX; 20857 final int right = maxOverScrollX + scrollRangeX; 20858 final int top = -maxOverScrollY; 20859 final int bottom = maxOverScrollY + scrollRangeY; 20860 20861 boolean clampedX = false; 20862 if (newScrollX > right) { 20863 newScrollX = right; 20864 clampedX = true; 20865 } else if (newScrollX < left) { 20866 newScrollX = left; 20867 clampedX = true; 20868 } 20869 20870 boolean clampedY = false; 20871 if (newScrollY > bottom) { 20872 newScrollY = bottom; 20873 clampedY = true; 20874 } else if (newScrollY < top) { 20875 newScrollY = top; 20876 clampedY = true; 20877 } 20878 20879 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 20880 20881 return clampedX || clampedY; 20882 } 20883 20884 /** 20885 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 20886 * respond to the results of an over-scroll operation. 20887 * 20888 * @param scrollX New X scroll value in pixels 20889 * @param scrollY New Y scroll value in pixels 20890 * @param clampedX True if scrollX was clamped to an over-scroll boundary 20891 * @param clampedY True if scrollY was clamped to an over-scroll boundary 20892 */ 20893 protected void onOverScrolled(int scrollX, int scrollY, 20894 boolean clampedX, boolean clampedY) { 20895 // Intentionally empty. 20896 } 20897 20898 /** 20899 * Returns the over-scroll mode for this view. The result will be 20900 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20901 * (allow over-scrolling only if the view content is larger than the container), 20902 * or {@link #OVER_SCROLL_NEVER}. 20903 * 20904 * @return This view's over-scroll mode. 20905 */ 20906 public int getOverScrollMode() { 20907 return mOverScrollMode; 20908 } 20909 20910 /** 20911 * Set the over-scroll mode for this view. Valid over-scroll modes are 20912 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20913 * (allow over-scrolling only if the view content is larger than the container), 20914 * or {@link #OVER_SCROLL_NEVER}. 20915 * 20916 * Setting the over-scroll mode of a view will have an effect only if the 20917 * view is capable of scrolling. 20918 * 20919 * @param overScrollMode The new over-scroll mode for this view. 20920 */ 20921 public void setOverScrollMode(int overScrollMode) { 20922 if (overScrollMode != OVER_SCROLL_ALWAYS && 20923 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 20924 overScrollMode != OVER_SCROLL_NEVER) { 20925 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 20926 } 20927 mOverScrollMode = overScrollMode; 20928 } 20929 20930 /** 20931 * Enable or disable nested scrolling for this view. 20932 * 20933 * <p>If this property is set to true the view will be permitted to initiate nested 20934 * scrolling operations with a compatible parent view in the current hierarchy. If this 20935 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 20936 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 20937 * the nested scroll.</p> 20938 * 20939 * @param enabled true to enable nested scrolling, false to disable 20940 * 20941 * @see #isNestedScrollingEnabled() 20942 */ 20943 public void setNestedScrollingEnabled(boolean enabled) { 20944 if (enabled) { 20945 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 20946 } else { 20947 stopNestedScroll(); 20948 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 20949 } 20950 } 20951 20952 /** 20953 * Returns true if nested scrolling is enabled for this view. 20954 * 20955 * <p>If nested scrolling is enabled and this View class implementation supports it, 20956 * this view will act as a nested scrolling child view when applicable, forwarding data 20957 * about the scroll operation in progress to a compatible and cooperating nested scrolling 20958 * parent.</p> 20959 * 20960 * @return true if nested scrolling is enabled 20961 * 20962 * @see #setNestedScrollingEnabled(boolean) 20963 */ 20964 public boolean isNestedScrollingEnabled() { 20965 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 20966 PFLAG3_NESTED_SCROLLING_ENABLED; 20967 } 20968 20969 /** 20970 * Begin a nestable scroll operation along the given axes. 20971 * 20972 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 20973 * 20974 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 20975 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 20976 * In the case of touch scrolling the nested scroll will be terminated automatically in 20977 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 20978 * In the event of programmatic scrolling the caller must explicitly call 20979 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 20980 * 20981 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 20982 * If it returns false the caller may ignore the rest of this contract until the next scroll. 20983 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 20984 * 20985 * <p>At each incremental step of the scroll the caller should invoke 20986 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 20987 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 20988 * parent at least partially consumed the scroll and the caller should adjust the amount it 20989 * scrolls by.</p> 20990 * 20991 * <p>After applying the remainder of the scroll delta the caller should invoke 20992 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 20993 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 20994 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 20995 * </p> 20996 * 20997 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 20998 * {@link #SCROLL_AXIS_VERTICAL}. 20999 * @return true if a cooperative parent was found and nested scrolling has been enabled for 21000 * the current gesture. 21001 * 21002 * @see #stopNestedScroll() 21003 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21004 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21005 */ 21006 public boolean startNestedScroll(int axes) { 21007 if (hasNestedScrollingParent()) { 21008 // Already in progress 21009 return true; 21010 } 21011 if (isNestedScrollingEnabled()) { 21012 ViewParent p = getParent(); 21013 View child = this; 21014 while (p != null) { 21015 try { 21016 if (p.onStartNestedScroll(child, this, axes)) { 21017 mNestedScrollingParent = p; 21018 p.onNestedScrollAccepted(child, this, axes); 21019 return true; 21020 } 21021 } catch (AbstractMethodError e) { 21022 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 21023 "method onStartNestedScroll", e); 21024 // Allow the search upward to continue 21025 } 21026 if (p instanceof View) { 21027 child = (View) p; 21028 } 21029 p = p.getParent(); 21030 } 21031 } 21032 return false; 21033 } 21034 21035 /** 21036 * Stop a nested scroll in progress. 21037 * 21038 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 21039 * 21040 * @see #startNestedScroll(int) 21041 */ 21042 public void stopNestedScroll() { 21043 if (mNestedScrollingParent != null) { 21044 mNestedScrollingParent.onStopNestedScroll(this); 21045 mNestedScrollingParent = null; 21046 } 21047 } 21048 21049 /** 21050 * Returns true if this view has a nested scrolling parent. 21051 * 21052 * <p>The presence of a nested scrolling parent indicates that this view has initiated 21053 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 21054 * 21055 * @return whether this view has a nested scrolling parent 21056 */ 21057 public boolean hasNestedScrollingParent() { 21058 return mNestedScrollingParent != null; 21059 } 21060 21061 /** 21062 * Dispatch one step of a nested scroll in progress. 21063 * 21064 * <p>Implementations of views that support nested scrolling should call this to report 21065 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 21066 * is not currently in progress or nested scrolling is not 21067 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 21068 * 21069 * <p>Compatible View implementations should also call 21070 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 21071 * consuming a component of the scroll event themselves.</p> 21072 * 21073 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 21074 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 21075 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 21076 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 21077 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21078 * in local view coordinates of this view from before this operation 21079 * to after it completes. View implementations may use this to adjust 21080 * expected input coordinate tracking. 21081 * @return true if the event was dispatched, false if it could not be dispatched. 21082 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 21083 */ 21084 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 21085 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 21086 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21087 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 21088 int startX = 0; 21089 int startY = 0; 21090 if (offsetInWindow != null) { 21091 getLocationInWindow(offsetInWindow); 21092 startX = offsetInWindow[0]; 21093 startY = offsetInWindow[1]; 21094 } 21095 21096 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 21097 dxUnconsumed, dyUnconsumed); 21098 21099 if (offsetInWindow != null) { 21100 getLocationInWindow(offsetInWindow); 21101 offsetInWindow[0] -= startX; 21102 offsetInWindow[1] -= startY; 21103 } 21104 return true; 21105 } else if (offsetInWindow != null) { 21106 // No motion, no dispatch. Keep offsetInWindow up to date. 21107 offsetInWindow[0] = 0; 21108 offsetInWindow[1] = 0; 21109 } 21110 } 21111 return false; 21112 } 21113 21114 /** 21115 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 21116 * 21117 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 21118 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 21119 * scrolling operation to consume some or all of the scroll operation before the child view 21120 * consumes it.</p> 21121 * 21122 * @param dx Horizontal scroll distance in pixels 21123 * @param dy Vertical scroll distance in pixels 21124 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 21125 * and consumed[1] the consumed dy. 21126 * @param offsetInWindow Optional. If not null, on return this will contain the offset 21127 * in local view coordinates of this view from before this operation 21128 * to after it completes. View implementations may use this to adjust 21129 * expected input coordinate tracking. 21130 * @return true if the parent consumed some or all of the scroll delta 21131 * @see #dispatchNestedScroll(int, int, int, int, int[]) 21132 */ 21133 public boolean dispatchNestedPreScroll(int dx, int dy, 21134 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 21135 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21136 if (dx != 0 || dy != 0) { 21137 int startX = 0; 21138 int startY = 0; 21139 if (offsetInWindow != null) { 21140 getLocationInWindow(offsetInWindow); 21141 startX = offsetInWindow[0]; 21142 startY = offsetInWindow[1]; 21143 } 21144 21145 if (consumed == null) { 21146 if (mTempNestedScrollConsumed == null) { 21147 mTempNestedScrollConsumed = new int[2]; 21148 } 21149 consumed = mTempNestedScrollConsumed; 21150 } 21151 consumed[0] = 0; 21152 consumed[1] = 0; 21153 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 21154 21155 if (offsetInWindow != null) { 21156 getLocationInWindow(offsetInWindow); 21157 offsetInWindow[0] -= startX; 21158 offsetInWindow[1] -= startY; 21159 } 21160 return consumed[0] != 0 || consumed[1] != 0; 21161 } else if (offsetInWindow != null) { 21162 offsetInWindow[0] = 0; 21163 offsetInWindow[1] = 0; 21164 } 21165 } 21166 return false; 21167 } 21168 21169 /** 21170 * Dispatch a fling to a nested scrolling parent. 21171 * 21172 * <p>This method should be used to indicate that a nested scrolling child has detected 21173 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 21174 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 21175 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 21176 * along a scrollable axis.</p> 21177 * 21178 * <p>If a nested scrolling child view would normally fling but it is at the edge of 21179 * its own content, it can use this method to delegate the fling to its nested scrolling 21180 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 21181 * 21182 * @param velocityX Horizontal fling velocity in pixels per second 21183 * @param velocityY Vertical fling velocity in pixels per second 21184 * @param consumed true if the child consumed the fling, false otherwise 21185 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 21186 */ 21187 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 21188 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21189 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 21190 } 21191 return false; 21192 } 21193 21194 /** 21195 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 21196 * 21197 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 21198 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 21199 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 21200 * before the child view consumes it. If this method returns <code>true</code>, a nested 21201 * parent view consumed the fling and this view should not scroll as a result.</p> 21202 * 21203 * <p>For a better user experience, only one view in a nested scrolling chain should consume 21204 * the fling at a time. If a parent view consumed the fling this method will return false. 21205 * Custom view implementations should account for this in two ways:</p> 21206 * 21207 * <ul> 21208 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 21209 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 21210 * position regardless.</li> 21211 * <li>If a nested parent does consume the fling, this view should not scroll at all, 21212 * even to settle back to a valid idle position.</li> 21213 * </ul> 21214 * 21215 * <p>Views should also not offer fling velocities to nested parent views along an axis 21216 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21217 * should not offer a horizontal fling velocity to its parents since scrolling along that 21218 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21219 * 21220 * @param velocityX Horizontal fling velocity in pixels per second 21221 * @param velocityY Vertical fling velocity in pixels per second 21222 * @return true if a nested scrolling parent consumed the fling 21223 */ 21224 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21225 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21226 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21227 } 21228 return false; 21229 } 21230 21231 /** 21232 * Gets a scale factor that determines the distance the view should scroll 21233 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21234 * @return The vertical scroll scale factor. 21235 * @hide 21236 */ 21237 protected float getVerticalScrollFactor() { 21238 if (mVerticalScrollFactor == 0) { 21239 TypedValue outValue = new TypedValue(); 21240 if (!mContext.getTheme().resolveAttribute( 21241 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21242 throw new IllegalStateException( 21243 "Expected theme to define listPreferredItemHeight."); 21244 } 21245 mVerticalScrollFactor = outValue.getDimension( 21246 mContext.getResources().getDisplayMetrics()); 21247 } 21248 return mVerticalScrollFactor; 21249 } 21250 21251 /** 21252 * Gets a scale factor that determines the distance the view should scroll 21253 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21254 * @return The horizontal scroll scale factor. 21255 * @hide 21256 */ 21257 protected float getHorizontalScrollFactor() { 21258 // TODO: Should use something else. 21259 return getVerticalScrollFactor(); 21260 } 21261 21262 /** 21263 * Return the value specifying the text direction or policy that was set with 21264 * {@link #setTextDirection(int)}. 21265 * 21266 * @return the defined text direction. It can be one of: 21267 * 21268 * {@link #TEXT_DIRECTION_INHERIT}, 21269 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21270 * {@link #TEXT_DIRECTION_ANY_RTL}, 21271 * {@link #TEXT_DIRECTION_LTR}, 21272 * {@link #TEXT_DIRECTION_RTL}, 21273 * {@link #TEXT_DIRECTION_LOCALE}, 21274 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21275 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21276 * 21277 * @attr ref android.R.styleable#View_textDirection 21278 * 21279 * @hide 21280 */ 21281 @ViewDebug.ExportedProperty(category = "text", mapping = { 21282 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21283 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21284 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21285 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21286 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21287 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21288 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21289 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21290 }) 21291 public int getRawTextDirection() { 21292 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21293 } 21294 21295 /** 21296 * Set the text direction. 21297 * 21298 * @param textDirection the direction to set. Should be one of: 21299 * 21300 * {@link #TEXT_DIRECTION_INHERIT}, 21301 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21302 * {@link #TEXT_DIRECTION_ANY_RTL}, 21303 * {@link #TEXT_DIRECTION_LTR}, 21304 * {@link #TEXT_DIRECTION_RTL}, 21305 * {@link #TEXT_DIRECTION_LOCALE} 21306 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21307 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21308 * 21309 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21310 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21311 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21312 * 21313 * @attr ref android.R.styleable#View_textDirection 21314 */ 21315 public void setTextDirection(int textDirection) { 21316 if (getRawTextDirection() != textDirection) { 21317 // Reset the current text direction and the resolved one 21318 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21319 resetResolvedTextDirection(); 21320 // Set the new text direction 21321 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21322 // Do resolution 21323 resolveTextDirection(); 21324 // Notify change 21325 onRtlPropertiesChanged(getLayoutDirection()); 21326 // Refresh 21327 requestLayout(); 21328 invalidate(true); 21329 } 21330 } 21331 21332 /** 21333 * Return the resolved text direction. 21334 * 21335 * @return the resolved text direction. Returns one of: 21336 * 21337 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21338 * {@link #TEXT_DIRECTION_ANY_RTL}, 21339 * {@link #TEXT_DIRECTION_LTR}, 21340 * {@link #TEXT_DIRECTION_RTL}, 21341 * {@link #TEXT_DIRECTION_LOCALE}, 21342 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21343 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21344 * 21345 * @attr ref android.R.styleable#View_textDirection 21346 */ 21347 @ViewDebug.ExportedProperty(category = "text", mapping = { 21348 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21349 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21350 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21351 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21352 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21353 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21354 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21355 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21356 }) 21357 public int getTextDirection() { 21358 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21359 } 21360 21361 /** 21362 * Resolve the text direction. 21363 * 21364 * @return true if resolution has been done, false otherwise. 21365 * 21366 * @hide 21367 */ 21368 public boolean resolveTextDirection() { 21369 // Reset any previous text direction resolution 21370 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21371 21372 if (hasRtlSupport()) { 21373 // Set resolved text direction flag depending on text direction flag 21374 final int textDirection = getRawTextDirection(); 21375 switch(textDirection) { 21376 case TEXT_DIRECTION_INHERIT: 21377 if (!canResolveTextDirection()) { 21378 // We cannot do the resolution if there is no parent, so use the default one 21379 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21380 // Resolution will need to happen again later 21381 return false; 21382 } 21383 21384 // Parent has not yet resolved, so we still return the default 21385 try { 21386 if (!mParent.isTextDirectionResolved()) { 21387 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21388 // Resolution will need to happen again later 21389 return false; 21390 } 21391 } catch (AbstractMethodError e) { 21392 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21393 " does not fully implement ViewParent", e); 21394 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21395 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21396 return true; 21397 } 21398 21399 // Set current resolved direction to the same value as the parent's one 21400 int parentResolvedDirection; 21401 try { 21402 parentResolvedDirection = mParent.getTextDirection(); 21403 } catch (AbstractMethodError e) { 21404 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21405 " does not fully implement ViewParent", e); 21406 parentResolvedDirection = TEXT_DIRECTION_LTR; 21407 } 21408 switch (parentResolvedDirection) { 21409 case TEXT_DIRECTION_FIRST_STRONG: 21410 case TEXT_DIRECTION_ANY_RTL: 21411 case TEXT_DIRECTION_LTR: 21412 case TEXT_DIRECTION_RTL: 21413 case TEXT_DIRECTION_LOCALE: 21414 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21415 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21416 mPrivateFlags2 |= 21417 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21418 break; 21419 default: 21420 // Default resolved direction is "first strong" heuristic 21421 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21422 } 21423 break; 21424 case TEXT_DIRECTION_FIRST_STRONG: 21425 case TEXT_DIRECTION_ANY_RTL: 21426 case TEXT_DIRECTION_LTR: 21427 case TEXT_DIRECTION_RTL: 21428 case TEXT_DIRECTION_LOCALE: 21429 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21430 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21431 // Resolved direction is the same as text direction 21432 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21433 break; 21434 default: 21435 // Default resolved direction is "first strong" heuristic 21436 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21437 } 21438 } else { 21439 // Default resolved direction is "first strong" heuristic 21440 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21441 } 21442 21443 // Set to resolved 21444 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21445 return true; 21446 } 21447 21448 /** 21449 * Check if text direction resolution can be done. 21450 * 21451 * @return true if text direction resolution can be done otherwise return false. 21452 */ 21453 public boolean canResolveTextDirection() { 21454 switch (getRawTextDirection()) { 21455 case TEXT_DIRECTION_INHERIT: 21456 if (mParent != null) { 21457 try { 21458 return mParent.canResolveTextDirection(); 21459 } catch (AbstractMethodError e) { 21460 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21461 " does not fully implement ViewParent", e); 21462 } 21463 } 21464 return false; 21465 21466 default: 21467 return true; 21468 } 21469 } 21470 21471 /** 21472 * Reset resolved text direction. Text direction will be resolved during a call to 21473 * {@link #onMeasure(int, int)}. 21474 * 21475 * @hide 21476 */ 21477 public void resetResolvedTextDirection() { 21478 // Reset any previous text direction resolution 21479 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21480 // Set to default value 21481 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21482 } 21483 21484 /** 21485 * @return true if text direction is inherited. 21486 * 21487 * @hide 21488 */ 21489 public boolean isTextDirectionInherited() { 21490 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21491 } 21492 21493 /** 21494 * @return true if text direction is resolved. 21495 */ 21496 public boolean isTextDirectionResolved() { 21497 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21498 } 21499 21500 /** 21501 * Return the value specifying the text alignment or policy that was set with 21502 * {@link #setTextAlignment(int)}. 21503 * 21504 * @return the defined text alignment. It can be one of: 21505 * 21506 * {@link #TEXT_ALIGNMENT_INHERIT}, 21507 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21508 * {@link #TEXT_ALIGNMENT_CENTER}, 21509 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21510 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21511 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21512 * {@link #TEXT_ALIGNMENT_VIEW_END} 21513 * 21514 * @attr ref android.R.styleable#View_textAlignment 21515 * 21516 * @hide 21517 */ 21518 @ViewDebug.ExportedProperty(category = "text", mapping = { 21519 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21520 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21521 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21522 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21523 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21524 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21525 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21526 }) 21527 @TextAlignment 21528 public int getRawTextAlignment() { 21529 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21530 } 21531 21532 /** 21533 * Set the text alignment. 21534 * 21535 * @param textAlignment The text alignment to set. Should be one of 21536 * 21537 * {@link #TEXT_ALIGNMENT_INHERIT}, 21538 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21539 * {@link #TEXT_ALIGNMENT_CENTER}, 21540 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21541 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21542 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21543 * {@link #TEXT_ALIGNMENT_VIEW_END} 21544 * 21545 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21546 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21547 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21548 * 21549 * @attr ref android.R.styleable#View_textAlignment 21550 */ 21551 public void setTextAlignment(@TextAlignment int textAlignment) { 21552 if (textAlignment != getRawTextAlignment()) { 21553 // Reset the current and resolved text alignment 21554 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21555 resetResolvedTextAlignment(); 21556 // Set the new text alignment 21557 mPrivateFlags2 |= 21558 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21559 // Do resolution 21560 resolveTextAlignment(); 21561 // Notify change 21562 onRtlPropertiesChanged(getLayoutDirection()); 21563 // Refresh 21564 requestLayout(); 21565 invalidate(true); 21566 } 21567 } 21568 21569 /** 21570 * Return the resolved text alignment. 21571 * 21572 * @return the resolved text alignment. Returns one of: 21573 * 21574 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21575 * {@link #TEXT_ALIGNMENT_CENTER}, 21576 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21577 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21578 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21579 * {@link #TEXT_ALIGNMENT_VIEW_END} 21580 * 21581 * @attr ref android.R.styleable#View_textAlignment 21582 */ 21583 @ViewDebug.ExportedProperty(category = "text", mapping = { 21584 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21585 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21586 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21587 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21588 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21589 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21590 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21591 }) 21592 @TextAlignment 21593 public int getTextAlignment() { 21594 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21595 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21596 } 21597 21598 /** 21599 * Resolve the text alignment. 21600 * 21601 * @return true if resolution has been done, false otherwise. 21602 * 21603 * @hide 21604 */ 21605 public boolean resolveTextAlignment() { 21606 // Reset any previous text alignment resolution 21607 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21608 21609 if (hasRtlSupport()) { 21610 // Set resolved text alignment flag depending on text alignment flag 21611 final int textAlignment = getRawTextAlignment(); 21612 switch (textAlignment) { 21613 case TEXT_ALIGNMENT_INHERIT: 21614 // Check if we can resolve the text alignment 21615 if (!canResolveTextAlignment()) { 21616 // We cannot do the resolution if there is no parent so use the default 21617 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21618 // Resolution will need to happen again later 21619 return false; 21620 } 21621 21622 // Parent has not yet resolved, so we still return the default 21623 try { 21624 if (!mParent.isTextAlignmentResolved()) { 21625 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21626 // Resolution will need to happen again later 21627 return false; 21628 } 21629 } catch (AbstractMethodError e) { 21630 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21631 " does not fully implement ViewParent", e); 21632 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21633 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21634 return true; 21635 } 21636 21637 int parentResolvedTextAlignment; 21638 try { 21639 parentResolvedTextAlignment = mParent.getTextAlignment(); 21640 } catch (AbstractMethodError e) { 21641 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21642 " does not fully implement ViewParent", e); 21643 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21644 } 21645 switch (parentResolvedTextAlignment) { 21646 case TEXT_ALIGNMENT_GRAVITY: 21647 case TEXT_ALIGNMENT_TEXT_START: 21648 case TEXT_ALIGNMENT_TEXT_END: 21649 case TEXT_ALIGNMENT_CENTER: 21650 case TEXT_ALIGNMENT_VIEW_START: 21651 case TEXT_ALIGNMENT_VIEW_END: 21652 // Resolved text alignment is the same as the parent resolved 21653 // text alignment 21654 mPrivateFlags2 |= 21655 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21656 break; 21657 default: 21658 // Use default resolved text alignment 21659 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21660 } 21661 break; 21662 case TEXT_ALIGNMENT_GRAVITY: 21663 case TEXT_ALIGNMENT_TEXT_START: 21664 case TEXT_ALIGNMENT_TEXT_END: 21665 case TEXT_ALIGNMENT_CENTER: 21666 case TEXT_ALIGNMENT_VIEW_START: 21667 case TEXT_ALIGNMENT_VIEW_END: 21668 // Resolved text alignment is the same as text alignment 21669 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21670 break; 21671 default: 21672 // Use default resolved text alignment 21673 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21674 } 21675 } else { 21676 // Use default resolved text alignment 21677 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21678 } 21679 21680 // Set the resolved 21681 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21682 return true; 21683 } 21684 21685 /** 21686 * Check if text alignment resolution can be done. 21687 * 21688 * @return true if text alignment resolution can be done otherwise return false. 21689 */ 21690 public boolean canResolveTextAlignment() { 21691 switch (getRawTextAlignment()) { 21692 case TEXT_DIRECTION_INHERIT: 21693 if (mParent != null) { 21694 try { 21695 return mParent.canResolveTextAlignment(); 21696 } catch (AbstractMethodError e) { 21697 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21698 " does not fully implement ViewParent", e); 21699 } 21700 } 21701 return false; 21702 21703 default: 21704 return true; 21705 } 21706 } 21707 21708 /** 21709 * Reset resolved text alignment. Text alignment will be resolved during a call to 21710 * {@link #onMeasure(int, int)}. 21711 * 21712 * @hide 21713 */ 21714 public void resetResolvedTextAlignment() { 21715 // Reset any previous text alignment resolution 21716 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21717 // Set to default 21718 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21719 } 21720 21721 /** 21722 * @return true if text alignment is inherited. 21723 * 21724 * @hide 21725 */ 21726 public boolean isTextAlignmentInherited() { 21727 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21728 } 21729 21730 /** 21731 * @return true if text alignment is resolved. 21732 */ 21733 public boolean isTextAlignmentResolved() { 21734 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21735 } 21736 21737 /** 21738 * Generate a value suitable for use in {@link #setId(int)}. 21739 * This value will not collide with ID values generated at build time by aapt for R.id. 21740 * 21741 * @return a generated ID value 21742 */ 21743 public static int generateViewId() { 21744 for (;;) { 21745 final int result = sNextGeneratedId.get(); 21746 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21747 int newValue = result + 1; 21748 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21749 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21750 return result; 21751 } 21752 } 21753 } 21754 21755 /** 21756 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21757 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21758 * a normal View or a ViewGroup with 21759 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21760 * @hide 21761 */ 21762 public void captureTransitioningViews(List<View> transitioningViews) { 21763 if (getVisibility() == View.VISIBLE) { 21764 transitioningViews.add(this); 21765 } 21766 } 21767 21768 /** 21769 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21770 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21771 * @hide 21772 */ 21773 public void findNamedViews(Map<String, View> namedElements) { 21774 if (getVisibility() == VISIBLE || mGhostView != null) { 21775 String transitionName = getTransitionName(); 21776 if (transitionName != null) { 21777 namedElements.put(transitionName, this); 21778 } 21779 } 21780 } 21781 21782 /** 21783 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21784 * The default implementation does not care the location or event types, but some subclasses 21785 * may use it (such as WebViews). 21786 * @param event The MotionEvent from a mouse 21787 * @param x The x position of the event, local to the view 21788 * @param y The y position of the event, local to the view 21789 * @see PointerIcon 21790 */ 21791 public PointerIcon getPointerIcon(MotionEvent event, float x, float y) { 21792 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21793 return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW); 21794 } 21795 return mPointerIcon; 21796 } 21797 21798 /** 21799 * Set the pointer icon for the current view. 21800 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21801 */ 21802 public void setPointerIcon(PointerIcon pointerIcon) { 21803 mPointerIcon = pointerIcon; 21804 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 21805 return; 21806 } 21807 try { 21808 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 21809 } catch (RemoteException e) { 21810 } 21811 } 21812 21813 /** 21814 * Request capturing further mouse events. 21815 * 21816 * When the view captures, the mouse pointer icon will disappear and will not change its 21817 * position. Further mouse events will come to the capturing view, and the mouse movements 21818 * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and 21819 * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not 21820 * be affected. 21821 * 21822 * The capture will be released through {@link #releasePointerCapture()}, or will be lost 21823 * automatically when the view or containing window disappear. 21824 * 21825 * @return true when succeeds. 21826 * @see #releasePointerCapture() 21827 * @see #hasPointerCapture() 21828 */ 21829 public void setPointerCapture() { 21830 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21831 if (viewRootImpl != null) { 21832 viewRootImpl.setPointerCapture(this); 21833 } 21834 } 21835 21836 21837 /** 21838 * Release the current capture of mouse events. 21839 * 21840 * If the view does not have the capture, it will do nothing. 21841 * @see #setPointerCapture() 21842 * @see #hasPointerCapture() 21843 */ 21844 public void releasePointerCapture() { 21845 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21846 if (viewRootImpl != null) { 21847 viewRootImpl.releasePointerCapture(this); 21848 } 21849 } 21850 21851 /** 21852 * Checks the capture status of mouse events. 21853 * 21854 * @return true if the view has the capture. 21855 * @see #setPointerCapture() 21856 * @see #hasPointerCapture() 21857 */ 21858 public boolean hasPointerCapture() { 21859 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21860 return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this); 21861 } 21862 21863 // 21864 // Properties 21865 // 21866 /** 21867 * A Property wrapper around the <code>alpha</code> functionality handled by the 21868 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 21869 */ 21870 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 21871 @Override 21872 public void setValue(View object, float value) { 21873 object.setAlpha(value); 21874 } 21875 21876 @Override 21877 public Float get(View object) { 21878 return object.getAlpha(); 21879 } 21880 }; 21881 21882 /** 21883 * A Property wrapper around the <code>translationX</code> functionality handled by the 21884 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 21885 */ 21886 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 21887 @Override 21888 public void setValue(View object, float value) { 21889 object.setTranslationX(value); 21890 } 21891 21892 @Override 21893 public Float get(View object) { 21894 return object.getTranslationX(); 21895 } 21896 }; 21897 21898 /** 21899 * A Property wrapper around the <code>translationY</code> functionality handled by the 21900 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 21901 */ 21902 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 21903 @Override 21904 public void setValue(View object, float value) { 21905 object.setTranslationY(value); 21906 } 21907 21908 @Override 21909 public Float get(View object) { 21910 return object.getTranslationY(); 21911 } 21912 }; 21913 21914 /** 21915 * A Property wrapper around the <code>translationZ</code> functionality handled by the 21916 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 21917 */ 21918 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 21919 @Override 21920 public void setValue(View object, float value) { 21921 object.setTranslationZ(value); 21922 } 21923 21924 @Override 21925 public Float get(View object) { 21926 return object.getTranslationZ(); 21927 } 21928 }; 21929 21930 /** 21931 * A Property wrapper around the <code>x</code> functionality handled by the 21932 * {@link View#setX(float)} and {@link View#getX()} methods. 21933 */ 21934 public static final Property<View, Float> X = new FloatProperty<View>("x") { 21935 @Override 21936 public void setValue(View object, float value) { 21937 object.setX(value); 21938 } 21939 21940 @Override 21941 public Float get(View object) { 21942 return object.getX(); 21943 } 21944 }; 21945 21946 /** 21947 * A Property wrapper around the <code>y</code> functionality handled by the 21948 * {@link View#setY(float)} and {@link View#getY()} methods. 21949 */ 21950 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 21951 @Override 21952 public void setValue(View object, float value) { 21953 object.setY(value); 21954 } 21955 21956 @Override 21957 public Float get(View object) { 21958 return object.getY(); 21959 } 21960 }; 21961 21962 /** 21963 * A Property wrapper around the <code>z</code> functionality handled by the 21964 * {@link View#setZ(float)} and {@link View#getZ()} methods. 21965 */ 21966 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 21967 @Override 21968 public void setValue(View object, float value) { 21969 object.setZ(value); 21970 } 21971 21972 @Override 21973 public Float get(View object) { 21974 return object.getZ(); 21975 } 21976 }; 21977 21978 /** 21979 * A Property wrapper around the <code>rotation</code> functionality handled by the 21980 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 21981 */ 21982 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 21983 @Override 21984 public void setValue(View object, float value) { 21985 object.setRotation(value); 21986 } 21987 21988 @Override 21989 public Float get(View object) { 21990 return object.getRotation(); 21991 } 21992 }; 21993 21994 /** 21995 * A Property wrapper around the <code>rotationX</code> functionality handled by the 21996 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 21997 */ 21998 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 21999 @Override 22000 public void setValue(View object, float value) { 22001 object.setRotationX(value); 22002 } 22003 22004 @Override 22005 public Float get(View object) { 22006 return object.getRotationX(); 22007 } 22008 }; 22009 22010 /** 22011 * A Property wrapper around the <code>rotationY</code> functionality handled by the 22012 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 22013 */ 22014 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 22015 @Override 22016 public void setValue(View object, float value) { 22017 object.setRotationY(value); 22018 } 22019 22020 @Override 22021 public Float get(View object) { 22022 return object.getRotationY(); 22023 } 22024 }; 22025 22026 /** 22027 * A Property wrapper around the <code>scaleX</code> functionality handled by the 22028 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 22029 */ 22030 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 22031 @Override 22032 public void setValue(View object, float value) { 22033 object.setScaleX(value); 22034 } 22035 22036 @Override 22037 public Float get(View object) { 22038 return object.getScaleX(); 22039 } 22040 }; 22041 22042 /** 22043 * A Property wrapper around the <code>scaleY</code> functionality handled by the 22044 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 22045 */ 22046 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 22047 @Override 22048 public void setValue(View object, float value) { 22049 object.setScaleY(value); 22050 } 22051 22052 @Override 22053 public Float get(View object) { 22054 return object.getScaleY(); 22055 } 22056 }; 22057 22058 /** 22059 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 22060 * Each MeasureSpec represents a requirement for either the width or the height. 22061 * A MeasureSpec is comprised of a size and a mode. There are three possible 22062 * modes: 22063 * <dl> 22064 * <dt>UNSPECIFIED</dt> 22065 * <dd> 22066 * The parent has not imposed any constraint on the child. It can be whatever size 22067 * it wants. 22068 * </dd> 22069 * 22070 * <dt>EXACTLY</dt> 22071 * <dd> 22072 * The parent has determined an exact size for the child. The child is going to be 22073 * given those bounds regardless of how big it wants to be. 22074 * </dd> 22075 * 22076 * <dt>AT_MOST</dt> 22077 * <dd> 22078 * The child can be as large as it wants up to the specified size. 22079 * </dd> 22080 * </dl> 22081 * 22082 * MeasureSpecs are implemented as ints to reduce object allocation. This class 22083 * is provided to pack and unpack the <size, mode> tuple into the int. 22084 */ 22085 public static class MeasureSpec { 22086 private static final int MODE_SHIFT = 30; 22087 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 22088 22089 /** @hide */ 22090 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 22091 @Retention(RetentionPolicy.SOURCE) 22092 public @interface MeasureSpecMode {} 22093 22094 /** 22095 * Measure specification mode: The parent has not imposed any constraint 22096 * on the child. It can be whatever size it wants. 22097 */ 22098 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 22099 22100 /** 22101 * Measure specification mode: The parent has determined an exact size 22102 * for the child. The child is going to be given those bounds regardless 22103 * of how big it wants to be. 22104 */ 22105 public static final int EXACTLY = 1 << MODE_SHIFT; 22106 22107 /** 22108 * Measure specification mode: The child can be as large as it wants up 22109 * to the specified size. 22110 */ 22111 public static final int AT_MOST = 2 << MODE_SHIFT; 22112 22113 /** 22114 * Creates a measure specification based on the supplied size and mode. 22115 * 22116 * The mode must always be one of the following: 22117 * <ul> 22118 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 22119 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 22120 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 22121 * </ul> 22122 * 22123 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 22124 * implementation was such that the order of arguments did not matter 22125 * and overflow in either value could impact the resulting MeasureSpec. 22126 * {@link android.widget.RelativeLayout} was affected by this bug. 22127 * Apps targeting API levels greater than 17 will get the fixed, more strict 22128 * behavior.</p> 22129 * 22130 * @param size the size of the measure specification 22131 * @param mode the mode of the measure specification 22132 * @return the measure specification based on size and mode 22133 */ 22134 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 22135 @MeasureSpecMode int mode) { 22136 if (sUseBrokenMakeMeasureSpec) { 22137 return size + mode; 22138 } else { 22139 return (size & ~MODE_MASK) | (mode & MODE_MASK); 22140 } 22141 } 22142 22143 /** 22144 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 22145 * will automatically get a size of 0. Older apps expect this. 22146 * 22147 * @hide internal use only for compatibility with system widgets and older apps 22148 */ 22149 public static int makeSafeMeasureSpec(int size, int mode) { 22150 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 22151 return 0; 22152 } 22153 return makeMeasureSpec(size, mode); 22154 } 22155 22156 /** 22157 * Extracts the mode from the supplied measure specification. 22158 * 22159 * @param measureSpec the measure specification to extract the mode from 22160 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 22161 * {@link android.view.View.MeasureSpec#AT_MOST} or 22162 * {@link android.view.View.MeasureSpec#EXACTLY} 22163 */ 22164 @MeasureSpecMode 22165 public static int getMode(int measureSpec) { 22166 //noinspection ResourceType 22167 return (measureSpec & MODE_MASK); 22168 } 22169 22170 /** 22171 * Extracts the size from the supplied measure specification. 22172 * 22173 * @param measureSpec the measure specification to extract the size from 22174 * @return the size in pixels defined in the supplied measure specification 22175 */ 22176 public static int getSize(int measureSpec) { 22177 return (measureSpec & ~MODE_MASK); 22178 } 22179 22180 static int adjust(int measureSpec, int delta) { 22181 final int mode = getMode(measureSpec); 22182 int size = getSize(measureSpec); 22183 if (mode == UNSPECIFIED) { 22184 // No need to adjust size for UNSPECIFIED mode. 22185 return makeMeasureSpec(size, UNSPECIFIED); 22186 } 22187 size += delta; 22188 if (size < 0) { 22189 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 22190 ") spec: " + toString(measureSpec) + " delta: " + delta); 22191 size = 0; 22192 } 22193 return makeMeasureSpec(size, mode); 22194 } 22195 22196 /** 22197 * Returns a String representation of the specified measure 22198 * specification. 22199 * 22200 * @param measureSpec the measure specification to convert to a String 22201 * @return a String with the following format: "MeasureSpec: MODE SIZE" 22202 */ 22203 public static String toString(int measureSpec) { 22204 int mode = getMode(measureSpec); 22205 int size = getSize(measureSpec); 22206 22207 StringBuilder sb = new StringBuilder("MeasureSpec: "); 22208 22209 if (mode == UNSPECIFIED) 22210 sb.append("UNSPECIFIED "); 22211 else if (mode == EXACTLY) 22212 sb.append("EXACTLY "); 22213 else if (mode == AT_MOST) 22214 sb.append("AT_MOST "); 22215 else 22216 sb.append(mode).append(" "); 22217 22218 sb.append(size); 22219 return sb.toString(); 22220 } 22221 } 22222 22223 private final class CheckForLongPress implements Runnable { 22224 private int mOriginalWindowAttachCount; 22225 private float mX; 22226 private float mY; 22227 22228 @Override 22229 public void run() { 22230 if (isPressed() && (mParent != null) 22231 && mOriginalWindowAttachCount == mWindowAttachCount) { 22232 if (performLongClick(mX, mY)) { 22233 mHasPerformedLongPress = true; 22234 } 22235 } 22236 } 22237 22238 public void setAnchor(float x, float y) { 22239 mX = x; 22240 mY = y; 22241 } 22242 22243 public void rememberWindowAttachCount() { 22244 mOriginalWindowAttachCount = mWindowAttachCount; 22245 } 22246 } 22247 22248 private final class CheckForTap implements Runnable { 22249 public float x; 22250 public float y; 22251 22252 @Override 22253 public void run() { 22254 mPrivateFlags &= ~PFLAG_PREPRESSED; 22255 setPressed(true, x, y); 22256 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22257 } 22258 } 22259 22260 private final class PerformClick implements Runnable { 22261 @Override 22262 public void run() { 22263 performClick(); 22264 } 22265 } 22266 22267 /** 22268 * This method returns a ViewPropertyAnimator object, which can be used to animate 22269 * specific properties on this View. 22270 * 22271 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22272 */ 22273 public ViewPropertyAnimator animate() { 22274 if (mAnimator == null) { 22275 mAnimator = new ViewPropertyAnimator(this); 22276 } 22277 return mAnimator; 22278 } 22279 22280 /** 22281 * Sets the name of the View to be used to identify Views in Transitions. 22282 * Names should be unique in the View hierarchy. 22283 * 22284 * @param transitionName The name of the View to uniquely identify it for Transitions. 22285 */ 22286 public final void setTransitionName(String transitionName) { 22287 mTransitionName = transitionName; 22288 } 22289 22290 /** 22291 * Returns the name of the View to be used to identify Views in Transitions. 22292 * Names should be unique in the View hierarchy. 22293 * 22294 * <p>This returns null if the View has not been given a name.</p> 22295 * 22296 * @return The name used of the View to be used to identify Views in Transitions or null 22297 * if no name has been given. 22298 */ 22299 @ViewDebug.ExportedProperty 22300 public String getTransitionName() { 22301 return mTransitionName; 22302 } 22303 22304 /** 22305 * @hide 22306 */ 22307 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 22308 // Do nothing. 22309 } 22310 22311 /** 22312 * Interface definition for a callback to be invoked when a hardware key event is 22313 * dispatched to this view. The callback will be invoked before the key event is 22314 * given to the view. This is only useful for hardware keyboards; a software input 22315 * method has no obligation to trigger this listener. 22316 */ 22317 public interface OnKeyListener { 22318 /** 22319 * Called when a hardware key is dispatched to a view. This allows listeners to 22320 * get a chance to respond before the target view. 22321 * <p>Key presses in software keyboards will generally NOT trigger this method, 22322 * although some may elect to do so in some situations. Do not assume a 22323 * software input method has to be key-based; even if it is, it may use key presses 22324 * in a different way than you expect, so there is no way to reliably catch soft 22325 * input key presses. 22326 * 22327 * @param v The view the key has been dispatched to. 22328 * @param keyCode The code for the physical key that was pressed 22329 * @param event The KeyEvent object containing full information about 22330 * the event. 22331 * @return True if the listener has consumed the event, false otherwise. 22332 */ 22333 boolean onKey(View v, int keyCode, KeyEvent event); 22334 } 22335 22336 /** 22337 * Interface definition for a callback to be invoked when a touch event is 22338 * dispatched to this view. The callback will be invoked before the touch 22339 * event is given to the view. 22340 */ 22341 public interface OnTouchListener { 22342 /** 22343 * Called when a touch event is dispatched to a view. This allows listeners to 22344 * get a chance to respond before the target view. 22345 * 22346 * @param v The view the touch event has been dispatched to. 22347 * @param event The MotionEvent object containing full information about 22348 * the event. 22349 * @return True if the listener has consumed the event, false otherwise. 22350 */ 22351 boolean onTouch(View v, MotionEvent event); 22352 } 22353 22354 /** 22355 * Interface definition for a callback to be invoked when a hover event is 22356 * dispatched to this view. The callback will be invoked before the hover 22357 * event is given to the view. 22358 */ 22359 public interface OnHoverListener { 22360 /** 22361 * Called when a hover event is dispatched to a view. This allows listeners to 22362 * get a chance to respond before the target view. 22363 * 22364 * @param v The view the hover event has been dispatched to. 22365 * @param event The MotionEvent object containing full information about 22366 * the event. 22367 * @return True if the listener has consumed the event, false otherwise. 22368 */ 22369 boolean onHover(View v, MotionEvent event); 22370 } 22371 22372 /** 22373 * Interface definition for a callback to be invoked when a generic motion event is 22374 * dispatched to this view. The callback will be invoked before the generic motion 22375 * event is given to the view. 22376 */ 22377 public interface OnGenericMotionListener { 22378 /** 22379 * Called when a generic motion event is dispatched to a view. This allows listeners to 22380 * get a chance to respond before the target view. 22381 * 22382 * @param v The view the generic motion event has been dispatched to. 22383 * @param event The MotionEvent object containing full information about 22384 * the event. 22385 * @return True if the listener has consumed the event, false otherwise. 22386 */ 22387 boolean onGenericMotion(View v, MotionEvent event); 22388 } 22389 22390 /** 22391 * Interface definition for a callback to be invoked when a view has been clicked and held. 22392 */ 22393 public interface OnLongClickListener { 22394 /** 22395 * Called when a view has been clicked and held. 22396 * 22397 * @param v The view that was clicked and held. 22398 * 22399 * @return true if the callback consumed the long click, false otherwise. 22400 */ 22401 boolean onLongClick(View v); 22402 } 22403 22404 /** 22405 * Interface definition for a callback to be invoked when a drag is being dispatched 22406 * to this view. The callback will be invoked before the hosting view's own 22407 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22408 * onDrag(event) behavior, it should return 'false' from this callback. 22409 * 22410 * <div class="special reference"> 22411 * <h3>Developer Guides</h3> 22412 * <p>For a guide to implementing drag and drop features, read the 22413 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22414 * </div> 22415 */ 22416 public interface OnDragListener { 22417 /** 22418 * Called when a drag event is dispatched to a view. This allows listeners 22419 * to get a chance to override base View behavior. 22420 * 22421 * @param v The View that received the drag event. 22422 * @param event The {@link android.view.DragEvent} object for the drag event. 22423 * @return {@code true} if the drag event was handled successfully, or {@code false} 22424 * if the drag event was not handled. Note that {@code false} will trigger the View 22425 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22426 */ 22427 boolean onDrag(View v, DragEvent event); 22428 } 22429 22430 /** 22431 * Interface definition for a callback to be invoked when the focus state of 22432 * a view changed. 22433 */ 22434 public interface OnFocusChangeListener { 22435 /** 22436 * Called when the focus state of a view has changed. 22437 * 22438 * @param v The view whose state has changed. 22439 * @param hasFocus The new focus state of v. 22440 */ 22441 void onFocusChange(View v, boolean hasFocus); 22442 } 22443 22444 /** 22445 * Interface definition for a callback to be invoked when a view is clicked. 22446 */ 22447 public interface OnClickListener { 22448 /** 22449 * Called when a view has been clicked. 22450 * 22451 * @param v The view that was clicked. 22452 */ 22453 void onClick(View v); 22454 } 22455 22456 /** 22457 * Interface definition for a callback to be invoked when a view is context clicked. 22458 */ 22459 public interface OnContextClickListener { 22460 /** 22461 * Called when a view is context clicked. 22462 * 22463 * @param v The view that has been context clicked. 22464 * @return true if the callback consumed the context click, false otherwise. 22465 */ 22466 boolean onContextClick(View v); 22467 } 22468 22469 /** 22470 * Interface definition for a callback to be invoked when the context menu 22471 * for this view is being built. 22472 */ 22473 public interface OnCreateContextMenuListener { 22474 /** 22475 * Called when the context menu for this view is being built. It is not 22476 * safe to hold onto the menu after this method returns. 22477 * 22478 * @param menu The context menu that is being built 22479 * @param v The view for which the context menu is being built 22480 * @param menuInfo Extra information about the item for which the 22481 * context menu should be shown. This information will vary 22482 * depending on the class of v. 22483 */ 22484 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22485 } 22486 22487 /** 22488 * Interface definition for a callback to be invoked when the status bar changes 22489 * visibility. This reports <strong>global</strong> changes to the system UI 22490 * state, not what the application is requesting. 22491 * 22492 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22493 */ 22494 public interface OnSystemUiVisibilityChangeListener { 22495 /** 22496 * Called when the status bar changes visibility because of a call to 22497 * {@link View#setSystemUiVisibility(int)}. 22498 * 22499 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22500 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22501 * This tells you the <strong>global</strong> state of these UI visibility 22502 * flags, not what your app is currently applying. 22503 */ 22504 public void onSystemUiVisibilityChange(int visibility); 22505 } 22506 22507 /** 22508 * Interface definition for a callback to be invoked when this view is attached 22509 * or detached from its window. 22510 */ 22511 public interface OnAttachStateChangeListener { 22512 /** 22513 * Called when the view is attached to a window. 22514 * @param v The view that was attached 22515 */ 22516 public void onViewAttachedToWindow(View v); 22517 /** 22518 * Called when the view is detached from a window. 22519 * @param v The view that was detached 22520 */ 22521 public void onViewDetachedFromWindow(View v); 22522 } 22523 22524 /** 22525 * Listener for applying window insets on a view in a custom way. 22526 * 22527 * <p>Apps may choose to implement this interface if they want to apply custom policy 22528 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22529 * is set, its 22530 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22531 * method will be called instead of the View's own 22532 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22533 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22534 * the View's normal behavior as part of its own.</p> 22535 */ 22536 public interface OnApplyWindowInsetsListener { 22537 /** 22538 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22539 * on a View, this listener method will be called instead of the view's own 22540 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22541 * 22542 * @param v The view applying window insets 22543 * @param insets The insets to apply 22544 * @return The insets supplied, minus any insets that were consumed 22545 */ 22546 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22547 } 22548 22549 private final class UnsetPressedState implements Runnable { 22550 @Override 22551 public void run() { 22552 setPressed(false); 22553 } 22554 } 22555 22556 /** 22557 * Base class for derived classes that want to save and restore their own 22558 * state in {@link android.view.View#onSaveInstanceState()}. 22559 */ 22560 public static class BaseSavedState extends AbsSavedState { 22561 String mStartActivityRequestWhoSaved; 22562 22563 /** 22564 * Constructor used when reading from a parcel. Reads the state of the superclass. 22565 * 22566 * @param source 22567 */ 22568 public BaseSavedState(Parcel source) { 22569 super(source); 22570 mStartActivityRequestWhoSaved = source.readString(); 22571 } 22572 22573 /** 22574 * Constructor called by derived classes when creating their SavedState objects 22575 * 22576 * @param superState The state of the superclass of this view 22577 */ 22578 public BaseSavedState(Parcelable superState) { 22579 super(superState); 22580 } 22581 22582 @Override 22583 public void writeToParcel(Parcel out, int flags) { 22584 super.writeToParcel(out, flags); 22585 out.writeString(mStartActivityRequestWhoSaved); 22586 } 22587 22588 public static final Parcelable.Creator<BaseSavedState> CREATOR = 22589 new Parcelable.Creator<BaseSavedState>() { 22590 public BaseSavedState createFromParcel(Parcel in) { 22591 return new BaseSavedState(in); 22592 } 22593 22594 public BaseSavedState[] newArray(int size) { 22595 return new BaseSavedState[size]; 22596 } 22597 }; 22598 } 22599 22600 /** 22601 * A set of information given to a view when it is attached to its parent 22602 * window. 22603 */ 22604 final static class AttachInfo { 22605 interface Callbacks { 22606 void playSoundEffect(int effectId); 22607 boolean performHapticFeedback(int effectId, boolean always); 22608 } 22609 22610 /** 22611 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22612 * to a Handler. This class contains the target (View) to invalidate and 22613 * the coordinates of the dirty rectangle. 22614 * 22615 * For performance purposes, this class also implements a pool of up to 22616 * POOL_LIMIT objects that get reused. This reduces memory allocations 22617 * whenever possible. 22618 */ 22619 static class InvalidateInfo { 22620 private static final int POOL_LIMIT = 10; 22621 22622 private static final SynchronizedPool<InvalidateInfo> sPool = 22623 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22624 22625 View target; 22626 22627 int left; 22628 int top; 22629 int right; 22630 int bottom; 22631 22632 public static InvalidateInfo obtain() { 22633 InvalidateInfo instance = sPool.acquire(); 22634 return (instance != null) ? instance : new InvalidateInfo(); 22635 } 22636 22637 public void recycle() { 22638 target = null; 22639 sPool.release(this); 22640 } 22641 } 22642 22643 final IWindowSession mSession; 22644 22645 final IWindow mWindow; 22646 22647 final IBinder mWindowToken; 22648 22649 final Display mDisplay; 22650 22651 final Callbacks mRootCallbacks; 22652 22653 IWindowId mIWindowId; 22654 WindowId mWindowId; 22655 22656 /** 22657 * The top view of the hierarchy. 22658 */ 22659 View mRootView; 22660 22661 IBinder mPanelParentWindowToken; 22662 22663 boolean mHardwareAccelerated; 22664 boolean mHardwareAccelerationRequested; 22665 ThreadedRenderer mHardwareRenderer; 22666 List<RenderNode> mPendingAnimatingRenderNodes; 22667 22668 /** 22669 * The state of the display to which the window is attached, as reported 22670 * by {@link Display#getState()}. Note that the display state constants 22671 * declared by {@link Display} do not exactly line up with the screen state 22672 * constants declared by {@link View} (there are more display states than 22673 * screen states). 22674 */ 22675 int mDisplayState = Display.STATE_UNKNOWN; 22676 22677 /** 22678 * Scale factor used by the compatibility mode 22679 */ 22680 float mApplicationScale; 22681 22682 /** 22683 * Indicates whether the application is in compatibility mode 22684 */ 22685 boolean mScalingRequired; 22686 22687 /** 22688 * Left position of this view's window 22689 */ 22690 int mWindowLeft; 22691 22692 /** 22693 * Top position of this view's window 22694 */ 22695 int mWindowTop; 22696 22697 /** 22698 * Indicates whether views need to use 32-bit drawing caches 22699 */ 22700 boolean mUse32BitDrawingCache; 22701 22702 /** 22703 * For windows that are full-screen but using insets to layout inside 22704 * of the screen areas, these are the current insets to appear inside 22705 * the overscan area of the display. 22706 */ 22707 final Rect mOverscanInsets = new Rect(); 22708 22709 /** 22710 * For windows that are full-screen but using insets to layout inside 22711 * of the screen decorations, these are the current insets for the 22712 * content of the window. 22713 */ 22714 final Rect mContentInsets = new Rect(); 22715 22716 /** 22717 * For windows that are full-screen but using insets to layout inside 22718 * of the screen decorations, these are the current insets for the 22719 * actual visible parts of the window. 22720 */ 22721 final Rect mVisibleInsets = new Rect(); 22722 22723 /** 22724 * For windows that are full-screen but using insets to layout inside 22725 * of the screen decorations, these are the current insets for the 22726 * stable system windows. 22727 */ 22728 final Rect mStableInsets = new Rect(); 22729 22730 /** 22731 * For windows that include areas that are not covered by real surface these are the outsets 22732 * for real surface. 22733 */ 22734 final Rect mOutsets = new Rect(); 22735 22736 /** 22737 * In multi-window we force show the navigation bar. Because we don't want that the surface 22738 * size changes in this mode, we instead have a flag whether the navigation bar size should 22739 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22740 */ 22741 boolean mAlwaysConsumeNavBar; 22742 22743 /** 22744 * The internal insets given by this window. This value is 22745 * supplied by the client (through 22746 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22747 * be given to the window manager when changed to be used in laying 22748 * out windows behind it. 22749 */ 22750 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22751 = new ViewTreeObserver.InternalInsetsInfo(); 22752 22753 /** 22754 * Set to true when mGivenInternalInsets is non-empty. 22755 */ 22756 boolean mHasNonEmptyGivenInternalInsets; 22757 22758 /** 22759 * All views in the window's hierarchy that serve as scroll containers, 22760 * used to determine if the window can be resized or must be panned 22761 * to adjust for a soft input area. 22762 */ 22763 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22764 22765 final KeyEvent.DispatcherState mKeyDispatchState 22766 = new KeyEvent.DispatcherState(); 22767 22768 /** 22769 * Indicates whether the view's window currently has the focus. 22770 */ 22771 boolean mHasWindowFocus; 22772 22773 /** 22774 * The current visibility of the window. 22775 */ 22776 int mWindowVisibility; 22777 22778 /** 22779 * Indicates the time at which drawing started to occur. 22780 */ 22781 long mDrawingTime; 22782 22783 /** 22784 * Indicates whether or not ignoring the DIRTY_MASK flags. 22785 */ 22786 boolean mIgnoreDirtyState; 22787 22788 /** 22789 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22790 * to avoid clearing that flag prematurely. 22791 */ 22792 boolean mSetIgnoreDirtyState = false; 22793 22794 /** 22795 * Indicates whether the view's window is currently in touch mode. 22796 */ 22797 boolean mInTouchMode; 22798 22799 /** 22800 * Indicates whether the view has requested unbuffered input dispatching for the current 22801 * event stream. 22802 */ 22803 boolean mUnbufferedDispatchRequested; 22804 22805 /** 22806 * Indicates that ViewAncestor should trigger a global layout change 22807 * the next time it performs a traversal 22808 */ 22809 boolean mRecomputeGlobalAttributes; 22810 22811 /** 22812 * Always report new attributes at next traversal. 22813 */ 22814 boolean mForceReportNewAttributes; 22815 22816 /** 22817 * Set during a traveral if any views want to keep the screen on. 22818 */ 22819 boolean mKeepScreenOn; 22820 22821 /** 22822 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22823 */ 22824 int mSystemUiVisibility; 22825 22826 /** 22827 * Hack to force certain system UI visibility flags to be cleared. 22828 */ 22829 int mDisabledSystemUiVisibility; 22830 22831 /** 22832 * Last global system UI visibility reported by the window manager. 22833 */ 22834 int mGlobalSystemUiVisibility; 22835 22836 /** 22837 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 22838 * attached. 22839 */ 22840 boolean mHasSystemUiListeners; 22841 22842 /** 22843 * Set if the window has requested to extend into the overscan region 22844 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 22845 */ 22846 boolean mOverscanRequested; 22847 22848 /** 22849 * Set if the visibility of any views has changed. 22850 */ 22851 boolean mViewVisibilityChanged; 22852 22853 /** 22854 * Set to true if a view has been scrolled. 22855 */ 22856 boolean mViewScrollChanged; 22857 22858 /** 22859 * Set to true if high contrast mode enabled 22860 */ 22861 boolean mHighContrastText; 22862 22863 /** 22864 * Set to true if a pointer event is currently being handled. 22865 */ 22866 boolean mHandlingPointerEvent; 22867 22868 /** 22869 * Global to the view hierarchy used as a temporary for dealing with 22870 * x/y points in the transparent region computations. 22871 */ 22872 final int[] mTransparentLocation = new int[2]; 22873 22874 /** 22875 * Global to the view hierarchy used as a temporary for dealing with 22876 * x/y points in the ViewGroup.invalidateChild implementation. 22877 */ 22878 final int[] mInvalidateChildLocation = new int[2]; 22879 22880 /** 22881 * Global to the view hierarchy used as a temporary for dealng with 22882 * computing absolute on-screen location. 22883 */ 22884 final int[] mTmpLocation = new int[2]; 22885 22886 /** 22887 * Global to the view hierarchy used as a temporary for dealing with 22888 * x/y location when view is transformed. 22889 */ 22890 final float[] mTmpTransformLocation = new float[2]; 22891 22892 /** 22893 * The view tree observer used to dispatch global events like 22894 * layout, pre-draw, touch mode change, etc. 22895 */ 22896 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 22897 22898 /** 22899 * A Canvas used by the view hierarchy to perform bitmap caching. 22900 */ 22901 Canvas mCanvas; 22902 22903 /** 22904 * The view root impl. 22905 */ 22906 final ViewRootImpl mViewRootImpl; 22907 22908 /** 22909 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 22910 * handler can be used to pump events in the UI events queue. 22911 */ 22912 final Handler mHandler; 22913 22914 /** 22915 * Temporary for use in computing invalidate rectangles while 22916 * calling up the hierarchy. 22917 */ 22918 final Rect mTmpInvalRect = new Rect(); 22919 22920 /** 22921 * Temporary for use in computing hit areas with transformed views 22922 */ 22923 final RectF mTmpTransformRect = new RectF(); 22924 22925 /** 22926 * Temporary for use in computing hit areas with transformed views 22927 */ 22928 final RectF mTmpTransformRect1 = new RectF(); 22929 22930 /** 22931 * Temporary list of rectanges. 22932 */ 22933 final List<RectF> mTmpRectList = new ArrayList<>(); 22934 22935 /** 22936 * Temporary for use in transforming invalidation rect 22937 */ 22938 final Matrix mTmpMatrix = new Matrix(); 22939 22940 /** 22941 * Temporary for use in transforming invalidation rect 22942 */ 22943 final Transformation mTmpTransformation = new Transformation(); 22944 22945 /** 22946 * Temporary for use in querying outlines from OutlineProviders 22947 */ 22948 final Outline mTmpOutline = new Outline(); 22949 22950 /** 22951 * Temporary list for use in collecting focusable descendents of a view. 22952 */ 22953 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 22954 22955 /** 22956 * The id of the window for accessibility purposes. 22957 */ 22958 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 22959 22960 /** 22961 * Flags related to accessibility processing. 22962 * 22963 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 22964 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 22965 */ 22966 int mAccessibilityFetchFlags; 22967 22968 /** 22969 * The drawable for highlighting accessibility focus. 22970 */ 22971 Drawable mAccessibilityFocusDrawable; 22972 22973 /** 22974 * Show where the margins, bounds and layout bounds are for each view. 22975 */ 22976 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 22977 22978 /** 22979 * Point used to compute visible regions. 22980 */ 22981 final Point mPoint = new Point(); 22982 22983 /** 22984 * Used to track which View originated a requestLayout() call, used when 22985 * requestLayout() is called during layout. 22986 */ 22987 View mViewRequestingLayout; 22988 22989 /** 22990 * Used to track views that need (at least) a partial relayout at their current size 22991 * during the next traversal. 22992 */ 22993 List<View> mPartialLayoutViews = new ArrayList<>(); 22994 22995 /** 22996 * Swapped with mPartialLayoutViews during layout to avoid concurrent 22997 * modification. Lazily assigned during ViewRootImpl layout. 22998 */ 22999 List<View> mEmptyPartialLayoutViews; 23000 23001 /** 23002 * Used to track the identity of the current drag operation. 23003 */ 23004 IBinder mDragToken; 23005 23006 /** 23007 * The drag shadow surface for the current drag operation. 23008 */ 23009 public Surface mDragSurface; 23010 23011 /** 23012 * Creates a new set of attachment information with the specified 23013 * events handler and thread. 23014 * 23015 * @param handler the events handler the view must use 23016 */ 23017 AttachInfo(IWindowSession session, IWindow window, Display display, 23018 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 23019 mSession = session; 23020 mWindow = window; 23021 mWindowToken = window.asBinder(); 23022 mDisplay = display; 23023 mViewRootImpl = viewRootImpl; 23024 mHandler = handler; 23025 mRootCallbacks = effectPlayer; 23026 } 23027 } 23028 23029 /** 23030 * <p>ScrollabilityCache holds various fields used by a View when scrolling 23031 * is supported. This avoids keeping too many unused fields in most 23032 * instances of View.</p> 23033 */ 23034 private static class ScrollabilityCache implements Runnable { 23035 23036 /** 23037 * Scrollbars are not visible 23038 */ 23039 public static final int OFF = 0; 23040 23041 /** 23042 * Scrollbars are visible 23043 */ 23044 public static final int ON = 1; 23045 23046 /** 23047 * Scrollbars are fading away 23048 */ 23049 public static final int FADING = 2; 23050 23051 public boolean fadeScrollBars; 23052 23053 public int fadingEdgeLength; 23054 public int scrollBarDefaultDelayBeforeFade; 23055 public int scrollBarFadeDuration; 23056 23057 public int scrollBarSize; 23058 public ScrollBarDrawable scrollBar; 23059 public float[] interpolatorValues; 23060 public View host; 23061 23062 public final Paint paint; 23063 public final Matrix matrix; 23064 public Shader shader; 23065 23066 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 23067 23068 private static final float[] OPAQUE = { 255 }; 23069 private static final float[] TRANSPARENT = { 0.0f }; 23070 23071 /** 23072 * When fading should start. This time moves into the future every time 23073 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 23074 */ 23075 public long fadeStartTime; 23076 23077 23078 /** 23079 * The current state of the scrollbars: ON, OFF, or FADING 23080 */ 23081 public int state = OFF; 23082 23083 private int mLastColor; 23084 23085 public final Rect mScrollBarBounds = new Rect(); 23086 23087 public static final int NOT_DRAGGING = 0; 23088 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 23089 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 23090 public int mScrollBarDraggingState = NOT_DRAGGING; 23091 23092 public float mScrollBarDraggingPos = 0; 23093 23094 public ScrollabilityCache(ViewConfiguration configuration, View host) { 23095 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 23096 scrollBarSize = configuration.getScaledScrollBarSize(); 23097 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 23098 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 23099 23100 paint = new Paint(); 23101 matrix = new Matrix(); 23102 // use use a height of 1, and then wack the matrix each time we 23103 // actually use it. 23104 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23105 paint.setShader(shader); 23106 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23107 23108 this.host = host; 23109 } 23110 23111 public void setFadeColor(int color) { 23112 if (color != mLastColor) { 23113 mLastColor = color; 23114 23115 if (color != 0) { 23116 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 23117 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 23118 paint.setShader(shader); 23119 // Restore the default transfer mode (src_over) 23120 paint.setXfermode(null); 23121 } else { 23122 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 23123 paint.setShader(shader); 23124 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 23125 } 23126 } 23127 } 23128 23129 public void run() { 23130 long now = AnimationUtils.currentAnimationTimeMillis(); 23131 if (now >= fadeStartTime) { 23132 23133 // the animation fades the scrollbars out by changing 23134 // the opacity (alpha) from fully opaque to fully 23135 // transparent 23136 int nextFrame = (int) now; 23137 int framesCount = 0; 23138 23139 Interpolator interpolator = scrollBarInterpolator; 23140 23141 // Start opaque 23142 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 23143 23144 // End transparent 23145 nextFrame += scrollBarFadeDuration; 23146 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 23147 23148 state = FADING; 23149 23150 // Kick off the fade animation 23151 host.invalidate(true); 23152 } 23153 } 23154 } 23155 23156 /** 23157 * Resuable callback for sending 23158 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 23159 */ 23160 private class SendViewScrolledAccessibilityEvent implements Runnable { 23161 public volatile boolean mIsPending; 23162 23163 public void run() { 23164 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 23165 mIsPending = false; 23166 } 23167 } 23168 23169 /** 23170 * <p> 23171 * This class represents a delegate that can be registered in a {@link View} 23172 * to enhance accessibility support via composition rather via inheritance. 23173 * It is specifically targeted to widget developers that extend basic View 23174 * classes i.e. classes in package android.view, that would like their 23175 * applications to be backwards compatible. 23176 * </p> 23177 * <div class="special reference"> 23178 * <h3>Developer Guides</h3> 23179 * <p>For more information about making applications accessible, read the 23180 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 23181 * developer guide.</p> 23182 * </div> 23183 * <p> 23184 * A scenario in which a developer would like to use an accessibility delegate 23185 * is overriding a method introduced in a later API version then the minimal API 23186 * version supported by the application. For example, the method 23187 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 23188 * in API version 4 when the accessibility APIs were first introduced. If a 23189 * developer would like his application to run on API version 4 devices (assuming 23190 * all other APIs used by the application are version 4 or lower) and take advantage 23191 * of this method, instead of overriding the method which would break the application's 23192 * backwards compatibility, he can override the corresponding method in this 23193 * delegate and register the delegate in the target View if the API version of 23194 * the system is high enough i.e. the API version is same or higher to the API 23195 * version that introduced 23196 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 23197 * </p> 23198 * <p> 23199 * Here is an example implementation: 23200 * </p> 23201 * <code><pre><p> 23202 * if (Build.VERSION.SDK_INT >= 14) { 23203 * // If the API version is equal of higher than the version in 23204 * // which onInitializeAccessibilityNodeInfo was introduced we 23205 * // register a delegate with a customized implementation. 23206 * View view = findViewById(R.id.view_id); 23207 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 23208 * public void onInitializeAccessibilityNodeInfo(View host, 23209 * AccessibilityNodeInfo info) { 23210 * // Let the default implementation populate the info. 23211 * super.onInitializeAccessibilityNodeInfo(host, info); 23212 * // Set some other information. 23213 * info.setEnabled(host.isEnabled()); 23214 * } 23215 * }); 23216 * } 23217 * </code></pre></p> 23218 * <p> 23219 * This delegate contains methods that correspond to the accessibility methods 23220 * in View. If a delegate has been specified the implementation in View hands 23221 * off handling to the corresponding method in this delegate. The default 23222 * implementation the delegate methods behaves exactly as the corresponding 23223 * method in View for the case of no accessibility delegate been set. Hence, 23224 * to customize the behavior of a View method, clients can override only the 23225 * corresponding delegate method without altering the behavior of the rest 23226 * accessibility related methods of the host view. 23227 * </p> 23228 * <p> 23229 * <strong>Note:</strong> On platform versions prior to 23230 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23231 * views in the {@code android.widget.*} package are called <i>before</i> 23232 * host methods. This prevents certain properties such as class name from 23233 * being modified by overriding 23234 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23235 * as any changes will be overwritten by the host class. 23236 * <p> 23237 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23238 * methods are called <i>after</i> host methods, which all properties to be 23239 * modified without being overwritten by the host class. 23240 */ 23241 public static class AccessibilityDelegate { 23242 23243 /** 23244 * Sends an accessibility event of the given type. If accessibility is not 23245 * enabled this method has no effect. 23246 * <p> 23247 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23248 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23249 * been set. 23250 * </p> 23251 * 23252 * @param host The View hosting the delegate. 23253 * @param eventType The type of the event to send. 23254 * 23255 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23256 */ 23257 public void sendAccessibilityEvent(View host, int eventType) { 23258 host.sendAccessibilityEventInternal(eventType); 23259 } 23260 23261 /** 23262 * Performs the specified accessibility action on the view. For 23263 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23264 * <p> 23265 * The default implementation behaves as 23266 * {@link View#performAccessibilityAction(int, Bundle) 23267 * View#performAccessibilityAction(int, Bundle)} for the case of 23268 * no accessibility delegate been set. 23269 * </p> 23270 * 23271 * @param action The action to perform. 23272 * @return Whether the action was performed. 23273 * 23274 * @see View#performAccessibilityAction(int, Bundle) 23275 * View#performAccessibilityAction(int, Bundle) 23276 */ 23277 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23278 return host.performAccessibilityActionInternal(action, args); 23279 } 23280 23281 /** 23282 * Sends an accessibility event. This method behaves exactly as 23283 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23284 * empty {@link AccessibilityEvent} and does not perform a check whether 23285 * accessibility is enabled. 23286 * <p> 23287 * The default implementation behaves as 23288 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23289 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23290 * the case of no accessibility delegate been set. 23291 * </p> 23292 * 23293 * @param host The View hosting the delegate. 23294 * @param event The event to send. 23295 * 23296 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23297 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23298 */ 23299 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23300 host.sendAccessibilityEventUncheckedInternal(event); 23301 } 23302 23303 /** 23304 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23305 * to its children for adding their text content to the event. 23306 * <p> 23307 * The default implementation behaves as 23308 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23309 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23310 * the case of no accessibility delegate been set. 23311 * </p> 23312 * 23313 * @param host The View hosting the delegate. 23314 * @param event The event. 23315 * @return True if the event population was completed. 23316 * 23317 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23318 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23319 */ 23320 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23321 return host.dispatchPopulateAccessibilityEventInternal(event); 23322 } 23323 23324 /** 23325 * Gives a chance to the host View to populate the accessibility event with its 23326 * text content. 23327 * <p> 23328 * The default implementation behaves as 23329 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23330 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23331 * the case of no accessibility delegate been set. 23332 * </p> 23333 * 23334 * @param host The View hosting the delegate. 23335 * @param event The accessibility event which to populate. 23336 * 23337 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23338 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23339 */ 23340 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23341 host.onPopulateAccessibilityEventInternal(event); 23342 } 23343 23344 /** 23345 * Initializes an {@link AccessibilityEvent} with information about the 23346 * the host View which is the event source. 23347 * <p> 23348 * The default implementation behaves as 23349 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23350 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23351 * the case of no accessibility delegate been set. 23352 * </p> 23353 * 23354 * @param host The View hosting the delegate. 23355 * @param event The event to initialize. 23356 * 23357 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23358 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23359 */ 23360 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23361 host.onInitializeAccessibilityEventInternal(event); 23362 } 23363 23364 /** 23365 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23366 * <p> 23367 * The default implementation behaves as 23368 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23369 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23370 * the case of no accessibility delegate been set. 23371 * </p> 23372 * 23373 * @param host The View hosting the delegate. 23374 * @param info The instance to initialize. 23375 * 23376 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23377 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23378 */ 23379 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23380 host.onInitializeAccessibilityNodeInfoInternal(info); 23381 } 23382 23383 /** 23384 * Called when a child of the host View has requested sending an 23385 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23386 * to augment the event. 23387 * <p> 23388 * The default implementation behaves as 23389 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23390 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23391 * the case of no accessibility delegate been set. 23392 * </p> 23393 * 23394 * @param host The View hosting the delegate. 23395 * @param child The child which requests sending the event. 23396 * @param event The event to be sent. 23397 * @return True if the event should be sent 23398 * 23399 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23400 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23401 */ 23402 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23403 AccessibilityEvent event) { 23404 return host.onRequestSendAccessibilityEventInternal(child, event); 23405 } 23406 23407 /** 23408 * Gets the provider for managing a virtual view hierarchy rooted at this View 23409 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23410 * that explore the window content. 23411 * <p> 23412 * The default implementation behaves as 23413 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23414 * the case of no accessibility delegate been set. 23415 * </p> 23416 * 23417 * @return The provider. 23418 * 23419 * @see AccessibilityNodeProvider 23420 */ 23421 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23422 return null; 23423 } 23424 23425 /** 23426 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23427 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23428 * This method is responsible for obtaining an accessibility node info from a 23429 * pool of reusable instances and calling 23430 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23431 * view to initialize the former. 23432 * <p> 23433 * <strong>Note:</strong> The client is responsible for recycling the obtained 23434 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23435 * creation. 23436 * </p> 23437 * <p> 23438 * The default implementation behaves as 23439 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23440 * the case of no accessibility delegate been set. 23441 * </p> 23442 * @return A populated {@link AccessibilityNodeInfo}. 23443 * 23444 * @see AccessibilityNodeInfo 23445 * 23446 * @hide 23447 */ 23448 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23449 return host.createAccessibilityNodeInfoInternal(); 23450 } 23451 } 23452 23453 private class MatchIdPredicate implements Predicate<View> { 23454 public int mId; 23455 23456 @Override 23457 public boolean apply(View view) { 23458 return (view.mID == mId); 23459 } 23460 } 23461 23462 private class MatchLabelForPredicate implements Predicate<View> { 23463 private int mLabeledId; 23464 23465 @Override 23466 public boolean apply(View view) { 23467 return (view.mLabelForId == mLabeledId); 23468 } 23469 } 23470 23471 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23472 private int mChangeTypes = 0; 23473 private boolean mPosted; 23474 private boolean mPostedWithDelay; 23475 private long mLastEventTimeMillis; 23476 23477 @Override 23478 public void run() { 23479 mPosted = false; 23480 mPostedWithDelay = false; 23481 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23482 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23483 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23484 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23485 event.setContentChangeTypes(mChangeTypes); 23486 sendAccessibilityEventUnchecked(event); 23487 } 23488 mChangeTypes = 0; 23489 } 23490 23491 public void runOrPost(int changeType) { 23492 mChangeTypes |= changeType; 23493 23494 // If this is a live region or the child of a live region, collect 23495 // all events from this frame and send them on the next frame. 23496 if (inLiveRegion()) { 23497 // If we're already posted with a delay, remove that. 23498 if (mPostedWithDelay) { 23499 removeCallbacks(this); 23500 mPostedWithDelay = false; 23501 } 23502 // Only post if we're not already posted. 23503 if (!mPosted) { 23504 post(this); 23505 mPosted = true; 23506 } 23507 return; 23508 } 23509 23510 if (mPosted) { 23511 return; 23512 } 23513 23514 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23515 final long minEventIntevalMillis = 23516 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23517 if (timeSinceLastMillis >= minEventIntevalMillis) { 23518 removeCallbacks(this); 23519 run(); 23520 } else { 23521 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23522 mPostedWithDelay = true; 23523 } 23524 } 23525 } 23526 23527 private boolean inLiveRegion() { 23528 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23529 return true; 23530 } 23531 23532 ViewParent parent = getParent(); 23533 while (parent instanceof View) { 23534 if (((View) parent).getAccessibilityLiveRegion() 23535 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23536 return true; 23537 } 23538 parent = parent.getParent(); 23539 } 23540 23541 return false; 23542 } 23543 23544 /** 23545 * Dump all private flags in readable format, useful for documentation and 23546 * sanity checking. 23547 */ 23548 private static void dumpFlags() { 23549 final HashMap<String, String> found = Maps.newHashMap(); 23550 try { 23551 for (Field field : View.class.getDeclaredFields()) { 23552 final int modifiers = field.getModifiers(); 23553 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23554 if (field.getType().equals(int.class)) { 23555 final int value = field.getInt(null); 23556 dumpFlag(found, field.getName(), value); 23557 } else if (field.getType().equals(int[].class)) { 23558 final int[] values = (int[]) field.get(null); 23559 for (int i = 0; i < values.length; i++) { 23560 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23561 } 23562 } 23563 } 23564 } 23565 } catch (IllegalAccessException e) { 23566 throw new RuntimeException(e); 23567 } 23568 23569 final ArrayList<String> keys = Lists.newArrayList(); 23570 keys.addAll(found.keySet()); 23571 Collections.sort(keys); 23572 for (String key : keys) { 23573 Log.d(VIEW_LOG_TAG, found.get(key)); 23574 } 23575 } 23576 23577 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23578 // Sort flags by prefix, then by bits, always keeping unique keys 23579 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23580 final int prefix = name.indexOf('_'); 23581 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23582 final String output = bits + " " + name; 23583 found.put(key, output); 23584 } 23585 23586 /** {@hide} */ 23587 public void encode(@NonNull ViewHierarchyEncoder stream) { 23588 stream.beginObject(this); 23589 encodeProperties(stream); 23590 stream.endObject(); 23591 } 23592 23593 /** {@hide} */ 23594 @CallSuper 23595 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23596 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23597 if (resolveId instanceof String) { 23598 stream.addProperty("id", (String) resolveId); 23599 } else { 23600 stream.addProperty("id", mID); 23601 } 23602 23603 stream.addProperty("misc:transformation.alpha", 23604 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23605 stream.addProperty("misc:transitionName", getTransitionName()); 23606 23607 // layout 23608 stream.addProperty("layout:left", mLeft); 23609 stream.addProperty("layout:right", mRight); 23610 stream.addProperty("layout:top", mTop); 23611 stream.addProperty("layout:bottom", mBottom); 23612 stream.addProperty("layout:width", getWidth()); 23613 stream.addProperty("layout:height", getHeight()); 23614 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23615 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23616 stream.addProperty("layout:hasTransientState", hasTransientState()); 23617 stream.addProperty("layout:baseline", getBaseline()); 23618 23619 // layout params 23620 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23621 if (layoutParams != null) { 23622 stream.addPropertyKey("layoutParams"); 23623 layoutParams.encode(stream); 23624 } 23625 23626 // scrolling 23627 stream.addProperty("scrolling:scrollX", mScrollX); 23628 stream.addProperty("scrolling:scrollY", mScrollY); 23629 23630 // padding 23631 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23632 stream.addProperty("padding:paddingRight", mPaddingRight); 23633 stream.addProperty("padding:paddingTop", mPaddingTop); 23634 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23635 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23636 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23637 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23638 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23639 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23640 23641 // measurement 23642 stream.addProperty("measurement:minHeight", mMinHeight); 23643 stream.addProperty("measurement:minWidth", mMinWidth); 23644 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23645 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23646 23647 // drawing 23648 stream.addProperty("drawing:elevation", getElevation()); 23649 stream.addProperty("drawing:translationX", getTranslationX()); 23650 stream.addProperty("drawing:translationY", getTranslationY()); 23651 stream.addProperty("drawing:translationZ", getTranslationZ()); 23652 stream.addProperty("drawing:rotation", getRotation()); 23653 stream.addProperty("drawing:rotationX", getRotationX()); 23654 stream.addProperty("drawing:rotationY", getRotationY()); 23655 stream.addProperty("drawing:scaleX", getScaleX()); 23656 stream.addProperty("drawing:scaleY", getScaleY()); 23657 stream.addProperty("drawing:pivotX", getPivotX()); 23658 stream.addProperty("drawing:pivotY", getPivotY()); 23659 stream.addProperty("drawing:opaque", isOpaque()); 23660 stream.addProperty("drawing:alpha", getAlpha()); 23661 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23662 stream.addProperty("drawing:shadow", hasShadow()); 23663 stream.addProperty("drawing:solidColor", getSolidColor()); 23664 stream.addProperty("drawing:layerType", mLayerType); 23665 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23666 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23667 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23668 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23669 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23670 23671 // focus 23672 stream.addProperty("focus:hasFocus", hasFocus()); 23673 stream.addProperty("focus:isFocused", isFocused()); 23674 stream.addProperty("focus:isFocusable", isFocusable()); 23675 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23676 23677 stream.addProperty("misc:clickable", isClickable()); 23678 stream.addProperty("misc:pressed", isPressed()); 23679 stream.addProperty("misc:selected", isSelected()); 23680 stream.addProperty("misc:touchMode", isInTouchMode()); 23681 stream.addProperty("misc:hovered", isHovered()); 23682 stream.addProperty("misc:activated", isActivated()); 23683 23684 stream.addProperty("misc:visibility", getVisibility()); 23685 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23686 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23687 23688 stream.addProperty("misc:enabled", isEnabled()); 23689 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23690 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23691 23692 // theme attributes 23693 Resources.Theme theme = getContext().getTheme(); 23694 if (theme != null) { 23695 stream.addPropertyKey("theme"); 23696 theme.encode(stream); 23697 } 23698 23699 // view attribute information 23700 int n = mAttributes != null ? mAttributes.length : 0; 23701 stream.addProperty("meta:__attrCount__", n/2); 23702 for (int i = 0; i < n; i += 2) { 23703 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23704 } 23705 23706 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23707 23708 // text 23709 stream.addProperty("text:textDirection", getTextDirection()); 23710 stream.addProperty("text:textAlignment", getTextAlignment()); 23711 23712 // accessibility 23713 CharSequence contentDescription = getContentDescription(); 23714 stream.addProperty("accessibility:contentDescription", 23715 contentDescription == null ? "" : contentDescription.toString()); 23716 stream.addProperty("accessibility:labelFor", getLabelFor()); 23717 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23718 } 23719} 23720