View.java revision 33e3036a38d0c32ab3e69a93116e3e6cce232030
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.LayoutRes; 28import android.annotation.NonNull; 29import android.annotation.Nullable; 30import android.annotation.Size; 31import android.content.ClipData; 32import android.content.Context; 33import android.content.res.ColorStateList; 34import android.content.res.Configuration; 35import android.content.res.Resources; 36import android.content.res.TypedArray; 37import android.graphics.Bitmap; 38import android.graphics.Canvas; 39import android.graphics.Insets; 40import android.graphics.Interpolator; 41import android.graphics.LinearGradient; 42import android.graphics.Matrix; 43import android.graphics.Outline; 44import android.graphics.Paint; 45import android.graphics.PixelFormat; 46import android.graphics.Point; 47import android.graphics.PorterDuff; 48import android.graphics.PorterDuffXfermode; 49import android.graphics.Rect; 50import android.graphics.RectF; 51import android.graphics.Region; 52import android.graphics.Shader; 53import android.graphics.drawable.ColorDrawable; 54import android.graphics.drawable.Drawable; 55import android.hardware.display.DisplayManagerGlobal; 56import android.os.Bundle; 57import android.os.Handler; 58import android.os.IBinder; 59import android.os.Parcel; 60import android.os.Parcelable; 61import android.os.RemoteException; 62import android.os.SystemClock; 63import android.os.SystemProperties; 64import android.os.Trace; 65import android.text.TextUtils; 66import android.util.AttributeSet; 67import android.util.FloatProperty; 68import android.util.LayoutDirection; 69import android.util.Log; 70import android.util.LongSparseLongArray; 71import android.util.Pools.SynchronizedPool; 72import android.util.Property; 73import android.util.SparseArray; 74import android.util.StateSet; 75import android.util.SuperNotCalledException; 76import android.util.TypedValue; 77import android.view.ContextMenu.ContextMenuInfo; 78import android.view.AccessibilityIterators.TextSegmentIterator; 79import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 80import android.view.AccessibilityIterators.WordTextSegmentIterator; 81import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 82import android.view.accessibility.AccessibilityEvent; 83import android.view.accessibility.AccessibilityEventSource; 84import android.view.accessibility.AccessibilityManager; 85import android.view.accessibility.AccessibilityNodeInfo; 86import android.view.accessibility.AccessibilityNodeProvider; 87import android.view.animation.Animation; 88import android.view.animation.AnimationUtils; 89import android.view.animation.Transformation; 90import android.view.inputmethod.EditorInfo; 91import android.view.inputmethod.InputConnection; 92import android.view.inputmethod.InputMethodManager; 93import android.widget.ScrollBarDrawable; 94 95import static android.os.Build.VERSION_CODES.*; 96import static java.lang.Math.max; 97 98import com.android.internal.R; 99import com.android.internal.util.Predicate; 100import com.android.internal.view.menu.MenuBuilder; 101import com.google.android.collect.Lists; 102import com.google.android.collect.Maps; 103 104import java.lang.annotation.Retention; 105import java.lang.annotation.RetentionPolicy; 106import java.lang.ref.WeakReference; 107import java.lang.reflect.Field; 108import java.lang.reflect.InvocationTargetException; 109import java.lang.reflect.Method; 110import java.lang.reflect.Modifier; 111import java.util.ArrayList; 112import java.util.Arrays; 113import java.util.Collections; 114import java.util.HashMap; 115import java.util.List; 116import java.util.Locale; 117import java.util.Map; 118import java.util.concurrent.CopyOnWriteArrayList; 119import java.util.concurrent.atomic.AtomicInteger; 120 121/** 122 * <p> 123 * This class represents the basic building block for user interface components. A View 124 * occupies a rectangular area on the screen and is responsible for drawing and 125 * event handling. View is the base class for <em>widgets</em>, which are 126 * used to create interactive UI components (buttons, text fields, etc.). The 127 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 128 * are invisible containers that hold other Views (or other ViewGroups) and define 129 * their layout properties. 130 * </p> 131 * 132 * <div class="special reference"> 133 * <h3>Developer Guides</h3> 134 * <p>For information about using this class to develop your application's user interface, 135 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 136 * </div> 137 * 138 * <a name="Using"></a> 139 * <h3>Using Views</h3> 140 * <p> 141 * All of the views in a window are arranged in a single tree. You can add views 142 * either from code or by specifying a tree of views in one or more XML layout 143 * files. There are many specialized subclasses of views that act as controls or 144 * are capable of displaying text, images, or other content. 145 * </p> 146 * <p> 147 * Once you have created a tree of views, there are typically a few types of 148 * common operations you may wish to perform: 149 * <ul> 150 * <li><strong>Set properties:</strong> for example setting the text of a 151 * {@link android.widget.TextView}. The available properties and the methods 152 * that set them will vary among the different subclasses of views. Note that 153 * properties that are known at build time can be set in the XML layout 154 * files.</li> 155 * <li><strong>Set focus:</strong> The framework will handled moving focus in 156 * response to user input. To force focus to a specific view, call 157 * {@link #requestFocus}.</li> 158 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 159 * that will be notified when something interesting happens to the view. For 160 * example, all views will let you set a listener to be notified when the view 161 * gains or loses focus. You can register such a listener using 162 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 163 * Other view subclasses offer more specialized listeners. For example, a Button 164 * exposes a listener to notify clients when the button is clicked.</li> 165 * <li><strong>Set visibility:</strong> You can hide or show views using 166 * {@link #setVisibility(int)}.</li> 167 * </ul> 168 * </p> 169 * <p><em> 170 * Note: The Android framework is responsible for measuring, laying out and 171 * drawing views. You should not call methods that perform these actions on 172 * views yourself unless you are actually implementing a 173 * {@link android.view.ViewGroup}. 174 * </em></p> 175 * 176 * <a name="Lifecycle"></a> 177 * <h3>Implementing a Custom View</h3> 178 * 179 * <p> 180 * To implement a custom view, you will usually begin by providing overrides for 181 * some of the standard methods that the framework calls on all views. You do 182 * not need to override all of these methods. In fact, you can start by just 183 * overriding {@link #onDraw(android.graphics.Canvas)}. 184 * <table border="2" width="85%" align="center" cellpadding="5"> 185 * <thead> 186 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 187 * </thead> 188 * 189 * <tbody> 190 * <tr> 191 * <td rowspan="2">Creation</td> 192 * <td>Constructors</td> 193 * <td>There is a form of the constructor that are called when the view 194 * is created from code and a form that is called when the view is 195 * inflated from a layout file. The second form should parse and apply 196 * any attributes defined in the layout file. 197 * </td> 198 * </tr> 199 * <tr> 200 * <td><code>{@link #onFinishInflate()}</code></td> 201 * <td>Called after a view and all of its children has been inflated 202 * from XML.</td> 203 * </tr> 204 * 205 * <tr> 206 * <td rowspan="3">Layout</td> 207 * <td><code>{@link #onMeasure(int, int)}</code></td> 208 * <td>Called to determine the size requirements for this view and all 209 * of its children. 210 * </td> 211 * </tr> 212 * <tr> 213 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 214 * <td>Called when this view should assign a size and position to all 215 * of its children. 216 * </td> 217 * </tr> 218 * <tr> 219 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 220 * <td>Called when the size of this view has changed. 221 * </td> 222 * </tr> 223 * 224 * <tr> 225 * <td>Drawing</td> 226 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 227 * <td>Called when the view should render its content. 228 * </td> 229 * </tr> 230 * 231 * <tr> 232 * <td rowspan="4">Event processing</td> 233 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 234 * <td>Called when a new hardware key event occurs. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 239 * <td>Called when a hardware key up event occurs. 240 * </td> 241 * </tr> 242 * <tr> 243 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 244 * <td>Called when a trackball motion event occurs. 245 * </td> 246 * </tr> 247 * <tr> 248 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 249 * <td>Called when a touch screen motion event occurs. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td rowspan="2">Focus</td> 255 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 256 * <td>Called when the view gains or loses focus. 257 * </td> 258 * </tr> 259 * 260 * <tr> 261 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 262 * <td>Called when the window containing the view gains or loses focus. 263 * </td> 264 * </tr> 265 * 266 * <tr> 267 * <td rowspan="3">Attaching</td> 268 * <td><code>{@link #onAttachedToWindow()}</code></td> 269 * <td>Called when the view is attached to a window. 270 * </td> 271 * </tr> 272 * 273 * <tr> 274 * <td><code>{@link #onDetachedFromWindow}</code></td> 275 * <td>Called when the view is detached from its window. 276 * </td> 277 * </tr> 278 * 279 * <tr> 280 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 281 * <td>Called when the visibility of the window containing the view 282 * has changed. 283 * </td> 284 * </tr> 285 * </tbody> 286 * 287 * </table> 288 * </p> 289 * 290 * <a name="IDs"></a> 291 * <h3>IDs</h3> 292 * Views may have an integer id associated with them. These ids are typically 293 * assigned in the layout XML files, and are used to find specific views within 294 * the view tree. A common pattern is to: 295 * <ul> 296 * <li>Define a Button in the layout file and assign it a unique ID. 297 * <pre> 298 * <Button 299 * android:id="@+id/my_button" 300 * android:layout_width="wrap_content" 301 * android:layout_height="wrap_content" 302 * android:text="@string/my_button_text"/> 303 * </pre></li> 304 * <li>From the onCreate method of an Activity, find the Button 305 * <pre class="prettyprint"> 306 * Button myButton = (Button) findViewById(R.id.my_button); 307 * </pre></li> 308 * </ul> 309 * <p> 310 * View IDs need not be unique throughout the tree, but it is good practice to 311 * ensure that they are at least unique within the part of the tree you are 312 * searching. 313 * </p> 314 * 315 * <a name="Position"></a> 316 * <h3>Position</h3> 317 * <p> 318 * The geometry of a view is that of a rectangle. A view has a location, 319 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 320 * two dimensions, expressed as a width and a height. The unit for location 321 * and dimensions is the pixel. 322 * </p> 323 * 324 * <p> 325 * It is possible to retrieve the location of a view by invoking the methods 326 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 327 * coordinate of the rectangle representing the view. The latter returns the 328 * top, or Y, coordinate of the rectangle representing the view. These methods 329 * both return the location of the view relative to its parent. For instance, 330 * when getLeft() returns 20, that means the view is located 20 pixels to the 331 * right of the left edge of its direct parent. 332 * </p> 333 * 334 * <p> 335 * In addition, several convenience methods are offered to avoid unnecessary 336 * computations, namely {@link #getRight()} and {@link #getBottom()}. 337 * These methods return the coordinates of the right and bottom edges of the 338 * rectangle representing the view. For instance, calling {@link #getRight()} 339 * is similar to the following computation: <code>getLeft() + getWidth()</code> 340 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 341 * </p> 342 * 343 * <a name="SizePaddingMargins"></a> 344 * <h3>Size, padding and margins</h3> 345 * <p> 346 * The size of a view is expressed with a width and a height. A view actually 347 * possess two pairs of width and height values. 348 * </p> 349 * 350 * <p> 351 * The first pair is known as <em>measured width</em> and 352 * <em>measured height</em>. These dimensions define how big a view wants to be 353 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 354 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 355 * and {@link #getMeasuredHeight()}. 356 * </p> 357 * 358 * <p> 359 * The second pair is simply known as <em>width</em> and <em>height</em>, or 360 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 361 * dimensions define the actual size of the view on screen, at drawing time and 362 * after layout. These values may, but do not have to, be different from the 363 * measured width and height. The width and height can be obtained by calling 364 * {@link #getWidth()} and {@link #getHeight()}. 365 * </p> 366 * 367 * <p> 368 * To measure its dimensions, a view takes into account its padding. The padding 369 * is expressed in pixels for the left, top, right and bottom parts of the view. 370 * Padding can be used to offset the content of the view by a specific amount of 371 * pixels. For instance, a left padding of 2 will push the view's content by 372 * 2 pixels to the right of the left edge. Padding can be set using the 373 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 374 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 375 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 376 * {@link #getPaddingEnd()}. 377 * </p> 378 * 379 * <p> 380 * Even though a view can define a padding, it does not provide any support for 381 * margins. However, view groups provide such a support. Refer to 382 * {@link android.view.ViewGroup} and 383 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 384 * </p> 385 * 386 * <a name="Layout"></a> 387 * <h3>Layout</h3> 388 * <p> 389 * Layout is a two pass process: a measure pass and a layout pass. The measuring 390 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 391 * of the view tree. Each view pushes dimension specifications down the tree 392 * during the recursion. At the end of the measure pass, every view has stored 393 * its measurements. The second pass happens in 394 * {@link #layout(int,int,int,int)} and is also top-down. During 395 * this pass each parent is responsible for positioning all of its children 396 * using the sizes computed in the measure pass. 397 * </p> 398 * 399 * <p> 400 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 401 * {@link #getMeasuredHeight()} values must be set, along with those for all of 402 * that view's descendants. A view's measured width and measured height values 403 * must respect the constraints imposed by the view's parents. This guarantees 404 * that at the end of the measure pass, all parents accept all of their 405 * children's measurements. A parent view may call measure() more than once on 406 * its children. For example, the parent may measure each child once with 407 * unspecified dimensions to find out how big they want to be, then call 408 * measure() on them again with actual numbers if the sum of all the children's 409 * unconstrained sizes is too big or too small. 410 * </p> 411 * 412 * <p> 413 * The measure pass uses two classes to communicate dimensions. The 414 * {@link MeasureSpec} class is used by views to tell their parents how they 415 * want to be measured and positioned. The base LayoutParams class just 416 * describes how big the view wants to be for both width and height. For each 417 * dimension, it can specify one of: 418 * <ul> 419 * <li> an exact number 420 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 421 * (minus padding) 422 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 423 * enclose its content (plus padding). 424 * </ul> 425 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 426 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 427 * an X and Y value. 428 * </p> 429 * 430 * <p> 431 * MeasureSpecs are used to push requirements down the tree from parent to 432 * child. A MeasureSpec can be in one of three modes: 433 * <ul> 434 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 435 * of a child view. For example, a LinearLayout may call measure() on its child 436 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 437 * tall the child view wants to be given a width of 240 pixels. 438 * <li>EXACTLY: This is used by the parent to impose an exact size on the 439 * child. The child must use this size, and guarantee that all of its 440 * descendants will fit within this size. 441 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 442 * child. The child must guarantee that it and all of its descendants will fit 443 * within this size. 444 * </ul> 445 * </p> 446 * 447 * <p> 448 * To initiate a layout, call {@link #requestLayout}. This method is typically 449 * called by a view on itself when it believes that is can no longer fit within 450 * its current bounds. 451 * </p> 452 * 453 * <a name="Drawing"></a> 454 * <h3>Drawing</h3> 455 * <p> 456 * Drawing is handled by walking the tree and recording the drawing commands of 457 * any View that needs to update. After this, the drawing commands of the 458 * entire tree are issued to screen, clipped to the newly damaged area. 459 * </p> 460 * 461 * <p> 462 * The tree is largely recorded and drawn in order, with parents drawn before 463 * (i.e., behind) their children, with siblings drawn in the order they appear 464 * in the tree. If you set a background drawable for a View, then the View will 465 * draw it before calling back to its <code>onDraw()</code> method. The child 466 * drawing order can be overridden with 467 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 468 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 469 * </p> 470 * 471 * <p> 472 * To force a view to draw, call {@link #invalidate()}. 473 * </p> 474 * 475 * <a name="EventHandlingThreading"></a> 476 * <h3>Event Handling and Threading</h3> 477 * <p> 478 * The basic cycle of a view is as follows: 479 * <ol> 480 * <li>An event comes in and is dispatched to the appropriate view. The view 481 * handles the event and notifies any listeners.</li> 482 * <li>If in the course of processing the event, the view's bounds may need 483 * to be changed, the view will call {@link #requestLayout()}.</li> 484 * <li>Similarly, if in the course of processing the event the view's appearance 485 * may need to be changed, the view will call {@link #invalidate()}.</li> 486 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 487 * the framework will take care of measuring, laying out, and drawing the tree 488 * as appropriate.</li> 489 * </ol> 490 * </p> 491 * 492 * <p><em>Note: The entire view tree is single threaded. You must always be on 493 * the UI thread when calling any method on any view.</em> 494 * If you are doing work on other threads and want to update the state of a view 495 * from that thread, you should use a {@link Handler}. 496 * </p> 497 * 498 * <a name="FocusHandling"></a> 499 * <h3>Focus Handling</h3> 500 * <p> 501 * The framework will handle routine focus movement in response to user input. 502 * This includes changing the focus as views are removed or hidden, or as new 503 * views become available. Views indicate their willingness to take focus 504 * through the {@link #isFocusable} method. To change whether a view can take 505 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 506 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 507 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 508 * </p> 509 * <p> 510 * Focus movement is based on an algorithm which finds the nearest neighbor in a 511 * given direction. In rare cases, the default algorithm may not match the 512 * intended behavior of the developer. In these situations, you can provide 513 * explicit overrides by using these XML attributes in the layout file: 514 * <pre> 515 * nextFocusDown 516 * nextFocusLeft 517 * nextFocusRight 518 * nextFocusUp 519 * </pre> 520 * </p> 521 * 522 * 523 * <p> 524 * To get a particular view to take focus, call {@link #requestFocus()}. 525 * </p> 526 * 527 * <a name="TouchMode"></a> 528 * <h3>Touch Mode</h3> 529 * <p> 530 * When a user is navigating a user interface via directional keys such as a D-pad, it is 531 * necessary to give focus to actionable items such as buttons so the user can see 532 * what will take input. If the device has touch capabilities, however, and the user 533 * begins interacting with the interface by touching it, it is no longer necessary to 534 * always highlight, or give focus to, a particular view. This motivates a mode 535 * for interaction named 'touch mode'. 536 * </p> 537 * <p> 538 * For a touch capable device, once the user touches the screen, the device 539 * will enter touch mode. From this point onward, only views for which 540 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 541 * Other views that are touchable, like buttons, will not take focus when touched; they will 542 * only fire the on click listeners. 543 * </p> 544 * <p> 545 * Any time a user hits a directional key, such as a D-pad direction, the view device will 546 * exit touch mode, and find a view to take focus, so that the user may resume interacting 547 * with the user interface without touching the screen again. 548 * </p> 549 * <p> 550 * The touch mode state is maintained across {@link android.app.Activity}s. Call 551 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 552 * </p> 553 * 554 * <a name="Scrolling"></a> 555 * <h3>Scrolling</h3> 556 * <p> 557 * The framework provides basic support for views that wish to internally 558 * scroll their content. This includes keeping track of the X and Y scroll 559 * offset as well as mechanisms for drawing scrollbars. See 560 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 561 * {@link #awakenScrollBars()} for more details. 562 * </p> 563 * 564 * <a name="Tags"></a> 565 * <h3>Tags</h3> 566 * <p> 567 * Unlike IDs, tags are not used to identify views. Tags are essentially an 568 * extra piece of information that can be associated with a view. They are most 569 * often used as a convenience to store data related to views in the views 570 * themselves rather than by putting them in a separate structure. 571 * </p> 572 * 573 * <a name="Properties"></a> 574 * <h3>Properties</h3> 575 * <p> 576 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 577 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 578 * available both in the {@link Property} form as well as in similarly-named setter/getter 579 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 580 * be used to set persistent state associated with these rendering-related properties on the view. 581 * The properties and methods can also be used in conjunction with 582 * {@link android.animation.Animator Animator}-based animations, described more in the 583 * <a href="#Animation">Animation</a> section. 584 * </p> 585 * 586 * <a name="Animation"></a> 587 * <h3>Animation</h3> 588 * <p> 589 * Starting with Android 3.0, the preferred way of animating views is to use the 590 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 591 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 592 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 593 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 594 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 595 * makes animating these View properties particularly easy and efficient. 596 * </p> 597 * <p> 598 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 599 * You can attach an {@link Animation} object to a view using 600 * {@link #setAnimation(Animation)} or 601 * {@link #startAnimation(Animation)}. The animation can alter the scale, 602 * rotation, translation and alpha of a view over time. If the animation is 603 * attached to a view that has children, the animation will affect the entire 604 * subtree rooted by that node. When an animation is started, the framework will 605 * take care of redrawing the appropriate views until the animation completes. 606 * </p> 607 * 608 * <a name="Security"></a> 609 * <h3>Security</h3> 610 * <p> 611 * Sometimes it is essential that an application be able to verify that an action 612 * is being performed with the full knowledge and consent of the user, such as 613 * granting a permission request, making a purchase or clicking on an advertisement. 614 * Unfortunately, a malicious application could try to spoof the user into 615 * performing these actions, unaware, by concealing the intended purpose of the view. 616 * As a remedy, the framework offers a touch filtering mechanism that can be used to 617 * improve the security of views that provide access to sensitive functionality. 618 * </p><p> 619 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 620 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 621 * will discard touches that are received whenever the view's window is obscured by 622 * another visible window. As a result, the view will not receive touches whenever a 623 * toast, dialog or other window appears above the view's window. 624 * </p><p> 625 * For more fine-grained control over security, consider overriding the 626 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 627 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 628 * </p> 629 * 630 * @attr ref android.R.styleable#View_alpha 631 * @attr ref android.R.styleable#View_background 632 * @attr ref android.R.styleable#View_clickable 633 * @attr ref android.R.styleable#View_contentDescription 634 * @attr ref android.R.styleable#View_drawingCacheQuality 635 * @attr ref android.R.styleable#View_duplicateParentState 636 * @attr ref android.R.styleable#View_id 637 * @attr ref android.R.styleable#View_requiresFadingEdge 638 * @attr ref android.R.styleable#View_fadeScrollbars 639 * @attr ref android.R.styleable#View_fadingEdgeLength 640 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 641 * @attr ref android.R.styleable#View_fitsSystemWindows 642 * @attr ref android.R.styleable#View_isScrollContainer 643 * @attr ref android.R.styleable#View_focusable 644 * @attr ref android.R.styleable#View_focusableInTouchMode 645 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 646 * @attr ref android.R.styleable#View_keepScreenOn 647 * @attr ref android.R.styleable#View_layerType 648 * @attr ref android.R.styleable#View_layoutDirection 649 * @attr ref android.R.styleable#View_longClickable 650 * @attr ref android.R.styleable#View_minHeight 651 * @attr ref android.R.styleable#View_minWidth 652 * @attr ref android.R.styleable#View_nextFocusDown 653 * @attr ref android.R.styleable#View_nextFocusLeft 654 * @attr ref android.R.styleable#View_nextFocusRight 655 * @attr ref android.R.styleable#View_nextFocusUp 656 * @attr ref android.R.styleable#View_onClick 657 * @attr ref android.R.styleable#View_padding 658 * @attr ref android.R.styleable#View_paddingBottom 659 * @attr ref android.R.styleable#View_paddingLeft 660 * @attr ref android.R.styleable#View_paddingRight 661 * @attr ref android.R.styleable#View_paddingTop 662 * @attr ref android.R.styleable#View_paddingStart 663 * @attr ref android.R.styleable#View_paddingEnd 664 * @attr ref android.R.styleable#View_saveEnabled 665 * @attr ref android.R.styleable#View_rotation 666 * @attr ref android.R.styleable#View_rotationX 667 * @attr ref android.R.styleable#View_rotationY 668 * @attr ref android.R.styleable#View_scaleX 669 * @attr ref android.R.styleable#View_scaleY 670 * @attr ref android.R.styleable#View_scrollX 671 * @attr ref android.R.styleable#View_scrollY 672 * @attr ref android.R.styleable#View_scrollbarSize 673 * @attr ref android.R.styleable#View_scrollbarStyle 674 * @attr ref android.R.styleable#View_scrollbars 675 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 676 * @attr ref android.R.styleable#View_scrollbarFadeDuration 677 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 678 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 679 * @attr ref android.R.styleable#View_scrollbarThumbVertical 680 * @attr ref android.R.styleable#View_scrollbarTrackVertical 681 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 682 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 683 * @attr ref android.R.styleable#View_stateListAnimator 684 * @attr ref android.R.styleable#View_transitionName 685 * @attr ref android.R.styleable#View_soundEffectsEnabled 686 * @attr ref android.R.styleable#View_tag 687 * @attr ref android.R.styleable#View_textAlignment 688 * @attr ref android.R.styleable#View_textDirection 689 * @attr ref android.R.styleable#View_transformPivotX 690 * @attr ref android.R.styleable#View_transformPivotY 691 * @attr ref android.R.styleable#View_translationX 692 * @attr ref android.R.styleable#View_translationY 693 * @attr ref android.R.styleable#View_translationZ 694 * @attr ref android.R.styleable#View_visibility 695 * 696 * @see android.view.ViewGroup 697 */ 698public class View implements Drawable.Callback, KeyEvent.Callback, 699 AccessibilityEventSource { 700 private static final boolean DBG = false; 701 702 /** 703 * The logging tag used by this class with android.util.Log. 704 */ 705 protected static final String VIEW_LOG_TAG = "View"; 706 707 /** 708 * When set to true, apps will draw debugging information about their layouts. 709 * 710 * @hide 711 */ 712 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 713 714 /** 715 * When set to true, this view will save its attribute data. 716 * 717 * @hide 718 */ 719 public static boolean mDebugViewAttributes = false; 720 721 /** 722 * Used to mark a View that has no ID. 723 */ 724 public static final int NO_ID = -1; 725 726 /** 727 * Signals that compatibility booleans have been initialized according to 728 * target SDK versions. 729 */ 730 private static boolean sCompatibilityDone = false; 731 732 /** 733 * Use the old (broken) way of building MeasureSpecs. 734 */ 735 private static boolean sUseBrokenMakeMeasureSpec = false; 736 737 /** 738 * Ignore any optimizations using the measure cache. 739 */ 740 private static boolean sIgnoreMeasureCache = false; 741 742 /** 743 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 744 * calling setFlags. 745 */ 746 private static final int NOT_FOCUSABLE = 0x00000000; 747 748 /** 749 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 750 * setFlags. 751 */ 752 private static final int FOCUSABLE = 0x00000001; 753 754 /** 755 * Mask for use with setFlags indicating bits used for focus. 756 */ 757 private static final int FOCUSABLE_MASK = 0x00000001; 758 759 /** 760 * This view will adjust its padding to fit sytem windows (e.g. status bar) 761 */ 762 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 763 764 /** @hide */ 765 @IntDef({VISIBLE, INVISIBLE, GONE}) 766 @Retention(RetentionPolicy.SOURCE) 767 public @interface Visibility {} 768 769 /** 770 * This view is visible. 771 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 772 * android:visibility}. 773 */ 774 public static final int VISIBLE = 0x00000000; 775 776 /** 777 * This view is invisible, but it still takes up space for layout purposes. 778 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 779 * android:visibility}. 780 */ 781 public static final int INVISIBLE = 0x00000004; 782 783 /** 784 * This view is invisible, and it doesn't take any space for layout 785 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 786 * android:visibility}. 787 */ 788 public static final int GONE = 0x00000008; 789 790 /** 791 * Mask for use with setFlags indicating bits used for visibility. 792 * {@hide} 793 */ 794 static final int VISIBILITY_MASK = 0x0000000C; 795 796 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 797 798 /** 799 * This view is enabled. Interpretation varies by subclass. 800 * Use with ENABLED_MASK when calling setFlags. 801 * {@hide} 802 */ 803 static final int ENABLED = 0x00000000; 804 805 /** 806 * This view is disabled. Interpretation varies by subclass. 807 * Use with ENABLED_MASK when calling setFlags. 808 * {@hide} 809 */ 810 static final int DISABLED = 0x00000020; 811 812 /** 813 * Mask for use with setFlags indicating bits used for indicating whether 814 * this view is enabled 815 * {@hide} 816 */ 817 static final int ENABLED_MASK = 0x00000020; 818 819 /** 820 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 821 * called and further optimizations will be performed. It is okay to have 822 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 823 * {@hide} 824 */ 825 static final int WILL_NOT_DRAW = 0x00000080; 826 827 /** 828 * Mask for use with setFlags indicating bits used for indicating whether 829 * this view is will draw 830 * {@hide} 831 */ 832 static final int DRAW_MASK = 0x00000080; 833 834 /** 835 * <p>This view doesn't show scrollbars.</p> 836 * {@hide} 837 */ 838 static final int SCROLLBARS_NONE = 0x00000000; 839 840 /** 841 * <p>This view shows horizontal scrollbars.</p> 842 * {@hide} 843 */ 844 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 845 846 /** 847 * <p>This view shows vertical scrollbars.</p> 848 * {@hide} 849 */ 850 static final int SCROLLBARS_VERTICAL = 0x00000200; 851 852 /** 853 * <p>Mask for use with setFlags indicating bits used for indicating which 854 * scrollbars are enabled.</p> 855 * {@hide} 856 */ 857 static final int SCROLLBARS_MASK = 0x00000300; 858 859 /** 860 * Indicates that the view should filter touches when its window is obscured. 861 * Refer to the class comments for more information about this security feature. 862 * {@hide} 863 */ 864 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 865 866 /** 867 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 868 * that they are optional and should be skipped if the window has 869 * requested system UI flags that ignore those insets for layout. 870 */ 871 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 872 873 /** 874 * <p>This view doesn't show fading edges.</p> 875 * {@hide} 876 */ 877 static final int FADING_EDGE_NONE = 0x00000000; 878 879 /** 880 * <p>This view shows horizontal fading edges.</p> 881 * {@hide} 882 */ 883 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 884 885 /** 886 * <p>This view shows vertical fading edges.</p> 887 * {@hide} 888 */ 889 static final int FADING_EDGE_VERTICAL = 0x00002000; 890 891 /** 892 * <p>Mask for use with setFlags indicating bits used for indicating which 893 * fading edges are enabled.</p> 894 * {@hide} 895 */ 896 static final int FADING_EDGE_MASK = 0x00003000; 897 898 /** 899 * <p>Indicates this view can be clicked. When clickable, a View reacts 900 * to clicks by notifying the OnClickListener.<p> 901 * {@hide} 902 */ 903 static final int CLICKABLE = 0x00004000; 904 905 /** 906 * <p>Indicates this view is caching its drawing into a bitmap.</p> 907 * {@hide} 908 */ 909 static final int DRAWING_CACHE_ENABLED = 0x00008000; 910 911 /** 912 * <p>Indicates that no icicle should be saved for this view.<p> 913 * {@hide} 914 */ 915 static final int SAVE_DISABLED = 0x000010000; 916 917 /** 918 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 919 * property.</p> 920 * {@hide} 921 */ 922 static final int SAVE_DISABLED_MASK = 0x000010000; 923 924 /** 925 * <p>Indicates that no drawing cache should ever be created for this view.<p> 926 * {@hide} 927 */ 928 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 929 930 /** 931 * <p>Indicates this view can take / keep focus when int touch mode.</p> 932 * {@hide} 933 */ 934 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 935 936 /** @hide */ 937 @Retention(RetentionPolicy.SOURCE) 938 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 939 public @interface DrawingCacheQuality {} 940 941 /** 942 * <p>Enables low quality mode for the drawing cache.</p> 943 */ 944 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 945 946 /** 947 * <p>Enables high quality mode for the drawing cache.</p> 948 */ 949 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 950 951 /** 952 * <p>Enables automatic quality mode for the drawing cache.</p> 953 */ 954 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 955 956 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 957 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 958 }; 959 960 /** 961 * <p>Mask for use with setFlags indicating bits used for the cache 962 * quality property.</p> 963 * {@hide} 964 */ 965 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 966 967 /** 968 * <p> 969 * Indicates this view can be long clicked. When long clickable, a View 970 * reacts to long clicks by notifying the OnLongClickListener or showing a 971 * context menu. 972 * </p> 973 * {@hide} 974 */ 975 static final int LONG_CLICKABLE = 0x00200000; 976 977 /** 978 * <p>Indicates that this view gets its drawable states from its direct parent 979 * and ignores its original internal states.</p> 980 * 981 * @hide 982 */ 983 static final int DUPLICATE_PARENT_STATE = 0x00400000; 984 985 /** @hide */ 986 @IntDef({ 987 SCROLLBARS_INSIDE_OVERLAY, 988 SCROLLBARS_INSIDE_INSET, 989 SCROLLBARS_OUTSIDE_OVERLAY, 990 SCROLLBARS_OUTSIDE_INSET 991 }) 992 @Retention(RetentionPolicy.SOURCE) 993 public @interface ScrollBarStyle {} 994 995 /** 996 * The scrollbar style to display the scrollbars inside the content area, 997 * without increasing the padding. The scrollbars will be overlaid with 998 * translucency on the view's content. 999 */ 1000 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1001 1002 /** 1003 * The scrollbar style to display the scrollbars inside the padded area, 1004 * increasing the padding of the view. The scrollbars will not overlap the 1005 * content area of the view. 1006 */ 1007 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1008 1009 /** 1010 * The scrollbar style to display the scrollbars at the edge of the view, 1011 * without increasing the padding. The scrollbars will be overlaid with 1012 * translucency. 1013 */ 1014 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1015 1016 /** 1017 * The scrollbar style to display the scrollbars at the edge of the view, 1018 * increasing the padding of the view. The scrollbars will only overlap the 1019 * background, if any. 1020 */ 1021 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1022 1023 /** 1024 * Mask to check if the scrollbar style is overlay or inset. 1025 * {@hide} 1026 */ 1027 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1028 1029 /** 1030 * Mask to check if the scrollbar style is inside or outside. 1031 * {@hide} 1032 */ 1033 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1034 1035 /** 1036 * Mask for scrollbar style. 1037 * {@hide} 1038 */ 1039 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1040 1041 /** 1042 * View flag indicating that the screen should remain on while the 1043 * window containing this view is visible to the user. This effectively 1044 * takes care of automatically setting the WindowManager's 1045 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1046 */ 1047 public static final int KEEP_SCREEN_ON = 0x04000000; 1048 1049 /** 1050 * View flag indicating whether this view should have sound effects enabled 1051 * for events such as clicking and touching. 1052 */ 1053 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1054 1055 /** 1056 * View flag indicating whether this view should have haptic feedback 1057 * enabled for events such as long presses. 1058 */ 1059 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1060 1061 /** 1062 * <p>Indicates that the view hierarchy should stop saving state when 1063 * it reaches this view. If state saving is initiated immediately at 1064 * the view, it will be allowed. 1065 * {@hide} 1066 */ 1067 static final int PARENT_SAVE_DISABLED = 0x20000000; 1068 1069 /** 1070 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1071 * {@hide} 1072 */ 1073 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1074 1075 /** @hide */ 1076 @IntDef(flag = true, 1077 value = { 1078 FOCUSABLES_ALL, 1079 FOCUSABLES_TOUCH_MODE 1080 }) 1081 @Retention(RetentionPolicy.SOURCE) 1082 public @interface FocusableMode {} 1083 1084 /** 1085 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1086 * should add all focusable Views regardless if they are focusable in touch mode. 1087 */ 1088 public static final int FOCUSABLES_ALL = 0x00000000; 1089 1090 /** 1091 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1092 * should add only Views focusable in touch mode. 1093 */ 1094 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1095 1096 /** @hide */ 1097 @IntDef({ 1098 FOCUS_BACKWARD, 1099 FOCUS_FORWARD, 1100 FOCUS_LEFT, 1101 FOCUS_UP, 1102 FOCUS_RIGHT, 1103 FOCUS_DOWN 1104 }) 1105 @Retention(RetentionPolicy.SOURCE) 1106 public @interface FocusDirection {} 1107 1108 /** @hide */ 1109 @IntDef({ 1110 FOCUS_LEFT, 1111 FOCUS_UP, 1112 FOCUS_RIGHT, 1113 FOCUS_DOWN 1114 }) 1115 @Retention(RetentionPolicy.SOURCE) 1116 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1117 1118 /** 1119 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1120 * item. 1121 */ 1122 public static final int FOCUS_BACKWARD = 0x00000001; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1126 * item. 1127 */ 1128 public static final int FOCUS_FORWARD = 0x00000002; 1129 1130 /** 1131 * Use with {@link #focusSearch(int)}. Move focus to the left. 1132 */ 1133 public static final int FOCUS_LEFT = 0x00000011; 1134 1135 /** 1136 * Use with {@link #focusSearch(int)}. Move focus up. 1137 */ 1138 public static final int FOCUS_UP = 0x00000021; 1139 1140 /** 1141 * Use with {@link #focusSearch(int)}. Move focus to the right. 1142 */ 1143 public static final int FOCUS_RIGHT = 0x00000042; 1144 1145 /** 1146 * Use with {@link #focusSearch(int)}. Move focus down. 1147 */ 1148 public static final int FOCUS_DOWN = 0x00000082; 1149 1150 /** 1151 * Bits of {@link #getMeasuredWidthAndState()} and 1152 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1153 */ 1154 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1155 1156 /** 1157 * Bits of {@link #getMeasuredWidthAndState()} and 1158 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1159 */ 1160 public static final int MEASURED_STATE_MASK = 0xff000000; 1161 1162 /** 1163 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1164 * for functions that combine both width and height into a single int, 1165 * such as {@link #getMeasuredState()} and the childState argument of 1166 * {@link #resolveSizeAndState(int, int, int)}. 1167 */ 1168 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1169 1170 /** 1171 * Bit of {@link #getMeasuredWidthAndState()} and 1172 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1173 * is smaller that the space the view would like to have. 1174 */ 1175 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1176 1177 /** 1178 * Base View state sets 1179 */ 1180 // Singles 1181 /** 1182 * Indicates the view has no states set. States are used with 1183 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1184 * view depending on its state. 1185 * 1186 * @see android.graphics.drawable.Drawable 1187 * @see #getDrawableState() 1188 */ 1189 protected static final int[] EMPTY_STATE_SET; 1190 /** 1191 * Indicates the view is enabled. States are used with 1192 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1193 * view depending on its state. 1194 * 1195 * @see android.graphics.drawable.Drawable 1196 * @see #getDrawableState() 1197 */ 1198 protected static final int[] ENABLED_STATE_SET; 1199 /** 1200 * Indicates the view is focused. States are used with 1201 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1202 * view depending on its state. 1203 * 1204 * @see android.graphics.drawable.Drawable 1205 * @see #getDrawableState() 1206 */ 1207 protected static final int[] FOCUSED_STATE_SET; 1208 /** 1209 * Indicates the view is selected. States are used with 1210 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1211 * view depending on its state. 1212 * 1213 * @see android.graphics.drawable.Drawable 1214 * @see #getDrawableState() 1215 */ 1216 protected static final int[] SELECTED_STATE_SET; 1217 /** 1218 * Indicates the view is pressed. States are used with 1219 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1220 * view depending on its state. 1221 * 1222 * @see android.graphics.drawable.Drawable 1223 * @see #getDrawableState() 1224 */ 1225 protected static final int[] PRESSED_STATE_SET; 1226 /** 1227 * Indicates the view's window has focus. States are used with 1228 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1229 * view depending on its state. 1230 * 1231 * @see android.graphics.drawable.Drawable 1232 * @see #getDrawableState() 1233 */ 1234 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1235 // Doubles 1236 /** 1237 * Indicates the view is enabled and has the focus. 1238 * 1239 * @see #ENABLED_STATE_SET 1240 * @see #FOCUSED_STATE_SET 1241 */ 1242 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1243 /** 1244 * Indicates the view is enabled and selected. 1245 * 1246 * @see #ENABLED_STATE_SET 1247 * @see #SELECTED_STATE_SET 1248 */ 1249 protected static final int[] ENABLED_SELECTED_STATE_SET; 1250 /** 1251 * Indicates the view is enabled and that its window has focus. 1252 * 1253 * @see #ENABLED_STATE_SET 1254 * @see #WINDOW_FOCUSED_STATE_SET 1255 */ 1256 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1257 /** 1258 * Indicates the view is focused and selected. 1259 * 1260 * @see #FOCUSED_STATE_SET 1261 * @see #SELECTED_STATE_SET 1262 */ 1263 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1264 /** 1265 * Indicates the view has the focus and that its window has the focus. 1266 * 1267 * @see #FOCUSED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1271 /** 1272 * Indicates the view is selected and that its window has the focus. 1273 * 1274 * @see #SELECTED_STATE_SET 1275 * @see #WINDOW_FOCUSED_STATE_SET 1276 */ 1277 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1278 // Triples 1279 /** 1280 * Indicates the view is enabled, focused and selected. 1281 * 1282 * @see #ENABLED_STATE_SET 1283 * @see #FOCUSED_STATE_SET 1284 * @see #SELECTED_STATE_SET 1285 */ 1286 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1287 /** 1288 * Indicates the view is enabled, focused and its window has the focus. 1289 * 1290 * @see #ENABLED_STATE_SET 1291 * @see #FOCUSED_STATE_SET 1292 * @see #WINDOW_FOCUSED_STATE_SET 1293 */ 1294 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1295 /** 1296 * Indicates the view is enabled, selected and its window has the focus. 1297 * 1298 * @see #ENABLED_STATE_SET 1299 * @see #SELECTED_STATE_SET 1300 * @see #WINDOW_FOCUSED_STATE_SET 1301 */ 1302 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1303 /** 1304 * Indicates the view is focused, selected and its window has the focus. 1305 * 1306 * @see #FOCUSED_STATE_SET 1307 * @see #SELECTED_STATE_SET 1308 * @see #WINDOW_FOCUSED_STATE_SET 1309 */ 1310 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1311 /** 1312 * Indicates the view is enabled, focused, selected and its window 1313 * has the focus. 1314 * 1315 * @see #ENABLED_STATE_SET 1316 * @see #FOCUSED_STATE_SET 1317 * @see #SELECTED_STATE_SET 1318 * @see #WINDOW_FOCUSED_STATE_SET 1319 */ 1320 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1321 /** 1322 * Indicates the view is pressed and its window has the focus. 1323 * 1324 * @see #PRESSED_STATE_SET 1325 * @see #WINDOW_FOCUSED_STATE_SET 1326 */ 1327 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1328 /** 1329 * Indicates the view is pressed and selected. 1330 * 1331 * @see #PRESSED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 */ 1334 protected static final int[] PRESSED_SELECTED_STATE_SET; 1335 /** 1336 * Indicates the view is pressed, selected and its window has the focus. 1337 * 1338 * @see #PRESSED_STATE_SET 1339 * @see #SELECTED_STATE_SET 1340 * @see #WINDOW_FOCUSED_STATE_SET 1341 */ 1342 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1343 /** 1344 * Indicates the view is pressed and focused. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 */ 1349 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1350 /** 1351 * Indicates the view is pressed, focused and its window has the focus. 1352 * 1353 * @see #PRESSED_STATE_SET 1354 * @see #FOCUSED_STATE_SET 1355 * @see #WINDOW_FOCUSED_STATE_SET 1356 */ 1357 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1358 /** 1359 * Indicates the view is pressed, focused and selected. 1360 * 1361 * @see #PRESSED_STATE_SET 1362 * @see #SELECTED_STATE_SET 1363 * @see #FOCUSED_STATE_SET 1364 */ 1365 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1366 /** 1367 * Indicates the view is pressed, focused, selected and its window has the focus. 1368 * 1369 * @see #PRESSED_STATE_SET 1370 * @see #FOCUSED_STATE_SET 1371 * @see #SELECTED_STATE_SET 1372 * @see #WINDOW_FOCUSED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed and enabled. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #ENABLED_STATE_SET 1380 */ 1381 protected static final int[] PRESSED_ENABLED_STATE_SET; 1382 /** 1383 * Indicates the view is pressed, enabled and its window has the focus. 1384 * 1385 * @see #PRESSED_STATE_SET 1386 * @see #ENABLED_STATE_SET 1387 * @see #WINDOW_FOCUSED_STATE_SET 1388 */ 1389 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1390 /** 1391 * Indicates the view is pressed, enabled and selected. 1392 * 1393 * @see #PRESSED_STATE_SET 1394 * @see #ENABLED_STATE_SET 1395 * @see #SELECTED_STATE_SET 1396 */ 1397 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1398 /** 1399 * Indicates the view is pressed, enabled, selected and its window has the 1400 * focus. 1401 * 1402 * @see #PRESSED_STATE_SET 1403 * @see #ENABLED_STATE_SET 1404 * @see #SELECTED_STATE_SET 1405 * @see #WINDOW_FOCUSED_STATE_SET 1406 */ 1407 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1408 /** 1409 * Indicates the view is pressed, enabled and focused. 1410 * 1411 * @see #PRESSED_STATE_SET 1412 * @see #ENABLED_STATE_SET 1413 * @see #FOCUSED_STATE_SET 1414 */ 1415 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1416 /** 1417 * Indicates the view is pressed, enabled, focused and its window has the 1418 * focus. 1419 * 1420 * @see #PRESSED_STATE_SET 1421 * @see #ENABLED_STATE_SET 1422 * @see #FOCUSED_STATE_SET 1423 * @see #WINDOW_FOCUSED_STATE_SET 1424 */ 1425 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1426 /** 1427 * Indicates the view is pressed, enabled, focused and selected. 1428 * 1429 * @see #PRESSED_STATE_SET 1430 * @see #ENABLED_STATE_SET 1431 * @see #SELECTED_STATE_SET 1432 * @see #FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1435 /** 1436 * Indicates the view is pressed, enabled, focused, selected and its window 1437 * has the focus. 1438 * 1439 * @see #PRESSED_STATE_SET 1440 * @see #ENABLED_STATE_SET 1441 * @see #SELECTED_STATE_SET 1442 * @see #FOCUSED_STATE_SET 1443 * @see #WINDOW_FOCUSED_STATE_SET 1444 */ 1445 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1446 1447 static { 1448 EMPTY_STATE_SET = StateSet.get(0); 1449 1450 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1451 1452 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1453 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1454 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1455 1456 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1457 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1458 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1459 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1460 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1461 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1462 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1463 | StateSet.VIEW_STATE_FOCUSED); 1464 1465 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1466 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1467 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1468 ENABLED_SELECTED_STATE_SET = StateSet.get( 1469 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1470 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1471 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1472 | StateSet.VIEW_STATE_ENABLED); 1473 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1474 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1475 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1476 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1477 | StateSet.VIEW_STATE_ENABLED); 1478 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1479 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1480 | StateSet.VIEW_STATE_ENABLED); 1481 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1482 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1483 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1484 1485 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1486 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1487 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1488 PRESSED_SELECTED_STATE_SET = StateSet.get( 1489 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1490 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1491 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1492 | StateSet.VIEW_STATE_PRESSED); 1493 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1494 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1495 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1496 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1497 | StateSet.VIEW_STATE_PRESSED); 1498 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1499 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1500 | StateSet.VIEW_STATE_PRESSED); 1501 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1502 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1503 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1504 PRESSED_ENABLED_STATE_SET = StateSet.get( 1505 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1506 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1507 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1508 | StateSet.VIEW_STATE_PRESSED); 1509 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1510 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1511 | StateSet.VIEW_STATE_PRESSED); 1512 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1513 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1514 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1515 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1516 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1517 | StateSet.VIEW_STATE_PRESSED); 1518 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1519 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1520 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1521 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1522 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1523 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1524 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1525 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1526 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1527 | StateSet.VIEW_STATE_PRESSED); 1528 } 1529 1530 /** 1531 * Accessibility event types that are dispatched for text population. 1532 */ 1533 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1534 AccessibilityEvent.TYPE_VIEW_CLICKED 1535 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1536 | AccessibilityEvent.TYPE_VIEW_SELECTED 1537 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1538 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1539 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1540 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1541 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1542 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1543 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1544 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1545 1546 /** 1547 * Temporary Rect currently for use in setBackground(). This will probably 1548 * be extended in the future to hold our own class with more than just 1549 * a Rect. :) 1550 */ 1551 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1552 1553 /** 1554 * Map used to store views' tags. 1555 */ 1556 private SparseArray<Object> mKeyedTags; 1557 1558 /** 1559 * The next available accessibility id. 1560 */ 1561 private static int sNextAccessibilityViewId; 1562 1563 /** 1564 * The animation currently associated with this view. 1565 * @hide 1566 */ 1567 protected Animation mCurrentAnimation = null; 1568 1569 /** 1570 * Width as measured during measure pass. 1571 * {@hide} 1572 */ 1573 @ViewDebug.ExportedProperty(category = "measurement") 1574 int mMeasuredWidth; 1575 1576 /** 1577 * Height as measured during measure pass. 1578 * {@hide} 1579 */ 1580 @ViewDebug.ExportedProperty(category = "measurement") 1581 int mMeasuredHeight; 1582 1583 /** 1584 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1585 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1586 * its display list. This flag, used only when hw accelerated, allows us to clear the 1587 * flag while retaining this information until it's needed (at getDisplayList() time and 1588 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1589 * 1590 * {@hide} 1591 */ 1592 boolean mRecreateDisplayList = false; 1593 1594 /** 1595 * The view's identifier. 1596 * {@hide} 1597 * 1598 * @see #setId(int) 1599 * @see #getId() 1600 */ 1601 @IdRes 1602 @ViewDebug.ExportedProperty(resolveId = true) 1603 int mID = NO_ID; 1604 1605 /** 1606 * The stable ID of this view for accessibility purposes. 1607 */ 1608 int mAccessibilityViewId = NO_ID; 1609 1610 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1611 1612 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1613 1614 /** 1615 * The view's tag. 1616 * {@hide} 1617 * 1618 * @see #setTag(Object) 1619 * @see #getTag() 1620 */ 1621 protected Object mTag = null; 1622 1623 // for mPrivateFlags: 1624 /** {@hide} */ 1625 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1626 /** {@hide} */ 1627 static final int PFLAG_FOCUSED = 0x00000002; 1628 /** {@hide} */ 1629 static final int PFLAG_SELECTED = 0x00000004; 1630 /** {@hide} */ 1631 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1632 /** {@hide} */ 1633 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1634 /** {@hide} */ 1635 static final int PFLAG_DRAWN = 0x00000020; 1636 /** 1637 * When this flag is set, this view is running an animation on behalf of its 1638 * children and should therefore not cancel invalidate requests, even if they 1639 * lie outside of this view's bounds. 1640 * 1641 * {@hide} 1642 */ 1643 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1644 /** {@hide} */ 1645 static final int PFLAG_SKIP_DRAW = 0x00000080; 1646 /** {@hide} */ 1647 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1648 /** {@hide} */ 1649 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1650 /** {@hide} */ 1651 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1652 /** {@hide} */ 1653 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1654 /** {@hide} */ 1655 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1656 /** {@hide} */ 1657 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1658 1659 private static final int PFLAG_PRESSED = 0x00004000; 1660 1661 /** {@hide} */ 1662 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1663 /** 1664 * Flag used to indicate that this view should be drawn once more (and only once 1665 * more) after its animation has completed. 1666 * {@hide} 1667 */ 1668 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1669 1670 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1671 1672 /** 1673 * Indicates that the View returned true when onSetAlpha() was called and that 1674 * the alpha must be restored. 1675 * {@hide} 1676 */ 1677 static final int PFLAG_ALPHA_SET = 0x00040000; 1678 1679 /** 1680 * Set by {@link #setScrollContainer(boolean)}. 1681 */ 1682 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1683 1684 /** 1685 * Set by {@link #setScrollContainer(boolean)}. 1686 */ 1687 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1688 1689 /** 1690 * View flag indicating whether this view was invalidated (fully or partially.) 1691 * 1692 * @hide 1693 */ 1694 static final int PFLAG_DIRTY = 0x00200000; 1695 1696 /** 1697 * View flag indicating whether this view was invalidated by an opaque 1698 * invalidate request. 1699 * 1700 * @hide 1701 */ 1702 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1703 1704 /** 1705 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1706 * 1707 * @hide 1708 */ 1709 static final int PFLAG_DIRTY_MASK = 0x00600000; 1710 1711 /** 1712 * Indicates whether the background is opaque. 1713 * 1714 * @hide 1715 */ 1716 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1717 1718 /** 1719 * Indicates whether the scrollbars are opaque. 1720 * 1721 * @hide 1722 */ 1723 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1724 1725 /** 1726 * Indicates whether the view is opaque. 1727 * 1728 * @hide 1729 */ 1730 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1731 1732 /** 1733 * Indicates a prepressed state; 1734 * the short time between ACTION_DOWN and recognizing 1735 * a 'real' press. Prepressed is used to recognize quick taps 1736 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1737 * 1738 * @hide 1739 */ 1740 private static final int PFLAG_PREPRESSED = 0x02000000; 1741 1742 /** 1743 * Indicates whether the view is temporarily detached. 1744 * 1745 * @hide 1746 */ 1747 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1748 1749 /** 1750 * Indicates that we should awaken scroll bars once attached 1751 * 1752 * @hide 1753 */ 1754 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1755 1756 /** 1757 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1758 * @hide 1759 */ 1760 private static final int PFLAG_HOVERED = 0x10000000; 1761 1762 /** 1763 * no longer needed, should be reused 1764 */ 1765 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1766 1767 /** {@hide} */ 1768 static final int PFLAG_ACTIVATED = 0x40000000; 1769 1770 /** 1771 * Indicates that this view was specifically invalidated, not just dirtied because some 1772 * child view was invalidated. The flag is used to determine when we need to recreate 1773 * a view's display list (as opposed to just returning a reference to its existing 1774 * display list). 1775 * 1776 * @hide 1777 */ 1778 static final int PFLAG_INVALIDATED = 0x80000000; 1779 1780 /** 1781 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1782 * 1783 * |-------|-------|-------|-------| 1784 * 1 PFLAG2_DRAG_CAN_ACCEPT 1785 * 1 PFLAG2_DRAG_HOVERED 1786 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1787 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1788 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1789 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1790 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1791 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1792 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1793 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1794 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1795 * 111 PFLAG2_TEXT_DIRECTION_MASK 1796 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1797 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1798 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1799 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1800 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1801 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1802 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1803 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1804 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1805 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1806 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1807 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1808 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1809 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1810 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1811 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1812 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1813 * 1 PFLAG2_VIEW_QUICK_REJECTED 1814 * 1 PFLAG2_PADDING_RESOLVED 1815 * 1 PFLAG2_DRAWABLE_RESOLVED 1816 * 1 PFLAG2_HAS_TRANSIENT_STATE 1817 * |-------|-------|-------|-------| 1818 */ 1819 1820 /** 1821 * Indicates that this view has reported that it can accept the current drag's content. 1822 * Cleared when the drag operation concludes. 1823 * @hide 1824 */ 1825 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1826 1827 /** 1828 * Indicates that this view is currently directly under the drag location in a 1829 * drag-and-drop operation involving content that it can accept. Cleared when 1830 * the drag exits the view, or when the drag operation concludes. 1831 * @hide 1832 */ 1833 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1834 1835 /** @hide */ 1836 @IntDef({ 1837 LAYOUT_DIRECTION_LTR, 1838 LAYOUT_DIRECTION_RTL, 1839 LAYOUT_DIRECTION_INHERIT, 1840 LAYOUT_DIRECTION_LOCALE 1841 }) 1842 @Retention(RetentionPolicy.SOURCE) 1843 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1844 public @interface LayoutDir {} 1845 1846 /** @hide */ 1847 @IntDef({ 1848 LAYOUT_DIRECTION_LTR, 1849 LAYOUT_DIRECTION_RTL 1850 }) 1851 @Retention(RetentionPolicy.SOURCE) 1852 public @interface ResolvedLayoutDir {} 1853 1854 /** 1855 * Horizontal layout direction of this view is from Left to Right. 1856 * Use with {@link #setLayoutDirection}. 1857 */ 1858 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1859 1860 /** 1861 * Horizontal layout direction of this view is from Right to Left. 1862 * Use with {@link #setLayoutDirection}. 1863 */ 1864 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1865 1866 /** 1867 * Horizontal layout direction of this view is inherited from its parent. 1868 * Use with {@link #setLayoutDirection}. 1869 */ 1870 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1871 1872 /** 1873 * Horizontal layout direction of this view is from deduced from the default language 1874 * script for the locale. Use with {@link #setLayoutDirection}. 1875 */ 1876 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1877 1878 /** 1879 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1880 * @hide 1881 */ 1882 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1883 1884 /** 1885 * Mask for use with private flags indicating bits used for horizontal layout direction. 1886 * @hide 1887 */ 1888 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1889 1890 /** 1891 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1892 * right-to-left direction. 1893 * @hide 1894 */ 1895 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1896 1897 /** 1898 * Indicates whether the view horizontal layout direction has been resolved. 1899 * @hide 1900 */ 1901 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1902 1903 /** 1904 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1905 * @hide 1906 */ 1907 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1908 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1909 1910 /* 1911 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1912 * flag value. 1913 * @hide 1914 */ 1915 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1916 LAYOUT_DIRECTION_LTR, 1917 LAYOUT_DIRECTION_RTL, 1918 LAYOUT_DIRECTION_INHERIT, 1919 LAYOUT_DIRECTION_LOCALE 1920 }; 1921 1922 /** 1923 * Default horizontal layout direction. 1924 */ 1925 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1926 1927 /** 1928 * Default horizontal layout direction. 1929 * @hide 1930 */ 1931 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1932 1933 /** 1934 * Text direction is inherited through {@link ViewGroup} 1935 */ 1936 public static final int TEXT_DIRECTION_INHERIT = 0; 1937 1938 /** 1939 * Text direction is using "first strong algorithm". The first strong directional character 1940 * determines the paragraph direction. If there is no strong directional character, the 1941 * paragraph direction is the view's resolved layout direction. 1942 */ 1943 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1944 1945 /** 1946 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1947 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1948 * If there are neither, the paragraph direction is the view's resolved layout direction. 1949 */ 1950 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1951 1952 /** 1953 * Text direction is forced to LTR. 1954 */ 1955 public static final int TEXT_DIRECTION_LTR = 3; 1956 1957 /** 1958 * Text direction is forced to RTL. 1959 */ 1960 public static final int TEXT_DIRECTION_RTL = 4; 1961 1962 /** 1963 * Text direction is coming from the system Locale. 1964 */ 1965 public static final int TEXT_DIRECTION_LOCALE = 5; 1966 1967 /** 1968 * Default text direction is inherited 1969 */ 1970 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1971 1972 /** 1973 * Default resolved text direction 1974 * @hide 1975 */ 1976 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1977 1978 /** 1979 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1980 * @hide 1981 */ 1982 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1983 1984 /** 1985 * Mask for use with private flags indicating bits used for text direction. 1986 * @hide 1987 */ 1988 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1989 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1990 1991 /** 1992 * Array of text direction flags for mapping attribute "textDirection" to correct 1993 * flag value. 1994 * @hide 1995 */ 1996 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1997 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1998 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1999 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2000 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2001 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2002 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2003 }; 2004 2005 /** 2006 * Indicates whether the view text direction has been resolved. 2007 * @hide 2008 */ 2009 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2010 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2011 2012 /** 2013 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2014 * @hide 2015 */ 2016 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2017 2018 /** 2019 * Mask for use with private flags indicating bits used for resolved text direction. 2020 * @hide 2021 */ 2022 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2023 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2024 2025 /** 2026 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2027 * @hide 2028 */ 2029 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2030 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2031 2032 /** @hide */ 2033 @IntDef({ 2034 TEXT_ALIGNMENT_INHERIT, 2035 TEXT_ALIGNMENT_GRAVITY, 2036 TEXT_ALIGNMENT_CENTER, 2037 TEXT_ALIGNMENT_TEXT_START, 2038 TEXT_ALIGNMENT_TEXT_END, 2039 TEXT_ALIGNMENT_VIEW_START, 2040 TEXT_ALIGNMENT_VIEW_END 2041 }) 2042 @Retention(RetentionPolicy.SOURCE) 2043 public @interface TextAlignment {} 2044 2045 /** 2046 * Default text alignment. The text alignment of this View is inherited from its parent. 2047 * Use with {@link #setTextAlignment(int)} 2048 */ 2049 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2050 2051 /** 2052 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2053 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2054 * 2055 * Use with {@link #setTextAlignment(int)} 2056 */ 2057 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2058 2059 /** 2060 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2061 * 2062 * Use with {@link #setTextAlignment(int)} 2063 */ 2064 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2065 2066 /** 2067 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2068 * 2069 * Use with {@link #setTextAlignment(int)} 2070 */ 2071 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2072 2073 /** 2074 * Center the paragraph, e.g. ALIGN_CENTER. 2075 * 2076 * Use with {@link #setTextAlignment(int)} 2077 */ 2078 public static final int TEXT_ALIGNMENT_CENTER = 4; 2079 2080 /** 2081 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2082 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2083 * 2084 * Use with {@link #setTextAlignment(int)} 2085 */ 2086 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2087 2088 /** 2089 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2090 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2091 * 2092 * Use with {@link #setTextAlignment(int)} 2093 */ 2094 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2095 2096 /** 2097 * Default text alignment is inherited 2098 */ 2099 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2100 2101 /** 2102 * Default resolved text alignment 2103 * @hide 2104 */ 2105 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2106 2107 /** 2108 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2109 * @hide 2110 */ 2111 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2112 2113 /** 2114 * Mask for use with private flags indicating bits used for text alignment. 2115 * @hide 2116 */ 2117 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2118 2119 /** 2120 * Array of text direction flags for mapping attribute "textAlignment" to correct 2121 * flag value. 2122 * @hide 2123 */ 2124 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2125 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2126 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2127 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2128 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2129 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2130 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2131 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2132 }; 2133 2134 /** 2135 * Indicates whether the view text alignment has been resolved. 2136 * @hide 2137 */ 2138 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2139 2140 /** 2141 * Bit shift to get the resolved text alignment. 2142 * @hide 2143 */ 2144 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2145 2146 /** 2147 * Mask for use with private flags indicating bits used for text alignment. 2148 * @hide 2149 */ 2150 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2151 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2152 2153 /** 2154 * Indicates whether if the view text alignment has been resolved to gravity 2155 */ 2156 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2157 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2158 2159 // Accessiblity constants for mPrivateFlags2 2160 2161 /** 2162 * Shift for the bits in {@link #mPrivateFlags2} related to the 2163 * "importantForAccessibility" attribute. 2164 */ 2165 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2166 2167 /** 2168 * Automatically determine whether a view is important for accessibility. 2169 */ 2170 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2171 2172 /** 2173 * The view is important for accessibility. 2174 */ 2175 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2176 2177 /** 2178 * The view is not important for accessibility. 2179 */ 2180 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2181 2182 /** 2183 * The view is not important for accessibility, nor are any of its 2184 * descendant views. 2185 */ 2186 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2187 2188 /** 2189 * The default whether the view is important for accessibility. 2190 */ 2191 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2192 2193 /** 2194 * Mask for obtainig the bits which specify how to determine 2195 * whether a view is important for accessibility. 2196 */ 2197 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2198 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2199 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2200 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2201 2202 /** 2203 * Shift for the bits in {@link #mPrivateFlags2} related to the 2204 * "accessibilityLiveRegion" attribute. 2205 */ 2206 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2207 2208 /** 2209 * Live region mode specifying that accessibility services should not 2210 * automatically announce changes to this view. This is the default live 2211 * region mode for most views. 2212 * <p> 2213 * Use with {@link #setAccessibilityLiveRegion(int)}. 2214 */ 2215 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2216 2217 /** 2218 * Live region mode specifying that accessibility services should announce 2219 * changes to this view. 2220 * <p> 2221 * Use with {@link #setAccessibilityLiveRegion(int)}. 2222 */ 2223 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2224 2225 /** 2226 * Live region mode specifying that accessibility services should interrupt 2227 * ongoing speech to immediately announce changes to this view. 2228 * <p> 2229 * Use with {@link #setAccessibilityLiveRegion(int)}. 2230 */ 2231 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2232 2233 /** 2234 * The default whether the view is important for accessibility. 2235 */ 2236 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2237 2238 /** 2239 * Mask for obtaining the bits which specify a view's accessibility live 2240 * region mode. 2241 */ 2242 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2243 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2244 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2245 2246 /** 2247 * Flag indicating whether a view has accessibility focus. 2248 */ 2249 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2250 2251 /** 2252 * Flag whether the accessibility state of the subtree rooted at this view changed. 2253 */ 2254 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2255 2256 /** 2257 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2258 * is used to check whether later changes to the view's transform should invalidate the 2259 * view to force the quickReject test to run again. 2260 */ 2261 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2262 2263 /** 2264 * Flag indicating that start/end padding has been resolved into left/right padding 2265 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2266 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2267 * during measurement. In some special cases this is required such as when an adapter-based 2268 * view measures prospective children without attaching them to a window. 2269 */ 2270 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2271 2272 /** 2273 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2274 */ 2275 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2276 2277 /** 2278 * Indicates that the view is tracking some sort of transient state 2279 * that the app should not need to be aware of, but that the framework 2280 * should take special care to preserve. 2281 */ 2282 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2283 2284 /** 2285 * Group of bits indicating that RTL properties resolution is done. 2286 */ 2287 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2288 PFLAG2_TEXT_DIRECTION_RESOLVED | 2289 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2290 PFLAG2_PADDING_RESOLVED | 2291 PFLAG2_DRAWABLE_RESOLVED; 2292 2293 // There are a couple of flags left in mPrivateFlags2 2294 2295 /* End of masks for mPrivateFlags2 */ 2296 2297 /** 2298 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2299 * 2300 * |-------|-------|-------|-------| 2301 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2302 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2303 * 1 PFLAG3_IS_LAID_OUT 2304 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2305 * 1 PFLAG3_CALLED_SUPER 2306 * |-------|-------|-------|-------| 2307 */ 2308 2309 /** 2310 * Flag indicating that view has a transform animation set on it. This is used to track whether 2311 * an animation is cleared between successive frames, in order to tell the associated 2312 * DisplayList to clear its animation matrix. 2313 */ 2314 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2315 2316 /** 2317 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2318 * animation is cleared between successive frames, in order to tell the associated 2319 * DisplayList to restore its alpha value. 2320 */ 2321 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2322 2323 /** 2324 * Flag indicating that the view has been through at least one layout since it 2325 * was last attached to a window. 2326 */ 2327 static final int PFLAG3_IS_LAID_OUT = 0x4; 2328 2329 /** 2330 * Flag indicating that a call to measure() was skipped and should be done 2331 * instead when layout() is invoked. 2332 */ 2333 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2334 2335 /** 2336 * Flag indicating that an overridden method correctly called down to 2337 * the superclass implementation as required by the API spec. 2338 */ 2339 static final int PFLAG3_CALLED_SUPER = 0x10; 2340 2341 /** 2342 * Flag indicating that we're in the process of applying window insets. 2343 */ 2344 static final int PFLAG3_APPLYING_INSETS = 0x20; 2345 2346 /** 2347 * Flag indicating that we're in the process of fitting system windows using the old method. 2348 */ 2349 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2350 2351 /** 2352 * Flag indicating that nested scrolling is enabled for this view. 2353 * The view will optionally cooperate with views up its parent chain to allow for 2354 * integrated nested scrolling along the same axis. 2355 */ 2356 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2357 2358 /* End of masks for mPrivateFlags3 */ 2359 2360 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2361 2362 /** 2363 * Always allow a user to over-scroll this view, provided it is a 2364 * view that can scroll. 2365 * 2366 * @see #getOverScrollMode() 2367 * @see #setOverScrollMode(int) 2368 */ 2369 public static final int OVER_SCROLL_ALWAYS = 0; 2370 2371 /** 2372 * Allow a user to over-scroll this view only if the content is large 2373 * enough to meaningfully scroll, provided it is a view that can scroll. 2374 * 2375 * @see #getOverScrollMode() 2376 * @see #setOverScrollMode(int) 2377 */ 2378 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2379 2380 /** 2381 * Never allow a user to over-scroll this view. 2382 * 2383 * @see #getOverScrollMode() 2384 * @see #setOverScrollMode(int) 2385 */ 2386 public static final int OVER_SCROLL_NEVER = 2; 2387 2388 /** 2389 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2390 * requested the system UI (status bar) to be visible (the default). 2391 * 2392 * @see #setSystemUiVisibility(int) 2393 */ 2394 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2395 2396 /** 2397 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2398 * system UI to enter an unobtrusive "low profile" mode. 2399 * 2400 * <p>This is for use in games, book readers, video players, or any other 2401 * "immersive" application where the usual system chrome is deemed too distracting. 2402 * 2403 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2404 * 2405 * @see #setSystemUiVisibility(int) 2406 */ 2407 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2408 2409 /** 2410 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2411 * system navigation be temporarily hidden. 2412 * 2413 * <p>This is an even less obtrusive state than that called for by 2414 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2415 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2416 * those to disappear. This is useful (in conjunction with the 2417 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2418 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2419 * window flags) for displaying content using every last pixel on the display. 2420 * 2421 * <p>There is a limitation: because navigation controls are so important, the least user 2422 * interaction will cause them to reappear immediately. When this happens, both 2423 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2424 * so that both elements reappear at the same time. 2425 * 2426 * @see #setSystemUiVisibility(int) 2427 */ 2428 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2429 2430 /** 2431 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2432 * into the normal fullscreen mode so that its content can take over the screen 2433 * while still allowing the user to interact with the application. 2434 * 2435 * <p>This has the same visual effect as 2436 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2437 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2438 * meaning that non-critical screen decorations (such as the status bar) will be 2439 * hidden while the user is in the View's window, focusing the experience on 2440 * that content. Unlike the window flag, if you are using ActionBar in 2441 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2442 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2443 * hide the action bar. 2444 * 2445 * <p>This approach to going fullscreen is best used over the window flag when 2446 * it is a transient state -- that is, the application does this at certain 2447 * points in its user interaction where it wants to allow the user to focus 2448 * on content, but not as a continuous state. For situations where the application 2449 * would like to simply stay full screen the entire time (such as a game that 2450 * wants to take over the screen), the 2451 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2452 * is usually a better approach. The state set here will be removed by the system 2453 * in various situations (such as the user moving to another application) like 2454 * the other system UI states. 2455 * 2456 * <p>When using this flag, the application should provide some easy facility 2457 * for the user to go out of it. A common example would be in an e-book 2458 * reader, where tapping on the screen brings back whatever screen and UI 2459 * decorations that had been hidden while the user was immersed in reading 2460 * the book. 2461 * 2462 * @see #setSystemUiVisibility(int) 2463 */ 2464 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2465 2466 /** 2467 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2468 * flags, we would like a stable view of the content insets given to 2469 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2470 * will always represent the worst case that the application can expect 2471 * as a continuous state. In the stock Android UI this is the space for 2472 * the system bar, nav bar, and status bar, but not more transient elements 2473 * such as an input method. 2474 * 2475 * The stable layout your UI sees is based on the system UI modes you can 2476 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2477 * then you will get a stable layout for changes of the 2478 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2479 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2480 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2481 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2482 * with a stable layout. (Note that you should avoid using 2483 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2484 * 2485 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2486 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2487 * then a hidden status bar will be considered a "stable" state for purposes 2488 * here. This allows your UI to continually hide the status bar, while still 2489 * using the system UI flags to hide the action bar while still retaining 2490 * a stable layout. Note that changing the window fullscreen flag will never 2491 * provide a stable layout for a clean transition. 2492 * 2493 * <p>If you are using ActionBar in 2494 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2495 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2496 * insets it adds to those given to the application. 2497 */ 2498 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2499 2500 /** 2501 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2502 * to be laid out as if it has requested 2503 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2504 * allows it to avoid artifacts when switching in and out of that mode, at 2505 * the expense that some of its user interface may be covered by screen 2506 * decorations when they are shown. You can perform layout of your inner 2507 * UI elements to account for the navigation system UI through the 2508 * {@link #fitSystemWindows(Rect)} method. 2509 */ 2510 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2511 2512 /** 2513 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2514 * to be laid out as if it has requested 2515 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2516 * allows it to avoid artifacts when switching in and out of that mode, at 2517 * the expense that some of its user interface may be covered by screen 2518 * decorations when they are shown. You can perform layout of your inner 2519 * UI elements to account for non-fullscreen system UI through the 2520 * {@link #fitSystemWindows(Rect)} method. 2521 */ 2522 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2523 2524 /** 2525 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2526 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2527 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2528 * user interaction. 2529 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2530 * has an effect when used in combination with that flag.</p> 2531 */ 2532 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2533 2534 /** 2535 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2536 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2537 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2538 * experience while also hiding the system bars. If this flag is not set, 2539 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2540 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2541 * if the user swipes from the top of the screen. 2542 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2543 * system gestures, such as swiping from the top of the screen. These transient system bars 2544 * will overlay app’s content, may have some degree of transparency, and will automatically 2545 * hide after a short timeout. 2546 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2547 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2548 * with one or both of those flags.</p> 2549 */ 2550 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2551 2552 /** 2553 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2554 * is compatible with light status bar backgrounds. 2555 * 2556 * <p>For this to take effect, the window must request 2557 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2558 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2559 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2560 * FLAG_TRANSLUCENT_STATUS}. 2561 * 2562 * @see android.R.attr#windowHasLightStatusBar 2563 */ 2564 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2565 2566 /** 2567 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2568 */ 2569 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2570 2571 /** 2572 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2573 */ 2574 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2575 2576 /** 2577 * @hide 2578 * 2579 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2580 * out of the public fields to keep the undefined bits out of the developer's way. 2581 * 2582 * Flag to make the status bar not expandable. Unless you also 2583 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2584 */ 2585 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2586 2587 /** 2588 * @hide 2589 * 2590 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2591 * out of the public fields to keep the undefined bits out of the developer's way. 2592 * 2593 * Flag to hide notification icons and scrolling ticker text. 2594 */ 2595 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2596 2597 /** 2598 * @hide 2599 * 2600 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2601 * out of the public fields to keep the undefined bits out of the developer's way. 2602 * 2603 * Flag to disable incoming notification alerts. This will not block 2604 * icons, but it will block sound, vibrating and other visual or aural notifications. 2605 */ 2606 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2607 2608 /** 2609 * @hide 2610 * 2611 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2612 * out of the public fields to keep the undefined bits out of the developer's way. 2613 * 2614 * Flag to hide only the scrolling ticker. Note that 2615 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2616 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2617 */ 2618 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2619 2620 /** 2621 * @hide 2622 * 2623 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2624 * out of the public fields to keep the undefined bits out of the developer's way. 2625 * 2626 * Flag to hide the center system info area. 2627 */ 2628 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2629 2630 /** 2631 * @hide 2632 * 2633 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2634 * out of the public fields to keep the undefined bits out of the developer's way. 2635 * 2636 * Flag to hide only the home button. Don't use this 2637 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2638 */ 2639 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2640 2641 /** 2642 * @hide 2643 * 2644 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2645 * out of the public fields to keep the undefined bits out of the developer's way. 2646 * 2647 * Flag to hide only the back button. Don't use this 2648 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2649 */ 2650 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2651 2652 /** 2653 * @hide 2654 * 2655 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2656 * out of the public fields to keep the undefined bits out of the developer's way. 2657 * 2658 * Flag to hide only the clock. You might use this if your activity has 2659 * its own clock making the status bar's clock redundant. 2660 */ 2661 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2662 2663 /** 2664 * @hide 2665 * 2666 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2667 * out of the public fields to keep the undefined bits out of the developer's way. 2668 * 2669 * Flag to hide only the recent apps button. Don't use this 2670 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2671 */ 2672 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2673 2674 /** 2675 * @hide 2676 * 2677 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2678 * out of the public fields to keep the undefined bits out of the developer's way. 2679 * 2680 * Flag to disable the global search gesture. Don't use this 2681 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2682 */ 2683 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2684 2685 /** 2686 * @hide 2687 * 2688 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2689 * out of the public fields to keep the undefined bits out of the developer's way. 2690 * 2691 * Flag to specify that the status bar is displayed in transient mode. 2692 */ 2693 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2694 2695 /** 2696 * @hide 2697 * 2698 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2699 * out of the public fields to keep the undefined bits out of the developer's way. 2700 * 2701 * Flag to specify that the navigation bar is displayed in transient mode. 2702 */ 2703 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2704 2705 /** 2706 * @hide 2707 * 2708 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2709 * out of the public fields to keep the undefined bits out of the developer's way. 2710 * 2711 * Flag to specify that the hidden status bar would like to be shown. 2712 */ 2713 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the hidden navigation bar would like to be shown. 2722 */ 2723 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the status bar is displayed in translucent mode. 2732 */ 2733 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the navigation bar is displayed in translucent mode. 2742 */ 2743 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * Whether Recents is visible or not. 2749 */ 2750 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2751 2752 /** 2753 * @hide 2754 * 2755 * Makes system ui transparent. 2756 */ 2757 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2758 2759 /** 2760 * @hide 2761 */ 2762 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2763 2764 /** 2765 * These are the system UI flags that can be cleared by events outside 2766 * of an application. Currently this is just the ability to tap on the 2767 * screen while hiding the navigation bar to have it return. 2768 * @hide 2769 */ 2770 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2771 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2772 | SYSTEM_UI_FLAG_FULLSCREEN; 2773 2774 /** 2775 * Flags that can impact the layout in relation to system UI. 2776 */ 2777 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2778 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2779 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2780 2781 /** @hide */ 2782 @IntDef(flag = true, 2783 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2784 @Retention(RetentionPolicy.SOURCE) 2785 public @interface FindViewFlags {} 2786 2787 /** 2788 * Find views that render the specified text. 2789 * 2790 * @see #findViewsWithText(ArrayList, CharSequence, int) 2791 */ 2792 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2793 2794 /** 2795 * Find find views that contain the specified content description. 2796 * 2797 * @see #findViewsWithText(ArrayList, CharSequence, int) 2798 */ 2799 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2800 2801 /** 2802 * Find views that contain {@link AccessibilityNodeProvider}. Such 2803 * a View is a root of virtual view hierarchy and may contain the searched 2804 * text. If this flag is set Views with providers are automatically 2805 * added and it is a responsibility of the client to call the APIs of 2806 * the provider to determine whether the virtual tree rooted at this View 2807 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2808 * representing the virtual views with this text. 2809 * 2810 * @see #findViewsWithText(ArrayList, CharSequence, int) 2811 * 2812 * @hide 2813 */ 2814 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2815 2816 /** 2817 * The undefined cursor position. 2818 * 2819 * @hide 2820 */ 2821 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2822 2823 /** 2824 * Indicates that the screen has changed state and is now off. 2825 * 2826 * @see #onScreenStateChanged(int) 2827 */ 2828 public static final int SCREEN_STATE_OFF = 0x0; 2829 2830 /** 2831 * Indicates that the screen has changed state and is now on. 2832 * 2833 * @see #onScreenStateChanged(int) 2834 */ 2835 public static final int SCREEN_STATE_ON = 0x1; 2836 2837 /** 2838 * Indicates no axis of view scrolling. 2839 */ 2840 public static final int SCROLL_AXIS_NONE = 0; 2841 2842 /** 2843 * Indicates scrolling along the horizontal axis. 2844 */ 2845 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2846 2847 /** 2848 * Indicates scrolling along the vertical axis. 2849 */ 2850 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2851 2852 /** 2853 * Controls the over-scroll mode for this view. 2854 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2855 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2856 * and {@link #OVER_SCROLL_NEVER}. 2857 */ 2858 private int mOverScrollMode; 2859 2860 /** 2861 * The parent this view is attached to. 2862 * {@hide} 2863 * 2864 * @see #getParent() 2865 */ 2866 protected ViewParent mParent; 2867 2868 /** 2869 * {@hide} 2870 */ 2871 AttachInfo mAttachInfo; 2872 2873 /** 2874 * {@hide} 2875 */ 2876 @ViewDebug.ExportedProperty(flagMapping = { 2877 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2878 name = "FORCE_LAYOUT"), 2879 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2880 name = "LAYOUT_REQUIRED"), 2881 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2882 name = "DRAWING_CACHE_INVALID", outputIf = false), 2883 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2884 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2885 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2886 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2887 }, formatToHexString = true) 2888 int mPrivateFlags; 2889 int mPrivateFlags2; 2890 int mPrivateFlags3; 2891 2892 /** 2893 * This view's request for the visibility of the status bar. 2894 * @hide 2895 */ 2896 @ViewDebug.ExportedProperty(flagMapping = { 2897 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2898 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2899 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2900 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2901 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2902 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2903 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2904 equals = SYSTEM_UI_FLAG_VISIBLE, 2905 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2906 }, formatToHexString = true) 2907 int mSystemUiVisibility; 2908 2909 /** 2910 * Reference count for transient state. 2911 * @see #setHasTransientState(boolean) 2912 */ 2913 int mTransientStateCount = 0; 2914 2915 /** 2916 * Count of how many windows this view has been attached to. 2917 */ 2918 int mWindowAttachCount; 2919 2920 /** 2921 * The layout parameters associated with this view and used by the parent 2922 * {@link android.view.ViewGroup} to determine how this view should be 2923 * laid out. 2924 * {@hide} 2925 */ 2926 protected ViewGroup.LayoutParams mLayoutParams; 2927 2928 /** 2929 * The view flags hold various views states. 2930 * {@hide} 2931 */ 2932 @ViewDebug.ExportedProperty(formatToHexString = true) 2933 int mViewFlags; 2934 2935 static class TransformationInfo { 2936 /** 2937 * The transform matrix for the View. This transform is calculated internally 2938 * based on the translation, rotation, and scale properties. 2939 * 2940 * Do *not* use this variable directly; instead call getMatrix(), which will 2941 * load the value from the View's RenderNode. 2942 */ 2943 private final Matrix mMatrix = new Matrix(); 2944 2945 /** 2946 * The inverse transform matrix for the View. This transform is calculated 2947 * internally based on the translation, rotation, and scale properties. 2948 * 2949 * Do *not* use this variable directly; instead call getInverseMatrix(), 2950 * which will load the value from the View's RenderNode. 2951 */ 2952 private Matrix mInverseMatrix; 2953 2954 /** 2955 * The opacity of the View. This is a value from 0 to 1, where 0 means 2956 * completely transparent and 1 means completely opaque. 2957 */ 2958 @ViewDebug.ExportedProperty 2959 float mAlpha = 1f; 2960 2961 /** 2962 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2963 * property only used by transitions, which is composited with the other alpha 2964 * values to calculate the final visual alpha value. 2965 */ 2966 float mTransitionAlpha = 1f; 2967 } 2968 2969 TransformationInfo mTransformationInfo; 2970 2971 /** 2972 * Current clip bounds. to which all drawing of this view are constrained. 2973 */ 2974 Rect mClipBounds = null; 2975 2976 private boolean mLastIsOpaque; 2977 2978 /** 2979 * The distance in pixels from the left edge of this view's parent 2980 * to the left edge of this view. 2981 * {@hide} 2982 */ 2983 @ViewDebug.ExportedProperty(category = "layout") 2984 protected int mLeft; 2985 /** 2986 * The distance in pixels from the left edge of this view's parent 2987 * to the right edge of this view. 2988 * {@hide} 2989 */ 2990 @ViewDebug.ExportedProperty(category = "layout") 2991 protected int mRight; 2992 /** 2993 * The distance in pixels from the top edge of this view's parent 2994 * to the top edge of this view. 2995 * {@hide} 2996 */ 2997 @ViewDebug.ExportedProperty(category = "layout") 2998 protected int mTop; 2999 /** 3000 * The distance in pixels from the top edge of this view's parent 3001 * to the bottom edge of this view. 3002 * {@hide} 3003 */ 3004 @ViewDebug.ExportedProperty(category = "layout") 3005 protected int mBottom; 3006 3007 /** 3008 * The offset, in pixels, by which the content of this view is scrolled 3009 * horizontally. 3010 * {@hide} 3011 */ 3012 @ViewDebug.ExportedProperty(category = "scrolling") 3013 protected int mScrollX; 3014 /** 3015 * The offset, in pixels, by which the content of this view is scrolled 3016 * vertically. 3017 * {@hide} 3018 */ 3019 @ViewDebug.ExportedProperty(category = "scrolling") 3020 protected int mScrollY; 3021 3022 /** 3023 * The left padding in pixels, that is the distance in pixels between the 3024 * left edge of this view and the left edge of its content. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "padding") 3028 protected int mPaddingLeft = 0; 3029 /** 3030 * The right padding in pixels, that is the distance in pixels between the 3031 * right edge of this view and the right edge of its content. 3032 * {@hide} 3033 */ 3034 @ViewDebug.ExportedProperty(category = "padding") 3035 protected int mPaddingRight = 0; 3036 /** 3037 * The top padding in pixels, that is the distance in pixels between the 3038 * top edge of this view and the top edge of its content. 3039 * {@hide} 3040 */ 3041 @ViewDebug.ExportedProperty(category = "padding") 3042 protected int mPaddingTop; 3043 /** 3044 * The bottom padding in pixels, that is the distance in pixels between the 3045 * bottom edge of this view and the bottom edge of its content. 3046 * {@hide} 3047 */ 3048 @ViewDebug.ExportedProperty(category = "padding") 3049 protected int mPaddingBottom; 3050 3051 /** 3052 * The layout insets in pixels, that is the distance in pixels between the 3053 * visible edges of this view its bounds. 3054 */ 3055 private Insets mLayoutInsets; 3056 3057 /** 3058 * Briefly describes the view and is primarily used for accessibility support. 3059 */ 3060 private CharSequence mContentDescription; 3061 3062 /** 3063 * Specifies the id of a view for which this view serves as a label for 3064 * accessibility purposes. 3065 */ 3066 private int mLabelForId = View.NO_ID; 3067 3068 /** 3069 * Predicate for matching labeled view id with its label for 3070 * accessibility purposes. 3071 */ 3072 private MatchLabelForPredicate mMatchLabelForPredicate; 3073 3074 /** 3075 * Specifies a view before which this one is visited in accessibility traversal. 3076 */ 3077 private int mAccessibilityTraversalBeforeId = NO_ID; 3078 3079 /** 3080 * Specifies a view after which this one is visited in accessibility traversal. 3081 */ 3082 private int mAccessibilityTraversalAfterId = NO_ID; 3083 3084 /** 3085 * Predicate for matching a view by its id. 3086 */ 3087 private MatchIdPredicate mMatchIdPredicate; 3088 3089 /** 3090 * Cache the paddingRight set by the user to append to the scrollbar's size. 3091 * 3092 * @hide 3093 */ 3094 @ViewDebug.ExportedProperty(category = "padding") 3095 protected int mUserPaddingRight; 3096 3097 /** 3098 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3099 * 3100 * @hide 3101 */ 3102 @ViewDebug.ExportedProperty(category = "padding") 3103 protected int mUserPaddingBottom; 3104 3105 /** 3106 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3107 * 3108 * @hide 3109 */ 3110 @ViewDebug.ExportedProperty(category = "padding") 3111 protected int mUserPaddingLeft; 3112 3113 /** 3114 * Cache the paddingStart set by the user to append to the scrollbar's size. 3115 * 3116 */ 3117 @ViewDebug.ExportedProperty(category = "padding") 3118 int mUserPaddingStart; 3119 3120 /** 3121 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3122 * 3123 */ 3124 @ViewDebug.ExportedProperty(category = "padding") 3125 int mUserPaddingEnd; 3126 3127 /** 3128 * Cache initial left padding. 3129 * 3130 * @hide 3131 */ 3132 int mUserPaddingLeftInitial; 3133 3134 /** 3135 * Cache initial right padding. 3136 * 3137 * @hide 3138 */ 3139 int mUserPaddingRightInitial; 3140 3141 /** 3142 * Default undefined padding 3143 */ 3144 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3145 3146 /** 3147 * Cache if a left padding has been defined 3148 */ 3149 private boolean mLeftPaddingDefined = false; 3150 3151 /** 3152 * Cache if a right padding has been defined 3153 */ 3154 private boolean mRightPaddingDefined = false; 3155 3156 /** 3157 * @hide 3158 */ 3159 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3160 /** 3161 * @hide 3162 */ 3163 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3164 3165 private LongSparseLongArray mMeasureCache; 3166 3167 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3168 private Drawable mBackground; 3169 private TintInfo mBackgroundTint; 3170 3171 /** 3172 * RenderNode used for backgrounds. 3173 * <p> 3174 * When non-null and valid, this is expected to contain an up-to-date copy 3175 * of the background drawable. It is cleared on temporary detach, and reset 3176 * on cleanup. 3177 */ 3178 private RenderNode mBackgroundRenderNode; 3179 3180 private int mBackgroundResource; 3181 private boolean mBackgroundSizeChanged; 3182 3183 private String mTransitionName; 3184 3185 private static class TintInfo { 3186 ColorStateList mTintList; 3187 PorterDuff.Mode mTintMode; 3188 boolean mHasTintMode; 3189 boolean mHasTintList; 3190 } 3191 3192 static class ListenerInfo { 3193 /** 3194 * Listener used to dispatch focus change events. 3195 * This field should be made private, so it is hidden from the SDK. 3196 * {@hide} 3197 */ 3198 protected OnFocusChangeListener mOnFocusChangeListener; 3199 3200 /** 3201 * Listeners for layout change events. 3202 */ 3203 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3204 3205 protected OnScrollChangeListener mOnScrollChangeListener; 3206 3207 /** 3208 * Listeners for attach events. 3209 */ 3210 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3211 3212 /** 3213 * Listener used to dispatch click events. 3214 * This field should be made private, so it is hidden from the SDK. 3215 * {@hide} 3216 */ 3217 public OnClickListener mOnClickListener; 3218 3219 /** 3220 * Listener used to dispatch long click events. 3221 * This field should be made private, so it is hidden from the SDK. 3222 * {@hide} 3223 */ 3224 protected OnLongClickListener mOnLongClickListener; 3225 3226 /** 3227 * Listener used to build the context menu. 3228 * This field should be made private, so it is hidden from the SDK. 3229 * {@hide} 3230 */ 3231 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3232 3233 private OnKeyListener mOnKeyListener; 3234 3235 private OnTouchListener mOnTouchListener; 3236 3237 private OnHoverListener mOnHoverListener; 3238 3239 private OnGenericMotionListener mOnGenericMotionListener; 3240 3241 private OnDragListener mOnDragListener; 3242 3243 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3244 3245 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3246 } 3247 3248 ListenerInfo mListenerInfo; 3249 3250 /** 3251 * The application environment this view lives in. 3252 * This field should be made private, so it is hidden from the SDK. 3253 * {@hide} 3254 */ 3255 @ViewDebug.ExportedProperty(deepExport = true) 3256 protected Context mContext; 3257 3258 private final Resources mResources; 3259 3260 private ScrollabilityCache mScrollCache; 3261 3262 private int[] mDrawableState = null; 3263 3264 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3265 3266 /** 3267 * Animator that automatically runs based on state changes. 3268 */ 3269 private StateListAnimator mStateListAnimator; 3270 3271 /** 3272 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3273 * the user may specify which view to go to next. 3274 */ 3275 private int mNextFocusLeftId = View.NO_ID; 3276 3277 /** 3278 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3279 * the user may specify which view to go to next. 3280 */ 3281 private int mNextFocusRightId = View.NO_ID; 3282 3283 /** 3284 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3285 * the user may specify which view to go to next. 3286 */ 3287 private int mNextFocusUpId = View.NO_ID; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3291 * the user may specify which view to go to next. 3292 */ 3293 private int mNextFocusDownId = View.NO_ID; 3294 3295 /** 3296 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3297 * the user may specify which view to go to next. 3298 */ 3299 int mNextFocusForwardId = View.NO_ID; 3300 3301 private CheckForLongPress mPendingCheckForLongPress; 3302 private CheckForTap mPendingCheckForTap = null; 3303 private PerformClick mPerformClick; 3304 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3305 3306 private UnsetPressedState mUnsetPressedState; 3307 3308 /** 3309 * Whether the long press's action has been invoked. The tap's action is invoked on the 3310 * up event while a long press is invoked as soon as the long press duration is reached, so 3311 * a long press could be performed before the tap is checked, in which case the tap's action 3312 * should not be invoked. 3313 */ 3314 private boolean mHasPerformedLongPress; 3315 3316 /** 3317 * The minimum height of the view. We'll try our best to have the height 3318 * of this view to at least this amount. 3319 */ 3320 @ViewDebug.ExportedProperty(category = "measurement") 3321 private int mMinHeight; 3322 3323 /** 3324 * The minimum width of the view. We'll try our best to have the width 3325 * of this view to at least this amount. 3326 */ 3327 @ViewDebug.ExportedProperty(category = "measurement") 3328 private int mMinWidth; 3329 3330 /** 3331 * The delegate to handle touch events that are physically in this view 3332 * but should be handled by another view. 3333 */ 3334 private TouchDelegate mTouchDelegate = null; 3335 3336 /** 3337 * Solid color to use as a background when creating the drawing cache. Enables 3338 * the cache to use 16 bit bitmaps instead of 32 bit. 3339 */ 3340 private int mDrawingCacheBackgroundColor = 0; 3341 3342 /** 3343 * Special tree observer used when mAttachInfo is null. 3344 */ 3345 private ViewTreeObserver mFloatingTreeObserver; 3346 3347 /** 3348 * Cache the touch slop from the context that created the view. 3349 */ 3350 private int mTouchSlop; 3351 3352 /** 3353 * Object that handles automatic animation of view properties. 3354 */ 3355 private ViewPropertyAnimator mAnimator = null; 3356 3357 /** 3358 * Flag indicating that a drag can cross window boundaries. When 3359 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3360 * with this flag set, all visible applications will be able to participate 3361 * in the drag operation and receive the dragged content. 3362 * 3363 * @hide 3364 */ 3365 public static final int DRAG_FLAG_GLOBAL = 1; 3366 3367 /** 3368 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3369 */ 3370 private float mVerticalScrollFactor; 3371 3372 /** 3373 * Position of the vertical scroll bar. 3374 */ 3375 private int mVerticalScrollbarPosition; 3376 3377 /** 3378 * Position the scroll bar at the default position as determined by the system. 3379 */ 3380 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3381 3382 /** 3383 * Position the scroll bar along the left edge. 3384 */ 3385 public static final int SCROLLBAR_POSITION_LEFT = 1; 3386 3387 /** 3388 * Position the scroll bar along the right edge. 3389 */ 3390 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3391 3392 /** 3393 * Indicates that the view does not have a layer. 3394 * 3395 * @see #getLayerType() 3396 * @see #setLayerType(int, android.graphics.Paint) 3397 * @see #LAYER_TYPE_SOFTWARE 3398 * @see #LAYER_TYPE_HARDWARE 3399 */ 3400 public static final int LAYER_TYPE_NONE = 0; 3401 3402 /** 3403 * <p>Indicates that the view has a software layer. A software layer is backed 3404 * by a bitmap and causes the view to be rendered using Android's software 3405 * rendering pipeline, even if hardware acceleration is enabled.</p> 3406 * 3407 * <p>Software layers have various usages:</p> 3408 * <p>When the application is not using hardware acceleration, a software layer 3409 * is useful to apply a specific color filter and/or blending mode and/or 3410 * translucency to a view and all its children.</p> 3411 * <p>When the application is using hardware acceleration, a software layer 3412 * is useful to render drawing primitives not supported by the hardware 3413 * accelerated pipeline. It can also be used to cache a complex view tree 3414 * into a texture and reduce the complexity of drawing operations. For instance, 3415 * when animating a complex view tree with a translation, a software layer can 3416 * be used to render the view tree only once.</p> 3417 * <p>Software layers should be avoided when the affected view tree updates 3418 * often. Every update will require to re-render the software layer, which can 3419 * potentially be slow (particularly when hardware acceleration is turned on 3420 * since the layer will have to be uploaded into a hardware texture after every 3421 * update.)</p> 3422 * 3423 * @see #getLayerType() 3424 * @see #setLayerType(int, android.graphics.Paint) 3425 * @see #LAYER_TYPE_NONE 3426 * @see #LAYER_TYPE_HARDWARE 3427 */ 3428 public static final int LAYER_TYPE_SOFTWARE = 1; 3429 3430 /** 3431 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3432 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3433 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3434 * rendering pipeline, but only if hardware acceleration is turned on for the 3435 * view hierarchy. When hardware acceleration is turned off, hardware layers 3436 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3437 * 3438 * <p>A hardware layer is useful to apply a specific color filter and/or 3439 * blending mode and/or translucency to a view and all its children.</p> 3440 * <p>A hardware layer can be used to cache a complex view tree into a 3441 * texture and reduce the complexity of drawing operations. For instance, 3442 * when animating a complex view tree with a translation, a hardware layer can 3443 * be used to render the view tree only once.</p> 3444 * <p>A hardware layer can also be used to increase the rendering quality when 3445 * rotation transformations are applied on a view. It can also be used to 3446 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3447 * 3448 * @see #getLayerType() 3449 * @see #setLayerType(int, android.graphics.Paint) 3450 * @see #LAYER_TYPE_NONE 3451 * @see #LAYER_TYPE_SOFTWARE 3452 */ 3453 public static final int LAYER_TYPE_HARDWARE = 2; 3454 3455 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3456 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3457 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3458 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3459 }) 3460 int mLayerType = LAYER_TYPE_NONE; 3461 Paint mLayerPaint; 3462 3463 /** 3464 * Set to true when drawing cache is enabled and cannot be created. 3465 * 3466 * @hide 3467 */ 3468 public boolean mCachingFailed; 3469 private Bitmap mDrawingCache; 3470 private Bitmap mUnscaledDrawingCache; 3471 3472 /** 3473 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3474 * <p> 3475 * When non-null and valid, this is expected to contain an up-to-date copy 3476 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3477 * cleanup. 3478 */ 3479 final RenderNode mRenderNode; 3480 3481 /** 3482 * Set to true when the view is sending hover accessibility events because it 3483 * is the innermost hovered view. 3484 */ 3485 private boolean mSendingHoverAccessibilityEvents; 3486 3487 /** 3488 * Delegate for injecting accessibility functionality. 3489 */ 3490 AccessibilityDelegate mAccessibilityDelegate; 3491 3492 /** 3493 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3494 * and add/remove objects to/from the overlay directly through the Overlay methods. 3495 */ 3496 ViewOverlay mOverlay; 3497 3498 /** 3499 * The currently active parent view for receiving delegated nested scrolling events. 3500 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3501 * by {@link #stopNestedScroll()} at the same point where we clear 3502 * requestDisallowInterceptTouchEvent. 3503 */ 3504 private ViewParent mNestedScrollingParent; 3505 3506 /** 3507 * Consistency verifier for debugging purposes. 3508 * @hide 3509 */ 3510 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3511 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3512 new InputEventConsistencyVerifier(this, 0) : null; 3513 3514 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3515 3516 private int[] mTempNestedScrollConsumed; 3517 3518 /** 3519 * An overlay is going to draw this View instead of being drawn as part of this 3520 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3521 * when this view is invalidated. 3522 */ 3523 GhostView mGhostView; 3524 3525 /** 3526 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3527 * @hide 3528 */ 3529 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3530 public String[] mAttributes; 3531 3532 /** 3533 * Maps a Resource id to its name. 3534 */ 3535 private static SparseArray<String> mAttributeMap; 3536 3537 /** 3538 * Simple constructor to use when creating a view from code. 3539 * 3540 * @param context The Context the view is running in, through which it can 3541 * access the current theme, resources, etc. 3542 */ 3543 public View(Context context) { 3544 mContext = context; 3545 mResources = context != null ? context.getResources() : null; 3546 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3547 // Set some flags defaults 3548 mPrivateFlags2 = 3549 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3550 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3551 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3552 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3553 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3554 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3555 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3556 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3557 mUserPaddingStart = UNDEFINED_PADDING; 3558 mUserPaddingEnd = UNDEFINED_PADDING; 3559 mRenderNode = RenderNode.create(getClass().getName(), this); 3560 3561 if (!sCompatibilityDone && context != null) { 3562 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3563 3564 // Older apps may need this compatibility hack for measurement. 3565 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3566 3567 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3568 // of whether a layout was requested on that View. 3569 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3570 3571 sCompatibilityDone = true; 3572 } 3573 } 3574 3575 /** 3576 * Constructor that is called when inflating a view from XML. This is called 3577 * when a view is being constructed from an XML file, supplying attributes 3578 * that were specified in the XML file. This version uses a default style of 3579 * 0, so the only attribute values applied are those in the Context's Theme 3580 * and the given AttributeSet. 3581 * 3582 * <p> 3583 * The method onFinishInflate() will be called after all children have been 3584 * added. 3585 * 3586 * @param context The Context the view is running in, through which it can 3587 * access the current theme, resources, etc. 3588 * @param attrs The attributes of the XML tag that is inflating the view. 3589 * @see #View(Context, AttributeSet, int) 3590 */ 3591 public View(Context context, @Nullable AttributeSet attrs) { 3592 this(context, attrs, 0); 3593 } 3594 3595 /** 3596 * Perform inflation from XML and apply a class-specific base style from a 3597 * theme attribute. This constructor of View allows subclasses to use their 3598 * own base style when they are inflating. For example, a Button class's 3599 * constructor would call this version of the super class constructor and 3600 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3601 * allows the theme's button style to modify all of the base view attributes 3602 * (in particular its background) as well as the Button class's attributes. 3603 * 3604 * @param context The Context the view is running in, through which it can 3605 * access the current theme, resources, etc. 3606 * @param attrs The attributes of the XML tag that is inflating the view. 3607 * @param defStyleAttr An attribute in the current theme that contains a 3608 * reference to a style resource that supplies default values for 3609 * the view. Can be 0 to not look for defaults. 3610 * @see #View(Context, AttributeSet) 3611 */ 3612 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 3613 this(context, attrs, defStyleAttr, 0); 3614 } 3615 3616 /** 3617 * Perform inflation from XML and apply a class-specific base style from a 3618 * theme attribute or style resource. This constructor of View allows 3619 * subclasses to use their own base style when they are inflating. 3620 * <p> 3621 * When determining the final value of a particular attribute, there are 3622 * four inputs that come into play: 3623 * <ol> 3624 * <li>Any attribute values in the given AttributeSet. 3625 * <li>The style resource specified in the AttributeSet (named "style"). 3626 * <li>The default style specified by <var>defStyleAttr</var>. 3627 * <li>The default style specified by <var>defStyleRes</var>. 3628 * <li>The base values in this theme. 3629 * </ol> 3630 * <p> 3631 * Each of these inputs is considered in-order, with the first listed taking 3632 * precedence over the following ones. In other words, if in the 3633 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3634 * , then the button's text will <em>always</em> be black, regardless of 3635 * what is specified in any of the styles. 3636 * 3637 * @param context The Context the view is running in, through which it can 3638 * access the current theme, resources, etc. 3639 * @param attrs The attributes of the XML tag that is inflating the view. 3640 * @param defStyleAttr An attribute in the current theme that contains a 3641 * reference to a style resource that supplies default values for 3642 * the view. Can be 0 to not look for defaults. 3643 * @param defStyleRes A resource identifier of a style resource that 3644 * supplies default values for the view, used only if 3645 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3646 * to not look for defaults. 3647 * @see #View(Context, AttributeSet, int) 3648 */ 3649 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3650 this(context); 3651 3652 final TypedArray a = context.obtainStyledAttributes( 3653 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3654 3655 if (mDebugViewAttributes) { 3656 saveAttributeData(attrs, a); 3657 } 3658 3659 Drawable background = null; 3660 3661 int leftPadding = -1; 3662 int topPadding = -1; 3663 int rightPadding = -1; 3664 int bottomPadding = -1; 3665 int startPadding = UNDEFINED_PADDING; 3666 int endPadding = UNDEFINED_PADDING; 3667 3668 int padding = -1; 3669 3670 int viewFlagValues = 0; 3671 int viewFlagMasks = 0; 3672 3673 boolean setScrollContainer = false; 3674 3675 int x = 0; 3676 int y = 0; 3677 3678 float tx = 0; 3679 float ty = 0; 3680 float tz = 0; 3681 float elevation = 0; 3682 float rotation = 0; 3683 float rotationX = 0; 3684 float rotationY = 0; 3685 float sx = 1f; 3686 float sy = 1f; 3687 boolean transformSet = false; 3688 3689 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3690 int overScrollMode = mOverScrollMode; 3691 boolean initializeScrollbars = false; 3692 3693 boolean startPaddingDefined = false; 3694 boolean endPaddingDefined = false; 3695 boolean leftPaddingDefined = false; 3696 boolean rightPaddingDefined = false; 3697 3698 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3699 3700 final int N = a.getIndexCount(); 3701 for (int i = 0; i < N; i++) { 3702 int attr = a.getIndex(i); 3703 switch (attr) { 3704 case com.android.internal.R.styleable.View_background: 3705 background = a.getDrawable(attr); 3706 break; 3707 case com.android.internal.R.styleable.View_padding: 3708 padding = a.getDimensionPixelSize(attr, -1); 3709 mUserPaddingLeftInitial = padding; 3710 mUserPaddingRightInitial = padding; 3711 leftPaddingDefined = true; 3712 rightPaddingDefined = true; 3713 break; 3714 case com.android.internal.R.styleable.View_paddingLeft: 3715 leftPadding = a.getDimensionPixelSize(attr, -1); 3716 mUserPaddingLeftInitial = leftPadding; 3717 leftPaddingDefined = true; 3718 break; 3719 case com.android.internal.R.styleable.View_paddingTop: 3720 topPadding = a.getDimensionPixelSize(attr, -1); 3721 break; 3722 case com.android.internal.R.styleable.View_paddingRight: 3723 rightPadding = a.getDimensionPixelSize(attr, -1); 3724 mUserPaddingRightInitial = rightPadding; 3725 rightPaddingDefined = true; 3726 break; 3727 case com.android.internal.R.styleable.View_paddingBottom: 3728 bottomPadding = a.getDimensionPixelSize(attr, -1); 3729 break; 3730 case com.android.internal.R.styleable.View_paddingStart: 3731 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3732 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3733 break; 3734 case com.android.internal.R.styleable.View_paddingEnd: 3735 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3736 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3737 break; 3738 case com.android.internal.R.styleable.View_scrollX: 3739 x = a.getDimensionPixelOffset(attr, 0); 3740 break; 3741 case com.android.internal.R.styleable.View_scrollY: 3742 y = a.getDimensionPixelOffset(attr, 0); 3743 break; 3744 case com.android.internal.R.styleable.View_alpha: 3745 setAlpha(a.getFloat(attr, 1f)); 3746 break; 3747 case com.android.internal.R.styleable.View_transformPivotX: 3748 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3749 break; 3750 case com.android.internal.R.styleable.View_transformPivotY: 3751 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3752 break; 3753 case com.android.internal.R.styleable.View_translationX: 3754 tx = a.getDimensionPixelOffset(attr, 0); 3755 transformSet = true; 3756 break; 3757 case com.android.internal.R.styleable.View_translationY: 3758 ty = a.getDimensionPixelOffset(attr, 0); 3759 transformSet = true; 3760 break; 3761 case com.android.internal.R.styleable.View_translationZ: 3762 tz = a.getDimensionPixelOffset(attr, 0); 3763 transformSet = true; 3764 break; 3765 case com.android.internal.R.styleable.View_elevation: 3766 elevation = a.getDimensionPixelOffset(attr, 0); 3767 transformSet = true; 3768 break; 3769 case com.android.internal.R.styleable.View_rotation: 3770 rotation = a.getFloat(attr, 0); 3771 transformSet = true; 3772 break; 3773 case com.android.internal.R.styleable.View_rotationX: 3774 rotationX = a.getFloat(attr, 0); 3775 transformSet = true; 3776 break; 3777 case com.android.internal.R.styleable.View_rotationY: 3778 rotationY = a.getFloat(attr, 0); 3779 transformSet = true; 3780 break; 3781 case com.android.internal.R.styleable.View_scaleX: 3782 sx = a.getFloat(attr, 1f); 3783 transformSet = true; 3784 break; 3785 case com.android.internal.R.styleable.View_scaleY: 3786 sy = a.getFloat(attr, 1f); 3787 transformSet = true; 3788 break; 3789 case com.android.internal.R.styleable.View_id: 3790 mID = a.getResourceId(attr, NO_ID); 3791 break; 3792 case com.android.internal.R.styleable.View_tag: 3793 mTag = a.getText(attr); 3794 break; 3795 case com.android.internal.R.styleable.View_fitsSystemWindows: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3798 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_focusable: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= FOCUSABLE; 3804 viewFlagMasks |= FOCUSABLE_MASK; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_focusableInTouchMode: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3810 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_clickable: 3814 if (a.getBoolean(attr, false)) { 3815 viewFlagValues |= CLICKABLE; 3816 viewFlagMasks |= CLICKABLE; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_longClickable: 3820 if (a.getBoolean(attr, false)) { 3821 viewFlagValues |= LONG_CLICKABLE; 3822 viewFlagMasks |= LONG_CLICKABLE; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_saveEnabled: 3826 if (!a.getBoolean(attr, true)) { 3827 viewFlagValues |= SAVE_DISABLED; 3828 viewFlagMasks |= SAVE_DISABLED_MASK; 3829 } 3830 break; 3831 case com.android.internal.R.styleable.View_duplicateParentState: 3832 if (a.getBoolean(attr, false)) { 3833 viewFlagValues |= DUPLICATE_PARENT_STATE; 3834 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3835 } 3836 break; 3837 case com.android.internal.R.styleable.View_visibility: 3838 final int visibility = a.getInt(attr, 0); 3839 if (visibility != 0) { 3840 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3841 viewFlagMasks |= VISIBILITY_MASK; 3842 } 3843 break; 3844 case com.android.internal.R.styleable.View_layoutDirection: 3845 // Clear any layout direction flags (included resolved bits) already set 3846 mPrivateFlags2 &= 3847 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3848 // Set the layout direction flags depending on the value of the attribute 3849 final int layoutDirection = a.getInt(attr, -1); 3850 final int value = (layoutDirection != -1) ? 3851 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3852 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3853 break; 3854 case com.android.internal.R.styleable.View_drawingCacheQuality: 3855 final int cacheQuality = a.getInt(attr, 0); 3856 if (cacheQuality != 0) { 3857 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3858 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3859 } 3860 break; 3861 case com.android.internal.R.styleable.View_contentDescription: 3862 setContentDescription(a.getString(attr)); 3863 break; 3864 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 3865 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 3866 break; 3867 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 3868 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 3869 break; 3870 case com.android.internal.R.styleable.View_labelFor: 3871 setLabelFor(a.getResourceId(attr, NO_ID)); 3872 break; 3873 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3874 if (!a.getBoolean(attr, true)) { 3875 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3876 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3877 } 3878 break; 3879 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3880 if (!a.getBoolean(attr, true)) { 3881 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3882 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3883 } 3884 break; 3885 case R.styleable.View_scrollbars: 3886 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3887 if (scrollbars != SCROLLBARS_NONE) { 3888 viewFlagValues |= scrollbars; 3889 viewFlagMasks |= SCROLLBARS_MASK; 3890 initializeScrollbars = true; 3891 } 3892 break; 3893 //noinspection deprecation 3894 case R.styleable.View_fadingEdge: 3895 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3896 // Ignore the attribute starting with ICS 3897 break; 3898 } 3899 // With builds < ICS, fall through and apply fading edges 3900 case R.styleable.View_requiresFadingEdge: 3901 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3902 if (fadingEdge != FADING_EDGE_NONE) { 3903 viewFlagValues |= fadingEdge; 3904 viewFlagMasks |= FADING_EDGE_MASK; 3905 initializeFadingEdgeInternal(a); 3906 } 3907 break; 3908 case R.styleable.View_scrollbarStyle: 3909 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3910 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3911 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3912 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3913 } 3914 break; 3915 case R.styleable.View_isScrollContainer: 3916 setScrollContainer = true; 3917 if (a.getBoolean(attr, false)) { 3918 setScrollContainer(true); 3919 } 3920 break; 3921 case com.android.internal.R.styleable.View_keepScreenOn: 3922 if (a.getBoolean(attr, false)) { 3923 viewFlagValues |= KEEP_SCREEN_ON; 3924 viewFlagMasks |= KEEP_SCREEN_ON; 3925 } 3926 break; 3927 case R.styleable.View_filterTouchesWhenObscured: 3928 if (a.getBoolean(attr, false)) { 3929 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3930 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3931 } 3932 break; 3933 case R.styleable.View_nextFocusLeft: 3934 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3935 break; 3936 case R.styleable.View_nextFocusRight: 3937 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3938 break; 3939 case R.styleable.View_nextFocusUp: 3940 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3941 break; 3942 case R.styleable.View_nextFocusDown: 3943 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3944 break; 3945 case R.styleable.View_nextFocusForward: 3946 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3947 break; 3948 case R.styleable.View_minWidth: 3949 mMinWidth = a.getDimensionPixelSize(attr, 0); 3950 break; 3951 case R.styleable.View_minHeight: 3952 mMinHeight = a.getDimensionPixelSize(attr, 0); 3953 break; 3954 case R.styleable.View_onClick: 3955 if (context.isRestricted()) { 3956 throw new IllegalStateException("The android:onClick attribute cannot " 3957 + "be used within a restricted context"); 3958 } 3959 3960 final String handlerName = a.getString(attr); 3961 if (handlerName != null) { 3962 setOnClickListener(new OnClickListener() { 3963 private Method mHandler; 3964 3965 public void onClick(View v) { 3966 if (mHandler == null) { 3967 try { 3968 mHandler = getContext().getClass().getMethod(handlerName, 3969 View.class); 3970 } catch (NoSuchMethodException e) { 3971 int id = getId(); 3972 String idText = id == NO_ID ? "" : " with id '" 3973 + getContext().getResources().getResourceEntryName( 3974 id) + "'"; 3975 throw new IllegalStateException("Could not find a method " + 3976 handlerName + "(View) in the activity " 3977 + getContext().getClass() + " for onClick handler" 3978 + " on view " + View.this.getClass() + idText, e); 3979 } 3980 } 3981 3982 try { 3983 mHandler.invoke(getContext(), View.this); 3984 } catch (IllegalAccessException e) { 3985 throw new IllegalStateException("Could not execute non " 3986 + "public method of the activity", e); 3987 } catch (InvocationTargetException e) { 3988 throw new IllegalStateException("Could not execute " 3989 + "method of the activity", e); 3990 } 3991 } 3992 }); 3993 } 3994 break; 3995 case R.styleable.View_overScrollMode: 3996 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3997 break; 3998 case R.styleable.View_verticalScrollbarPosition: 3999 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4000 break; 4001 case R.styleable.View_layerType: 4002 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4003 break; 4004 case R.styleable.View_textDirection: 4005 // Clear any text direction flag already set 4006 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4007 // Set the text direction flags depending on the value of the attribute 4008 final int textDirection = a.getInt(attr, -1); 4009 if (textDirection != -1) { 4010 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4011 } 4012 break; 4013 case R.styleable.View_textAlignment: 4014 // Clear any text alignment flag already set 4015 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4016 // Set the text alignment flag depending on the value of the attribute 4017 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4018 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4019 break; 4020 case R.styleable.View_importantForAccessibility: 4021 setImportantForAccessibility(a.getInt(attr, 4022 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4023 break; 4024 case R.styleable.View_accessibilityLiveRegion: 4025 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4026 break; 4027 case R.styleable.View_transitionName: 4028 setTransitionName(a.getString(attr)); 4029 break; 4030 case R.styleable.View_nestedScrollingEnabled: 4031 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4032 break; 4033 case R.styleable.View_stateListAnimator: 4034 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4035 a.getResourceId(attr, 0))); 4036 break; 4037 case R.styleable.View_backgroundTint: 4038 // This will get applied later during setBackground(). 4039 if (mBackgroundTint == null) { 4040 mBackgroundTint = new TintInfo(); 4041 } 4042 mBackgroundTint.mTintList = a.getColorStateList( 4043 R.styleable.View_backgroundTint); 4044 mBackgroundTint.mHasTintList = true; 4045 break; 4046 case R.styleable.View_backgroundTintMode: 4047 // This will get applied later during setBackground(). 4048 if (mBackgroundTint == null) { 4049 mBackgroundTint = new TintInfo(); 4050 } 4051 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4052 R.styleable.View_backgroundTintMode, -1), null); 4053 mBackgroundTint.mHasTintMode = true; 4054 break; 4055 case R.styleable.View_outlineProvider: 4056 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4057 PROVIDER_BACKGROUND)); 4058 break; 4059 } 4060 } 4061 4062 setOverScrollMode(overScrollMode); 4063 4064 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4065 // the resolved layout direction). Those cached values will be used later during padding 4066 // resolution. 4067 mUserPaddingStart = startPadding; 4068 mUserPaddingEnd = endPadding; 4069 4070 if (background != null) { 4071 setBackground(background); 4072 } 4073 4074 // setBackground above will record that padding is currently provided by the background. 4075 // If we have padding specified via xml, record that here instead and use it. 4076 mLeftPaddingDefined = leftPaddingDefined; 4077 mRightPaddingDefined = rightPaddingDefined; 4078 4079 if (padding >= 0) { 4080 leftPadding = padding; 4081 topPadding = padding; 4082 rightPadding = padding; 4083 bottomPadding = padding; 4084 mUserPaddingLeftInitial = padding; 4085 mUserPaddingRightInitial = padding; 4086 } 4087 4088 if (isRtlCompatibilityMode()) { 4089 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4090 // left / right padding are used if defined (meaning here nothing to do). If they are not 4091 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4092 // start / end and resolve them as left / right (layout direction is not taken into account). 4093 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4094 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4095 // defined. 4096 if (!mLeftPaddingDefined && startPaddingDefined) { 4097 leftPadding = startPadding; 4098 } 4099 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4100 if (!mRightPaddingDefined && endPaddingDefined) { 4101 rightPadding = endPadding; 4102 } 4103 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4104 } else { 4105 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4106 // values defined. Otherwise, left /right values are used. 4107 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4108 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4109 // defined. 4110 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4111 4112 if (mLeftPaddingDefined && !hasRelativePadding) { 4113 mUserPaddingLeftInitial = leftPadding; 4114 } 4115 if (mRightPaddingDefined && !hasRelativePadding) { 4116 mUserPaddingRightInitial = rightPadding; 4117 } 4118 } 4119 4120 internalSetPadding( 4121 mUserPaddingLeftInitial, 4122 topPadding >= 0 ? topPadding : mPaddingTop, 4123 mUserPaddingRightInitial, 4124 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4125 4126 if (viewFlagMasks != 0) { 4127 setFlags(viewFlagValues, viewFlagMasks); 4128 } 4129 4130 if (initializeScrollbars) { 4131 initializeScrollbarsInternal(a); 4132 } 4133 4134 a.recycle(); 4135 4136 // Needs to be called after mViewFlags is set 4137 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4138 recomputePadding(); 4139 } 4140 4141 if (x != 0 || y != 0) { 4142 scrollTo(x, y); 4143 } 4144 4145 if (transformSet) { 4146 setTranslationX(tx); 4147 setTranslationY(ty); 4148 setTranslationZ(tz); 4149 setElevation(elevation); 4150 setRotation(rotation); 4151 setRotationX(rotationX); 4152 setRotationY(rotationY); 4153 setScaleX(sx); 4154 setScaleY(sy); 4155 } 4156 4157 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4158 setScrollContainer(true); 4159 } 4160 4161 computeOpaqueFlags(); 4162 } 4163 4164 /** 4165 * Non-public constructor for use in testing 4166 */ 4167 View() { 4168 mResources = null; 4169 mRenderNode = RenderNode.create(getClass().getName(), this); 4170 } 4171 4172 private static SparseArray<String> getAttributeMap() { 4173 if (mAttributeMap == null) { 4174 mAttributeMap = new SparseArray<String>(); 4175 } 4176 return mAttributeMap; 4177 } 4178 4179 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4180 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4181 mAttributes = new String[length]; 4182 4183 int i = 0; 4184 if (attrs != null) { 4185 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4186 mAttributes[i] = attrs.getAttributeName(i); 4187 mAttributes[i + 1] = attrs.getAttributeValue(i); 4188 } 4189 4190 } 4191 4192 SparseArray<String> attributeMap = getAttributeMap(); 4193 for (int j = 0; j < a.length(); ++j) { 4194 if (a.hasValue(j)) { 4195 try { 4196 int resourceId = a.getResourceId(j, 0); 4197 if (resourceId == 0) { 4198 continue; 4199 } 4200 4201 String resourceName = attributeMap.get(resourceId); 4202 if (resourceName == null) { 4203 resourceName = a.getResources().getResourceName(resourceId); 4204 attributeMap.put(resourceId, resourceName); 4205 } 4206 4207 mAttributes[i] = resourceName; 4208 mAttributes[i + 1] = a.getText(j).toString(); 4209 i += 2; 4210 } catch (Resources.NotFoundException e) { 4211 // if we can't get the resource name, we just ignore it 4212 } 4213 } 4214 } 4215 } 4216 4217 public String toString() { 4218 StringBuilder out = new StringBuilder(128); 4219 out.append(getClass().getName()); 4220 out.append('{'); 4221 out.append(Integer.toHexString(System.identityHashCode(this))); 4222 out.append(' '); 4223 switch (mViewFlags&VISIBILITY_MASK) { 4224 case VISIBLE: out.append('V'); break; 4225 case INVISIBLE: out.append('I'); break; 4226 case GONE: out.append('G'); break; 4227 default: out.append('.'); break; 4228 } 4229 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4230 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4231 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4232 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4233 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4234 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4235 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4236 out.append(' '); 4237 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4238 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4239 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4240 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4241 out.append('p'); 4242 } else { 4243 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4244 } 4245 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4246 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4247 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4248 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4249 out.append(' '); 4250 out.append(mLeft); 4251 out.append(','); 4252 out.append(mTop); 4253 out.append('-'); 4254 out.append(mRight); 4255 out.append(','); 4256 out.append(mBottom); 4257 final int id = getId(); 4258 if (id != NO_ID) { 4259 out.append(" #"); 4260 out.append(Integer.toHexString(id)); 4261 final Resources r = mResources; 4262 if (Resources.resourceHasPackage(id) && r != null) { 4263 try { 4264 String pkgname; 4265 switch (id&0xff000000) { 4266 case 0x7f000000: 4267 pkgname="app"; 4268 break; 4269 case 0x01000000: 4270 pkgname="android"; 4271 break; 4272 default: 4273 pkgname = r.getResourcePackageName(id); 4274 break; 4275 } 4276 String typename = r.getResourceTypeName(id); 4277 String entryname = r.getResourceEntryName(id); 4278 out.append(" "); 4279 out.append(pkgname); 4280 out.append(":"); 4281 out.append(typename); 4282 out.append("/"); 4283 out.append(entryname); 4284 } catch (Resources.NotFoundException e) { 4285 } 4286 } 4287 } 4288 out.append("}"); 4289 return out.toString(); 4290 } 4291 4292 /** 4293 * <p> 4294 * Initializes the fading edges from a given set of styled attributes. This 4295 * method should be called by subclasses that need fading edges and when an 4296 * instance of these subclasses is created programmatically rather than 4297 * being inflated from XML. This method is automatically called when the XML 4298 * is inflated. 4299 * </p> 4300 * 4301 * @param a the styled attributes set to initialize the fading edges from 4302 * 4303 * @removed 4304 */ 4305 protected void initializeFadingEdge(TypedArray a) { 4306 // This method probably shouldn't have been included in the SDK to begin with. 4307 // It relies on 'a' having been initialized using an attribute filter array that is 4308 // not publicly available to the SDK. The old method has been renamed 4309 // to initializeFadingEdgeInternal and hidden for framework use only; 4310 // this one initializes using defaults to make it safe to call for apps. 4311 4312 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4313 4314 initializeFadingEdgeInternal(arr); 4315 4316 arr.recycle(); 4317 } 4318 4319 /** 4320 * <p> 4321 * Initializes the fading edges from a given set of styled attributes. This 4322 * method should be called by subclasses that need fading edges and when an 4323 * instance of these subclasses is created programmatically rather than 4324 * being inflated from XML. This method is automatically called when the XML 4325 * is inflated. 4326 * </p> 4327 * 4328 * @param a the styled attributes set to initialize the fading edges from 4329 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4330 */ 4331 protected void initializeFadingEdgeInternal(TypedArray a) { 4332 initScrollCache(); 4333 4334 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4335 R.styleable.View_fadingEdgeLength, 4336 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4337 } 4338 4339 /** 4340 * Returns the size of the vertical faded edges used to indicate that more 4341 * content in this view is visible. 4342 * 4343 * @return The size in pixels of the vertical faded edge or 0 if vertical 4344 * faded edges are not enabled for this view. 4345 * @attr ref android.R.styleable#View_fadingEdgeLength 4346 */ 4347 public int getVerticalFadingEdgeLength() { 4348 if (isVerticalFadingEdgeEnabled()) { 4349 ScrollabilityCache cache = mScrollCache; 4350 if (cache != null) { 4351 return cache.fadingEdgeLength; 4352 } 4353 } 4354 return 0; 4355 } 4356 4357 /** 4358 * Set the size of the faded edge used to indicate that more content in this 4359 * view is available. Will not change whether the fading edge is enabled; use 4360 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4361 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4362 * for the vertical or horizontal fading edges. 4363 * 4364 * @param length The size in pixels of the faded edge used to indicate that more 4365 * content in this view is visible. 4366 */ 4367 public void setFadingEdgeLength(int length) { 4368 initScrollCache(); 4369 mScrollCache.fadingEdgeLength = length; 4370 } 4371 4372 /** 4373 * Returns the size of the horizontal faded edges used to indicate that more 4374 * content in this view is visible. 4375 * 4376 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4377 * faded edges are not enabled for this view. 4378 * @attr ref android.R.styleable#View_fadingEdgeLength 4379 */ 4380 public int getHorizontalFadingEdgeLength() { 4381 if (isHorizontalFadingEdgeEnabled()) { 4382 ScrollabilityCache cache = mScrollCache; 4383 if (cache != null) { 4384 return cache.fadingEdgeLength; 4385 } 4386 } 4387 return 0; 4388 } 4389 4390 /** 4391 * Returns the width of the vertical scrollbar. 4392 * 4393 * @return The width in pixels of the vertical scrollbar or 0 if there 4394 * is no vertical scrollbar. 4395 */ 4396 public int getVerticalScrollbarWidth() { 4397 ScrollabilityCache cache = mScrollCache; 4398 if (cache != null) { 4399 ScrollBarDrawable scrollBar = cache.scrollBar; 4400 if (scrollBar != null) { 4401 int size = scrollBar.getSize(true); 4402 if (size <= 0) { 4403 size = cache.scrollBarSize; 4404 } 4405 return size; 4406 } 4407 return 0; 4408 } 4409 return 0; 4410 } 4411 4412 /** 4413 * Returns the height of the horizontal scrollbar. 4414 * 4415 * @return The height in pixels of the horizontal scrollbar or 0 if 4416 * there is no horizontal scrollbar. 4417 */ 4418 protected int getHorizontalScrollbarHeight() { 4419 ScrollabilityCache cache = mScrollCache; 4420 if (cache != null) { 4421 ScrollBarDrawable scrollBar = cache.scrollBar; 4422 if (scrollBar != null) { 4423 int size = scrollBar.getSize(false); 4424 if (size <= 0) { 4425 size = cache.scrollBarSize; 4426 } 4427 return size; 4428 } 4429 return 0; 4430 } 4431 return 0; 4432 } 4433 4434 /** 4435 * <p> 4436 * Initializes the scrollbars from a given set of styled attributes. This 4437 * method should be called by subclasses that need scrollbars and when an 4438 * instance of these subclasses is created programmatically rather than 4439 * being inflated from XML. This method is automatically called when the XML 4440 * is inflated. 4441 * </p> 4442 * 4443 * @param a the styled attributes set to initialize the scrollbars from 4444 * 4445 * @removed 4446 */ 4447 protected void initializeScrollbars(TypedArray a) { 4448 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4449 // using the View filter array which is not available to the SDK. As such, internal 4450 // framework usage now uses initializeScrollbarsInternal and we grab a default 4451 // TypedArray with the right filter instead here. 4452 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4453 4454 initializeScrollbarsInternal(arr); 4455 4456 // We ignored the method parameter. Recycle the one we actually did use. 4457 arr.recycle(); 4458 } 4459 4460 /** 4461 * <p> 4462 * Initializes the scrollbars from a given set of styled attributes. This 4463 * method should be called by subclasses that need scrollbars and when an 4464 * instance of these subclasses is created programmatically rather than 4465 * being inflated from XML. This method is automatically called when the XML 4466 * is inflated. 4467 * </p> 4468 * 4469 * @param a the styled attributes set to initialize the scrollbars from 4470 * @hide 4471 */ 4472 protected void initializeScrollbarsInternal(TypedArray a) { 4473 initScrollCache(); 4474 4475 final ScrollabilityCache scrollabilityCache = mScrollCache; 4476 4477 if (scrollabilityCache.scrollBar == null) { 4478 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4479 scrollabilityCache.scrollBar.setCallback(this); 4480 scrollabilityCache.scrollBar.setState(getDrawableState()); 4481 } 4482 4483 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4484 4485 if (!fadeScrollbars) { 4486 scrollabilityCache.state = ScrollabilityCache.ON; 4487 } 4488 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4489 4490 4491 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4492 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4493 .getScrollBarFadeDuration()); 4494 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4495 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4496 ViewConfiguration.getScrollDefaultDelay()); 4497 4498 4499 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4500 com.android.internal.R.styleable.View_scrollbarSize, 4501 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4502 4503 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4504 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4505 4506 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4507 if (thumb != null) { 4508 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4509 } 4510 4511 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4512 false); 4513 if (alwaysDraw) { 4514 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4515 } 4516 4517 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4518 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4519 4520 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4521 if (thumb != null) { 4522 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4523 } 4524 4525 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4526 false); 4527 if (alwaysDraw) { 4528 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4529 } 4530 4531 // Apply layout direction to the new Drawables if needed 4532 final int layoutDirection = getLayoutDirection(); 4533 if (track != null) { 4534 track.setLayoutDirection(layoutDirection); 4535 } 4536 if (thumb != null) { 4537 thumb.setLayoutDirection(layoutDirection); 4538 } 4539 4540 // Re-apply user/background padding so that scrollbar(s) get added 4541 resolvePadding(); 4542 } 4543 4544 /** 4545 * <p> 4546 * Initalizes the scrollability cache if necessary. 4547 * </p> 4548 */ 4549 private void initScrollCache() { 4550 if (mScrollCache == null) { 4551 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4552 } 4553 } 4554 4555 private ScrollabilityCache getScrollCache() { 4556 initScrollCache(); 4557 return mScrollCache; 4558 } 4559 4560 /** 4561 * Set the position of the vertical scroll bar. Should be one of 4562 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4563 * {@link #SCROLLBAR_POSITION_RIGHT}. 4564 * 4565 * @param position Where the vertical scroll bar should be positioned. 4566 */ 4567 public void setVerticalScrollbarPosition(int position) { 4568 if (mVerticalScrollbarPosition != position) { 4569 mVerticalScrollbarPosition = position; 4570 computeOpaqueFlags(); 4571 resolvePadding(); 4572 } 4573 } 4574 4575 /** 4576 * @return The position where the vertical scroll bar will show, if applicable. 4577 * @see #setVerticalScrollbarPosition(int) 4578 */ 4579 public int getVerticalScrollbarPosition() { 4580 return mVerticalScrollbarPosition; 4581 } 4582 4583 ListenerInfo getListenerInfo() { 4584 if (mListenerInfo != null) { 4585 return mListenerInfo; 4586 } 4587 mListenerInfo = new ListenerInfo(); 4588 return mListenerInfo; 4589 } 4590 4591 /** 4592 * Register a callback to be invoked when the scroll X or Y positions of 4593 * this view change. 4594 * <p> 4595 * <b>Note:</b> Some views handle scrolling independently from View and may 4596 * have their own separate listeners for scroll-type events. For example, 4597 * {@link android.widget.ListView ListView} allows clients to register an 4598 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 4599 * to listen for changes in list scroll position. 4600 * 4601 * @param l The listener to notify when the scroll X or Y position changes. 4602 * @see android.view.View#getScrollX() 4603 * @see android.view.View#getScrollY() 4604 */ 4605 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4606 getListenerInfo().mOnScrollChangeListener = l; 4607 } 4608 4609 /** 4610 * Register a callback to be invoked when focus of this view changed. 4611 * 4612 * @param l The callback that will run. 4613 */ 4614 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4615 getListenerInfo().mOnFocusChangeListener = l; 4616 } 4617 4618 /** 4619 * Add a listener that will be called when the bounds of the view change due to 4620 * layout processing. 4621 * 4622 * @param listener The listener that will be called when layout bounds change. 4623 */ 4624 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4625 ListenerInfo li = getListenerInfo(); 4626 if (li.mOnLayoutChangeListeners == null) { 4627 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4628 } 4629 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4630 li.mOnLayoutChangeListeners.add(listener); 4631 } 4632 } 4633 4634 /** 4635 * Remove a listener for layout changes. 4636 * 4637 * @param listener The listener for layout bounds change. 4638 */ 4639 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4640 ListenerInfo li = mListenerInfo; 4641 if (li == null || li.mOnLayoutChangeListeners == null) { 4642 return; 4643 } 4644 li.mOnLayoutChangeListeners.remove(listener); 4645 } 4646 4647 /** 4648 * Add a listener for attach state changes. 4649 * 4650 * This listener will be called whenever this view is attached or detached 4651 * from a window. Remove the listener using 4652 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4653 * 4654 * @param listener Listener to attach 4655 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4656 */ 4657 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4658 ListenerInfo li = getListenerInfo(); 4659 if (li.mOnAttachStateChangeListeners == null) { 4660 li.mOnAttachStateChangeListeners 4661 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4662 } 4663 li.mOnAttachStateChangeListeners.add(listener); 4664 } 4665 4666 /** 4667 * Remove a listener for attach state changes. The listener will receive no further 4668 * notification of window attach/detach events. 4669 * 4670 * @param listener Listener to remove 4671 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4672 */ 4673 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4674 ListenerInfo li = mListenerInfo; 4675 if (li == null || li.mOnAttachStateChangeListeners == null) { 4676 return; 4677 } 4678 li.mOnAttachStateChangeListeners.remove(listener); 4679 } 4680 4681 /** 4682 * Returns the focus-change callback registered for this view. 4683 * 4684 * @return The callback, or null if one is not registered. 4685 */ 4686 public OnFocusChangeListener getOnFocusChangeListener() { 4687 ListenerInfo li = mListenerInfo; 4688 return li != null ? li.mOnFocusChangeListener : null; 4689 } 4690 4691 /** 4692 * Register a callback to be invoked when this view is clicked. If this view is not 4693 * clickable, it becomes clickable. 4694 * 4695 * @param l The callback that will run 4696 * 4697 * @see #setClickable(boolean) 4698 */ 4699 public void setOnClickListener(@Nullable OnClickListener l) { 4700 if (!isClickable()) { 4701 setClickable(true); 4702 } 4703 getListenerInfo().mOnClickListener = l; 4704 } 4705 4706 /** 4707 * Return whether this view has an attached OnClickListener. Returns 4708 * true if there is a listener, false if there is none. 4709 */ 4710 public boolean hasOnClickListeners() { 4711 ListenerInfo li = mListenerInfo; 4712 return (li != null && li.mOnClickListener != null); 4713 } 4714 4715 /** 4716 * Register a callback to be invoked when this view is clicked and held. If this view is not 4717 * long clickable, it becomes long clickable. 4718 * 4719 * @param l The callback that will run 4720 * 4721 * @see #setLongClickable(boolean) 4722 */ 4723 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 4724 if (!isLongClickable()) { 4725 setLongClickable(true); 4726 } 4727 getListenerInfo().mOnLongClickListener = l; 4728 } 4729 4730 /** 4731 * Register a callback to be invoked when the context menu for this view is 4732 * being built. If this view is not long clickable, it becomes long clickable. 4733 * 4734 * @param l The callback that will run 4735 * 4736 */ 4737 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4738 if (!isLongClickable()) { 4739 setLongClickable(true); 4740 } 4741 getListenerInfo().mOnCreateContextMenuListener = l; 4742 } 4743 4744 /** 4745 * Call this view's OnClickListener, if it is defined. Performs all normal 4746 * actions associated with clicking: reporting accessibility event, playing 4747 * a sound, etc. 4748 * 4749 * @return True there was an assigned OnClickListener that was called, false 4750 * otherwise is returned. 4751 */ 4752 public boolean performClick() { 4753 final boolean result; 4754 final ListenerInfo li = mListenerInfo; 4755 if (li != null && li.mOnClickListener != null) { 4756 playSoundEffect(SoundEffectConstants.CLICK); 4757 li.mOnClickListener.onClick(this); 4758 result = true; 4759 } else { 4760 result = false; 4761 } 4762 4763 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4764 return result; 4765 } 4766 4767 /** 4768 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4769 * this only calls the listener, and does not do any associated clicking 4770 * actions like reporting an accessibility event. 4771 * 4772 * @return True there was an assigned OnClickListener that was called, false 4773 * otherwise is returned. 4774 */ 4775 public boolean callOnClick() { 4776 ListenerInfo li = mListenerInfo; 4777 if (li != null && li.mOnClickListener != null) { 4778 li.mOnClickListener.onClick(this); 4779 return true; 4780 } 4781 return false; 4782 } 4783 4784 /** 4785 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4786 * OnLongClickListener did not consume the event. 4787 * 4788 * @return True if one of the above receivers consumed the event, false otherwise. 4789 */ 4790 public boolean performLongClick() { 4791 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4792 4793 boolean handled = false; 4794 ListenerInfo li = mListenerInfo; 4795 if (li != null && li.mOnLongClickListener != null) { 4796 handled = li.mOnLongClickListener.onLongClick(View.this); 4797 } 4798 if (!handled) { 4799 handled = showContextMenu(); 4800 } 4801 if (handled) { 4802 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4803 } 4804 return handled; 4805 } 4806 4807 /** 4808 * Performs button-related actions during a touch down event. 4809 * 4810 * @param event The event. 4811 * @return True if the down was consumed. 4812 * 4813 * @hide 4814 */ 4815 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4816 if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE && 4817 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4818 showContextMenu(event.getX(), event.getY(), event.getMetaState()); 4819 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 4820 return true; 4821 } 4822 return false; 4823 } 4824 4825 /** 4826 * Bring up the context menu for this view. 4827 * 4828 * @return Whether a context menu was displayed. 4829 */ 4830 public boolean showContextMenu() { 4831 return getParent().showContextMenuForChild(this); 4832 } 4833 4834 /** 4835 * Bring up the context menu for this view, referring to the item under the specified point. 4836 * 4837 * @param x The referenced x coordinate. 4838 * @param y The referenced y coordinate. 4839 * @param metaState The keyboard modifiers that were pressed. 4840 * @return Whether a context menu was displayed. 4841 * 4842 * @hide 4843 */ 4844 public boolean showContextMenu(float x, float y, int metaState) { 4845 return showContextMenu(); 4846 } 4847 4848 /** 4849 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 4850 * 4851 * @param callback Callback that will control the lifecycle of the action mode 4852 * @return The new action mode if it is started, null otherwise 4853 * 4854 * @see ActionMode 4855 * @see #startActionMode(android.view.ActionMode.Callback, int) 4856 */ 4857 public ActionMode startActionMode(ActionMode.Callback callback) { 4858 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 4859 } 4860 4861 /** 4862 * Start an action mode with the given type. 4863 * 4864 * @param callback Callback that will control the lifecycle of the action mode 4865 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 4866 * @return The new action mode if it is started, null otherwise 4867 * 4868 * @see ActionMode 4869 */ 4870 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 4871 ViewParent parent = getParent(); 4872 if (parent == null) return null; 4873 try { 4874 return parent.startActionModeForChild(this, callback, type); 4875 } catch (AbstractMethodError ame) { 4876 // Older implementations of custom views might not implement this. 4877 return parent.startActionModeForChild(this, callback); 4878 } 4879 } 4880 4881 /** 4882 * Register a callback to be invoked when a hardware key is pressed in this view. 4883 * Key presses in software input methods will generally not trigger the methods of 4884 * this listener. 4885 * @param l the key listener to attach to this view 4886 */ 4887 public void setOnKeyListener(OnKeyListener l) { 4888 getListenerInfo().mOnKeyListener = l; 4889 } 4890 4891 /** 4892 * Register a callback to be invoked when a touch event is sent to this view. 4893 * @param l the touch listener to attach to this view 4894 */ 4895 public void setOnTouchListener(OnTouchListener l) { 4896 getListenerInfo().mOnTouchListener = l; 4897 } 4898 4899 /** 4900 * Register a callback to be invoked when a generic motion event is sent to this view. 4901 * @param l the generic motion listener to attach to this view 4902 */ 4903 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4904 getListenerInfo().mOnGenericMotionListener = l; 4905 } 4906 4907 /** 4908 * Register a callback to be invoked when a hover event is sent to this view. 4909 * @param l the hover listener to attach to this view 4910 */ 4911 public void setOnHoverListener(OnHoverListener l) { 4912 getListenerInfo().mOnHoverListener = l; 4913 } 4914 4915 /** 4916 * Register a drag event listener callback object for this View. The parameter is 4917 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4918 * View, the system calls the 4919 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4920 * @param l An implementation of {@link android.view.View.OnDragListener}. 4921 */ 4922 public void setOnDragListener(OnDragListener l) { 4923 getListenerInfo().mOnDragListener = l; 4924 } 4925 4926 /** 4927 * Give this view focus. This will cause 4928 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4929 * 4930 * Note: this does not check whether this {@link View} should get focus, it just 4931 * gives it focus no matter what. It should only be called internally by framework 4932 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4933 * 4934 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4935 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4936 * focus moved when requestFocus() is called. It may not always 4937 * apply, in which case use the default View.FOCUS_DOWN. 4938 * @param previouslyFocusedRect The rectangle of the view that had focus 4939 * prior in this View's coordinate system. 4940 */ 4941 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4942 if (DBG) { 4943 System.out.println(this + " requestFocus()"); 4944 } 4945 4946 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4947 mPrivateFlags |= PFLAG_FOCUSED; 4948 4949 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4950 4951 if (mParent != null) { 4952 mParent.requestChildFocus(this, this); 4953 } 4954 4955 if (mAttachInfo != null) { 4956 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4957 } 4958 4959 onFocusChanged(true, direction, previouslyFocusedRect); 4960 refreshDrawableState(); 4961 } 4962 } 4963 4964 /** 4965 * Populates <code>outRect</code> with the hotspot bounds. By default, 4966 * the hotspot bounds are identical to the screen bounds. 4967 * 4968 * @param outRect rect to populate with hotspot bounds 4969 * @hide Only for internal use by views and widgets. 4970 */ 4971 public void getHotspotBounds(Rect outRect) { 4972 final Drawable background = getBackground(); 4973 if (background != null) { 4974 background.getHotspotBounds(outRect); 4975 } else { 4976 getBoundsOnScreen(outRect); 4977 } 4978 } 4979 4980 /** 4981 * Request that a rectangle of this view be visible on the screen, 4982 * scrolling if necessary just enough. 4983 * 4984 * <p>A View should call this if it maintains some notion of which part 4985 * of its content is interesting. For example, a text editing view 4986 * should call this when its cursor moves. 4987 * 4988 * @param rectangle The rectangle. 4989 * @return Whether any parent scrolled. 4990 */ 4991 public boolean requestRectangleOnScreen(Rect rectangle) { 4992 return requestRectangleOnScreen(rectangle, false); 4993 } 4994 4995 /** 4996 * Request that a rectangle of this view be visible on the screen, 4997 * scrolling if necessary just enough. 4998 * 4999 * <p>A View should call this if it maintains some notion of which part 5000 * of its content is interesting. For example, a text editing view 5001 * should call this when its cursor moves. 5002 * 5003 * <p>When <code>immediate</code> is set to true, scrolling will not be 5004 * animated. 5005 * 5006 * @param rectangle The rectangle. 5007 * @param immediate True to forbid animated scrolling, false otherwise 5008 * @return Whether any parent scrolled. 5009 */ 5010 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5011 if (mParent == null) { 5012 return false; 5013 } 5014 5015 View child = this; 5016 5017 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5018 position.set(rectangle); 5019 5020 ViewParent parent = mParent; 5021 boolean scrolled = false; 5022 while (parent != null) { 5023 rectangle.set((int) position.left, (int) position.top, 5024 (int) position.right, (int) position.bottom); 5025 5026 scrolled |= parent.requestChildRectangleOnScreen(child, 5027 rectangle, immediate); 5028 5029 if (!child.hasIdentityMatrix()) { 5030 child.getMatrix().mapRect(position); 5031 } 5032 5033 position.offset(child.mLeft, child.mTop); 5034 5035 if (!(parent instanceof View)) { 5036 break; 5037 } 5038 5039 View parentView = (View) parent; 5040 5041 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5042 5043 child = parentView; 5044 parent = child.getParent(); 5045 } 5046 5047 return scrolled; 5048 } 5049 5050 /** 5051 * Called when this view wants to give up focus. If focus is cleared 5052 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5053 * <p> 5054 * <strong>Note:</strong> When a View clears focus the framework is trying 5055 * to give focus to the first focusable View from the top. Hence, if this 5056 * View is the first from the top that can take focus, then all callbacks 5057 * related to clearing focus will be invoked after which the framework will 5058 * give focus to this view. 5059 * </p> 5060 */ 5061 public void clearFocus() { 5062 if (DBG) { 5063 System.out.println(this + " clearFocus()"); 5064 } 5065 5066 clearFocusInternal(null, true, true); 5067 } 5068 5069 /** 5070 * Clears focus from the view, optionally propagating the change up through 5071 * the parent hierarchy and requesting that the root view place new focus. 5072 * 5073 * @param propagate whether to propagate the change up through the parent 5074 * hierarchy 5075 * @param refocus when propagate is true, specifies whether to request the 5076 * root view place new focus 5077 */ 5078 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5079 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5080 mPrivateFlags &= ~PFLAG_FOCUSED; 5081 5082 if (propagate && mParent != null) { 5083 mParent.clearChildFocus(this); 5084 } 5085 5086 onFocusChanged(false, 0, null); 5087 refreshDrawableState(); 5088 5089 if (propagate && (!refocus || !rootViewRequestFocus())) { 5090 notifyGlobalFocusCleared(this); 5091 } 5092 } 5093 } 5094 5095 void notifyGlobalFocusCleared(View oldFocus) { 5096 if (oldFocus != null && mAttachInfo != null) { 5097 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5098 } 5099 } 5100 5101 boolean rootViewRequestFocus() { 5102 final View root = getRootView(); 5103 return root != null && root.requestFocus(); 5104 } 5105 5106 /** 5107 * Called internally by the view system when a new view is getting focus. 5108 * This is what clears the old focus. 5109 * <p> 5110 * <b>NOTE:</b> The parent view's focused child must be updated manually 5111 * after calling this method. Otherwise, the view hierarchy may be left in 5112 * an inconstent state. 5113 */ 5114 void unFocus(View focused) { 5115 if (DBG) { 5116 System.out.println(this + " unFocus()"); 5117 } 5118 5119 clearFocusInternal(focused, false, false); 5120 } 5121 5122 /** 5123 * Returns true if this view has focus itself, or is the ancestor of the 5124 * view that has focus. 5125 * 5126 * @return True if this view has or contains focus, false otherwise. 5127 */ 5128 @ViewDebug.ExportedProperty(category = "focus") 5129 public boolean hasFocus() { 5130 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5131 } 5132 5133 /** 5134 * Returns true if this view is focusable or if it contains a reachable View 5135 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5136 * is a View whose parents do not block descendants focus. 5137 * 5138 * Only {@link #VISIBLE} views are considered focusable. 5139 * 5140 * @return True if the view is focusable or if the view contains a focusable 5141 * View, false otherwise. 5142 * 5143 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5144 * @see ViewGroup#getTouchscreenBlocksFocus() 5145 */ 5146 public boolean hasFocusable() { 5147 if (!isFocusableInTouchMode()) { 5148 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5149 final ViewGroup g = (ViewGroup) p; 5150 if (g.shouldBlockFocusForTouchscreen()) { 5151 return false; 5152 } 5153 } 5154 } 5155 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5156 } 5157 5158 /** 5159 * Called by the view system when the focus state of this view changes. 5160 * When the focus change event is caused by directional navigation, direction 5161 * and previouslyFocusedRect provide insight into where the focus is coming from. 5162 * When overriding, be sure to call up through to the super class so that 5163 * the standard focus handling will occur. 5164 * 5165 * @param gainFocus True if the View has focus; false otherwise. 5166 * @param direction The direction focus has moved when requestFocus() 5167 * is called to give this view focus. Values are 5168 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5169 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5170 * It may not always apply, in which case use the default. 5171 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5172 * system, of the previously focused view. If applicable, this will be 5173 * passed in as finer grained information about where the focus is coming 5174 * from (in addition to direction). Will be <code>null</code> otherwise. 5175 */ 5176 @CallSuper 5177 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5178 @Nullable Rect previouslyFocusedRect) { 5179 if (gainFocus) { 5180 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5181 } else { 5182 notifyViewAccessibilityStateChangedIfNeeded( 5183 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5184 } 5185 5186 InputMethodManager imm = InputMethodManager.peekInstance(); 5187 if (!gainFocus) { 5188 if (isPressed()) { 5189 setPressed(false); 5190 } 5191 if (imm != null && mAttachInfo != null 5192 && mAttachInfo.mHasWindowFocus) { 5193 imm.focusOut(this); 5194 } 5195 onFocusLost(); 5196 } else if (imm != null && mAttachInfo != null 5197 && mAttachInfo.mHasWindowFocus) { 5198 imm.focusIn(this); 5199 } 5200 5201 invalidate(true); 5202 ListenerInfo li = mListenerInfo; 5203 if (li != null && li.mOnFocusChangeListener != null) { 5204 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5205 } 5206 5207 if (mAttachInfo != null) { 5208 mAttachInfo.mKeyDispatchState.reset(this); 5209 } 5210 } 5211 5212 /** 5213 * Sends an accessibility event of the given type. If accessibility is 5214 * not enabled this method has no effect. The default implementation calls 5215 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5216 * to populate information about the event source (this View), then calls 5217 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5218 * populate the text content of the event source including its descendants, 5219 * and last calls 5220 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5221 * on its parent to request sending of the event to interested parties. 5222 * <p> 5223 * If an {@link AccessibilityDelegate} has been specified via calling 5224 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5225 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5226 * responsible for handling this call. 5227 * </p> 5228 * 5229 * @param eventType The type of the event to send, as defined by several types from 5230 * {@link android.view.accessibility.AccessibilityEvent}, such as 5231 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5232 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5233 * 5234 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5235 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5236 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5237 * @see AccessibilityDelegate 5238 */ 5239 public void sendAccessibilityEvent(int eventType) { 5240 if (mAccessibilityDelegate != null) { 5241 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5242 } else { 5243 sendAccessibilityEventInternal(eventType); 5244 } 5245 } 5246 5247 /** 5248 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5249 * {@link AccessibilityEvent} to make an announcement which is related to some 5250 * sort of a context change for which none of the events representing UI transitions 5251 * is a good fit. For example, announcing a new page in a book. If accessibility 5252 * is not enabled this method does nothing. 5253 * 5254 * @param text The announcement text. 5255 */ 5256 public void announceForAccessibility(CharSequence text) { 5257 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5258 AccessibilityEvent event = AccessibilityEvent.obtain( 5259 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5260 onInitializeAccessibilityEvent(event); 5261 event.getText().add(text); 5262 event.setContentDescription(null); 5263 mParent.requestSendAccessibilityEvent(this, event); 5264 } 5265 } 5266 5267 /** 5268 * @see #sendAccessibilityEvent(int) 5269 * 5270 * Note: Called from the default {@link AccessibilityDelegate}. 5271 * 5272 * @hide 5273 */ 5274 public void sendAccessibilityEventInternal(int eventType) { 5275 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5276 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5277 } 5278 } 5279 5280 /** 5281 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5282 * takes as an argument an empty {@link AccessibilityEvent} and does not 5283 * perform a check whether accessibility is enabled. 5284 * <p> 5285 * If an {@link AccessibilityDelegate} has been specified via calling 5286 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5287 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5288 * is responsible for handling this call. 5289 * </p> 5290 * 5291 * @param event The event to send. 5292 * 5293 * @see #sendAccessibilityEvent(int) 5294 */ 5295 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5296 if (mAccessibilityDelegate != null) { 5297 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5298 } else { 5299 sendAccessibilityEventUncheckedInternal(event); 5300 } 5301 } 5302 5303 /** 5304 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5305 * 5306 * Note: Called from the default {@link AccessibilityDelegate}. 5307 * 5308 * @hide 5309 */ 5310 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5311 if (!isShown()) { 5312 return; 5313 } 5314 onInitializeAccessibilityEvent(event); 5315 // Only a subset of accessibility events populates text content. 5316 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5317 dispatchPopulateAccessibilityEvent(event); 5318 } 5319 // In the beginning we called #isShown(), so we know that getParent() is not null. 5320 getParent().requestSendAccessibilityEvent(this, event); 5321 } 5322 5323 /** 5324 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5325 * to its children for adding their text content to the event. Note that the 5326 * event text is populated in a separate dispatch path since we add to the 5327 * event not only the text of the source but also the text of all its descendants. 5328 * A typical implementation will call 5329 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5330 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5331 * on each child. Override this method if custom population of the event text 5332 * content is required. 5333 * <p> 5334 * If an {@link AccessibilityDelegate} has been specified via calling 5335 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5336 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5337 * is responsible for handling this call. 5338 * </p> 5339 * <p> 5340 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5341 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5342 * </p> 5343 * 5344 * @param event The event. 5345 * 5346 * @return True if the event population was completed. 5347 */ 5348 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5349 if (mAccessibilityDelegate != null) { 5350 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5351 } else { 5352 return dispatchPopulateAccessibilityEventInternal(event); 5353 } 5354 } 5355 5356 /** 5357 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5358 * 5359 * Note: Called from the default {@link AccessibilityDelegate}. 5360 * 5361 * @hide 5362 */ 5363 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5364 onPopulateAccessibilityEvent(event); 5365 return false; 5366 } 5367 5368 /** 5369 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5370 * giving a chance to this View to populate the accessibility event with its 5371 * text content. While this method is free to modify event 5372 * attributes other than text content, doing so should normally be performed in 5373 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5374 * <p> 5375 * Example: Adding formatted date string to an accessibility event in addition 5376 * to the text added by the super implementation: 5377 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5378 * super.onPopulateAccessibilityEvent(event); 5379 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5380 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5381 * mCurrentDate.getTimeInMillis(), flags); 5382 * event.getText().add(selectedDateUtterance); 5383 * }</pre> 5384 * <p> 5385 * If an {@link AccessibilityDelegate} has been specified via calling 5386 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5387 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5388 * is responsible for handling this call. 5389 * </p> 5390 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5391 * information to the event, in case the default implementation has basic information to add. 5392 * </p> 5393 * 5394 * @param event The accessibility event which to populate. 5395 * 5396 * @see #sendAccessibilityEvent(int) 5397 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5398 */ 5399 @CallSuper 5400 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5401 if (mAccessibilityDelegate != null) { 5402 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5403 } else { 5404 onPopulateAccessibilityEventInternal(event); 5405 } 5406 } 5407 5408 /** 5409 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5410 * 5411 * Note: Called from the default {@link AccessibilityDelegate}. 5412 * 5413 * @hide 5414 */ 5415 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5416 } 5417 5418 /** 5419 * Initializes an {@link AccessibilityEvent} with information about 5420 * this View which is the event source. In other words, the source of 5421 * an accessibility event is the view whose state change triggered firing 5422 * the event. 5423 * <p> 5424 * Example: Setting the password property of an event in addition 5425 * to properties set by the super implementation: 5426 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5427 * super.onInitializeAccessibilityEvent(event); 5428 * event.setPassword(true); 5429 * }</pre> 5430 * <p> 5431 * If an {@link AccessibilityDelegate} has been specified via calling 5432 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5433 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5434 * is responsible for handling this call. 5435 * </p> 5436 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5437 * information to the event, in case the default implementation has basic information to add. 5438 * </p> 5439 * @param event The event to initialize. 5440 * 5441 * @see #sendAccessibilityEvent(int) 5442 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5443 */ 5444 @CallSuper 5445 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5446 if (mAccessibilityDelegate != null) { 5447 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5448 } else { 5449 onInitializeAccessibilityEventInternal(event); 5450 } 5451 } 5452 5453 /** 5454 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5455 * 5456 * Note: Called from the default {@link AccessibilityDelegate}. 5457 * 5458 * @hide 5459 */ 5460 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5461 event.setSource(this); 5462 event.setClassName(getAccessibilityClassName()); 5463 event.setPackageName(getContext().getPackageName()); 5464 event.setEnabled(isEnabled()); 5465 event.setContentDescription(mContentDescription); 5466 5467 switch (event.getEventType()) { 5468 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5469 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5470 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5471 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5472 event.setItemCount(focusablesTempList.size()); 5473 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5474 if (mAttachInfo != null) { 5475 focusablesTempList.clear(); 5476 } 5477 } break; 5478 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5479 CharSequence text = getIterableTextForAccessibility(); 5480 if (text != null && text.length() > 0) { 5481 event.setFromIndex(getAccessibilitySelectionStart()); 5482 event.setToIndex(getAccessibilitySelectionEnd()); 5483 event.setItemCount(text.length()); 5484 } 5485 } break; 5486 } 5487 } 5488 5489 /** 5490 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5491 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5492 * This method is responsible for obtaining an accessibility node info from a 5493 * pool of reusable instances and calling 5494 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5495 * initialize the former. 5496 * <p> 5497 * Note: The client is responsible for recycling the obtained instance by calling 5498 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5499 * </p> 5500 * 5501 * @return A populated {@link AccessibilityNodeInfo}. 5502 * 5503 * @see AccessibilityNodeInfo 5504 */ 5505 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5506 if (mAccessibilityDelegate != null) { 5507 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5508 } else { 5509 return createAccessibilityNodeInfoInternal(); 5510 } 5511 } 5512 5513 /** 5514 * @see #createAccessibilityNodeInfo() 5515 * 5516 * @hide 5517 */ 5518 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5519 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5520 if (provider != null) { 5521 return provider.createAccessibilityNodeInfo(View.NO_ID); 5522 } else { 5523 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5524 onInitializeAccessibilityNodeInfo(info); 5525 return info; 5526 } 5527 } 5528 5529 /** 5530 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5531 * The base implementation sets: 5532 * <ul> 5533 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5534 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5535 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5536 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5537 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5538 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5539 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5540 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5541 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5542 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5543 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5544 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5545 * </ul> 5546 * <p> 5547 * Subclasses should override this method, call the super implementation, 5548 * and set additional attributes. 5549 * </p> 5550 * <p> 5551 * If an {@link AccessibilityDelegate} has been specified via calling 5552 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5553 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5554 * is responsible for handling this call. 5555 * </p> 5556 * 5557 * @param info The instance to initialize. 5558 */ 5559 @CallSuper 5560 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5561 if (mAccessibilityDelegate != null) { 5562 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5563 } else { 5564 onInitializeAccessibilityNodeInfoInternal(info); 5565 } 5566 } 5567 5568 /** 5569 * Gets the location of this view in screen coordinates. 5570 * 5571 * @param outRect The output location 5572 * @hide 5573 */ 5574 public void getBoundsOnScreen(Rect outRect) { 5575 getBoundsOnScreen(outRect, false); 5576 } 5577 5578 /** 5579 * Gets the location of this view in screen coordinates. 5580 * 5581 * @param outRect The output location 5582 * @param clipToParent Whether to clip child bounds to the parent ones. 5583 * @hide 5584 */ 5585 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 5586 if (mAttachInfo == null) { 5587 return; 5588 } 5589 5590 RectF position = mAttachInfo.mTmpTransformRect; 5591 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5592 5593 if (!hasIdentityMatrix()) { 5594 getMatrix().mapRect(position); 5595 } 5596 5597 position.offset(mLeft, mTop); 5598 5599 ViewParent parent = mParent; 5600 while (parent instanceof View) { 5601 View parentView = (View) parent; 5602 5603 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5604 5605 if (clipToParent) { 5606 position.left = Math.max(position.left, 0); 5607 position.top = Math.max(position.top, 0); 5608 position.right = Math.min(position.right, parentView.getWidth()); 5609 position.bottom = Math.min(position.bottom, parentView.getHeight()); 5610 } 5611 5612 if (!parentView.hasIdentityMatrix()) { 5613 parentView.getMatrix().mapRect(position); 5614 } 5615 5616 position.offset(parentView.mLeft, parentView.mTop); 5617 5618 parent = parentView.mParent; 5619 } 5620 5621 if (parent instanceof ViewRootImpl) { 5622 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5623 position.offset(0, -viewRootImpl.mCurScrollY); 5624 } 5625 5626 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5627 5628 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5629 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5630 } 5631 5632 /** 5633 * Return the class name of this object to be used for accessibility purposes. 5634 * Subclasses should only override this if they are implementing something that 5635 * should be seen as a completely new class of view when used by accessibility, 5636 * unrelated to the class it is deriving from. This is used to fill in 5637 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 5638 */ 5639 public CharSequence getAccessibilityClassName() { 5640 return View.class.getName(); 5641 } 5642 5643 /** 5644 * Called when assist structure is being retrieved from a view as part of 5645 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 5646 * @param structure Additional standard structured view structure to supply. 5647 * @param extras Non-standard extensions. 5648 */ 5649 public void onProvideAssistStructure(ViewAssistStructure structure, Bundle extras) { 5650 } 5651 5652 /** 5653 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5654 * 5655 * Note: Called from the default {@link AccessibilityDelegate}. 5656 * 5657 * @hide 5658 */ 5659 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5660 Rect bounds = mAttachInfo.mTmpInvalRect; 5661 5662 getDrawingRect(bounds); 5663 info.setBoundsInParent(bounds); 5664 5665 getBoundsOnScreen(bounds, true); 5666 info.setBoundsInScreen(bounds); 5667 5668 ViewParent parent = getParentForAccessibility(); 5669 if (parent instanceof View) { 5670 info.setParent((View) parent); 5671 } 5672 5673 if (mID != View.NO_ID) { 5674 View rootView = getRootView(); 5675 if (rootView == null) { 5676 rootView = this; 5677 } 5678 5679 View label = rootView.findLabelForView(this, mID); 5680 if (label != null) { 5681 info.setLabeledBy(label); 5682 } 5683 5684 if ((mAttachInfo.mAccessibilityFetchFlags 5685 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5686 && Resources.resourceHasPackage(mID)) { 5687 try { 5688 String viewId = getResources().getResourceName(mID); 5689 info.setViewIdResourceName(viewId); 5690 } catch (Resources.NotFoundException nfe) { 5691 /* ignore */ 5692 } 5693 } 5694 } 5695 5696 if (mLabelForId != View.NO_ID) { 5697 View rootView = getRootView(); 5698 if (rootView == null) { 5699 rootView = this; 5700 } 5701 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5702 if (labeled != null) { 5703 info.setLabelFor(labeled); 5704 } 5705 } 5706 5707 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 5708 View rootView = getRootView(); 5709 if (rootView == null) { 5710 rootView = this; 5711 } 5712 View next = rootView.findViewInsideOutShouldExist(this, 5713 mAccessibilityTraversalBeforeId); 5714 if (next != null) { 5715 info.setTraversalBefore(next); 5716 } 5717 } 5718 5719 if (mAccessibilityTraversalAfterId != View.NO_ID) { 5720 View rootView = getRootView(); 5721 if (rootView == null) { 5722 rootView = this; 5723 } 5724 View next = rootView.findViewInsideOutShouldExist(this, 5725 mAccessibilityTraversalAfterId); 5726 if (next != null) { 5727 info.setTraversalAfter(next); 5728 } 5729 } 5730 5731 info.setVisibleToUser(isVisibleToUser()); 5732 5733 info.setPackageName(mContext.getPackageName()); 5734 info.setClassName(getAccessibilityClassName()); 5735 info.setContentDescription(getContentDescription()); 5736 5737 info.setEnabled(isEnabled()); 5738 info.setClickable(isClickable()); 5739 info.setFocusable(isFocusable()); 5740 info.setFocused(isFocused()); 5741 info.setAccessibilityFocused(isAccessibilityFocused()); 5742 info.setSelected(isSelected()); 5743 info.setLongClickable(isLongClickable()); 5744 info.setLiveRegion(getAccessibilityLiveRegion()); 5745 5746 // TODO: These make sense only if we are in an AdapterView but all 5747 // views can be selected. Maybe from accessibility perspective 5748 // we should report as selectable view in an AdapterView. 5749 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5750 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5751 5752 if (isFocusable()) { 5753 if (isFocused()) { 5754 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5755 } else { 5756 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5757 } 5758 } 5759 5760 if (!isAccessibilityFocused()) { 5761 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5762 } else { 5763 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5764 } 5765 5766 if (isClickable() && isEnabled()) { 5767 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5768 } 5769 5770 if (isLongClickable() && isEnabled()) { 5771 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5772 } 5773 5774 CharSequence text = getIterableTextForAccessibility(); 5775 if (text != null && text.length() > 0) { 5776 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5777 5778 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5779 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5780 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5781 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5782 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5783 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5784 } 5785 } 5786 5787 private View findLabelForView(View view, int labeledId) { 5788 if (mMatchLabelForPredicate == null) { 5789 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5790 } 5791 mMatchLabelForPredicate.mLabeledId = labeledId; 5792 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5793 } 5794 5795 /** 5796 * Computes whether this view is visible to the user. Such a view is 5797 * attached, visible, all its predecessors are visible, it is not clipped 5798 * entirely by its predecessors, and has an alpha greater than zero. 5799 * 5800 * @return Whether the view is visible on the screen. 5801 * 5802 * @hide 5803 */ 5804 protected boolean isVisibleToUser() { 5805 return isVisibleToUser(null); 5806 } 5807 5808 /** 5809 * Computes whether the given portion of this view is visible to the user. 5810 * Such a view is attached, visible, all its predecessors are visible, 5811 * has an alpha greater than zero, and the specified portion is not 5812 * clipped entirely by its predecessors. 5813 * 5814 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5815 * <code>null</code>, and the entire view will be tested in this case. 5816 * When <code>true</code> is returned by the function, the actual visible 5817 * region will be stored in this parameter; that is, if boundInView is fully 5818 * contained within the view, no modification will be made, otherwise regions 5819 * outside of the visible area of the view will be clipped. 5820 * 5821 * @return Whether the specified portion of the view is visible on the screen. 5822 * 5823 * @hide 5824 */ 5825 protected boolean isVisibleToUser(Rect boundInView) { 5826 if (mAttachInfo != null) { 5827 // Attached to invisible window means this view is not visible. 5828 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5829 return false; 5830 } 5831 // An invisible predecessor or one with alpha zero means 5832 // that this view is not visible to the user. 5833 Object current = this; 5834 while (current instanceof View) { 5835 View view = (View) current; 5836 // We have attach info so this view is attached and there is no 5837 // need to check whether we reach to ViewRootImpl on the way up. 5838 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5839 view.getVisibility() != VISIBLE) { 5840 return false; 5841 } 5842 current = view.mParent; 5843 } 5844 // Check if the view is entirely covered by its predecessors. 5845 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5846 Point offset = mAttachInfo.mPoint; 5847 if (!getGlobalVisibleRect(visibleRect, offset)) { 5848 return false; 5849 } 5850 // Check if the visible portion intersects the rectangle of interest. 5851 if (boundInView != null) { 5852 visibleRect.offset(-offset.x, -offset.y); 5853 return boundInView.intersect(visibleRect); 5854 } 5855 return true; 5856 } 5857 return false; 5858 } 5859 5860 /** 5861 * Returns the delegate for implementing accessibility support via 5862 * composition. For more details see {@link AccessibilityDelegate}. 5863 * 5864 * @return The delegate, or null if none set. 5865 * 5866 * @hide 5867 */ 5868 public AccessibilityDelegate getAccessibilityDelegate() { 5869 return mAccessibilityDelegate; 5870 } 5871 5872 /** 5873 * Sets a delegate for implementing accessibility support via composition as 5874 * opposed to inheritance. The delegate's primary use is for implementing 5875 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5876 * 5877 * @param delegate The delegate instance. 5878 * 5879 * @see AccessibilityDelegate 5880 */ 5881 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 5882 mAccessibilityDelegate = delegate; 5883 } 5884 5885 /** 5886 * Gets the provider for managing a virtual view hierarchy rooted at this View 5887 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5888 * that explore the window content. 5889 * <p> 5890 * If this method returns an instance, this instance is responsible for managing 5891 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5892 * View including the one representing the View itself. Similarly the returned 5893 * instance is responsible for performing accessibility actions on any virtual 5894 * view or the root view itself. 5895 * </p> 5896 * <p> 5897 * If an {@link AccessibilityDelegate} has been specified via calling 5898 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5899 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5900 * is responsible for handling this call. 5901 * </p> 5902 * 5903 * @return The provider. 5904 * 5905 * @see AccessibilityNodeProvider 5906 */ 5907 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5908 if (mAccessibilityDelegate != null) { 5909 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5910 } else { 5911 return null; 5912 } 5913 } 5914 5915 /** 5916 * Gets the unique identifier of this view on the screen for accessibility purposes. 5917 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5918 * 5919 * @return The view accessibility id. 5920 * 5921 * @hide 5922 */ 5923 public int getAccessibilityViewId() { 5924 if (mAccessibilityViewId == NO_ID) { 5925 mAccessibilityViewId = sNextAccessibilityViewId++; 5926 } 5927 return mAccessibilityViewId; 5928 } 5929 5930 /** 5931 * Gets the unique identifier of the window in which this View reseides. 5932 * 5933 * @return The window accessibility id. 5934 * 5935 * @hide 5936 */ 5937 public int getAccessibilityWindowId() { 5938 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5939 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5940 } 5941 5942 /** 5943 * Gets the {@link View} description. It briefly describes the view and is 5944 * primarily used for accessibility support. Set this property to enable 5945 * better accessibility support for your application. This is especially 5946 * true for views that do not have textual representation (For example, 5947 * ImageButton). 5948 * 5949 * @return The content description. 5950 * 5951 * @attr ref android.R.styleable#View_contentDescription 5952 */ 5953 @ViewDebug.ExportedProperty(category = "accessibility") 5954 public CharSequence getContentDescription() { 5955 return mContentDescription; 5956 } 5957 5958 /** 5959 * Sets the {@link View} description. It briefly describes the view and is 5960 * primarily used for accessibility support. Set this property to enable 5961 * better accessibility support for your application. This is especially 5962 * true for views that do not have textual representation (For example, 5963 * ImageButton). 5964 * 5965 * @param contentDescription The content description. 5966 * 5967 * @attr ref android.R.styleable#View_contentDescription 5968 */ 5969 @RemotableViewMethod 5970 public void setContentDescription(CharSequence contentDescription) { 5971 if (mContentDescription == null) { 5972 if (contentDescription == null) { 5973 return; 5974 } 5975 } else if (mContentDescription.equals(contentDescription)) { 5976 return; 5977 } 5978 mContentDescription = contentDescription; 5979 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5980 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5981 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5982 notifySubtreeAccessibilityStateChangedIfNeeded(); 5983 } else { 5984 notifyViewAccessibilityStateChangedIfNeeded( 5985 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5986 } 5987 } 5988 5989 /** 5990 * Sets the id of a view before which this one is visited in accessibility traversal. 5991 * A screen-reader must visit the content of this view before the content of the one 5992 * it precedes. For example, if view B is set to be before view A, then a screen-reader 5993 * will traverse the entire content of B before traversing the entire content of A, 5994 * regardles of what traversal strategy it is using. 5995 * <p> 5996 * Views that do not have specified before/after relationships are traversed in order 5997 * determined by the screen-reader. 5998 * </p> 5999 * <p> 6000 * Setting that this view is before a view that is not important for accessibility 6001 * or if this view is not important for accessibility will have no effect as the 6002 * screen-reader is not aware of unimportant views. 6003 * </p> 6004 * 6005 * @param beforeId The id of a view this one precedes in accessibility traversal. 6006 * 6007 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6008 * 6009 * @see #setImportantForAccessibility(int) 6010 */ 6011 @RemotableViewMethod 6012 public void setAccessibilityTraversalBefore(int beforeId) { 6013 if (mAccessibilityTraversalBeforeId == beforeId) { 6014 return; 6015 } 6016 mAccessibilityTraversalBeforeId = beforeId; 6017 notifyViewAccessibilityStateChangedIfNeeded( 6018 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6019 } 6020 6021 /** 6022 * Gets the id of a view before which this one is visited in accessibility traversal. 6023 * 6024 * @return The id of a view this one precedes in accessibility traversal if 6025 * specified, otherwise {@link #NO_ID}. 6026 * 6027 * @see #setAccessibilityTraversalBefore(int) 6028 */ 6029 public int getAccessibilityTraversalBefore() { 6030 return mAccessibilityTraversalBeforeId; 6031 } 6032 6033 /** 6034 * Sets the id of a view after which this one is visited in accessibility traversal. 6035 * A screen-reader must visit the content of the other view before the content of this 6036 * one. For example, if view B is set to be after view A, then a screen-reader 6037 * will traverse the entire content of A before traversing the entire content of B, 6038 * regardles of what traversal strategy it is using. 6039 * <p> 6040 * Views that do not have specified before/after relationships are traversed in order 6041 * determined by the screen-reader. 6042 * </p> 6043 * <p> 6044 * Setting that this view is after a view that is not important for accessibility 6045 * or if this view is not important for accessibility will have no effect as the 6046 * screen-reader is not aware of unimportant views. 6047 * </p> 6048 * 6049 * @param afterId The id of a view this one succedees in accessibility traversal. 6050 * 6051 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6052 * 6053 * @see #setImportantForAccessibility(int) 6054 */ 6055 @RemotableViewMethod 6056 public void setAccessibilityTraversalAfter(int afterId) { 6057 if (mAccessibilityTraversalAfterId == afterId) { 6058 return; 6059 } 6060 mAccessibilityTraversalAfterId = afterId; 6061 notifyViewAccessibilityStateChangedIfNeeded( 6062 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6063 } 6064 6065 /** 6066 * Gets the id of a view after which this one is visited in accessibility traversal. 6067 * 6068 * @return The id of a view this one succeedes in accessibility traversal if 6069 * specified, otherwise {@link #NO_ID}. 6070 * 6071 * @see #setAccessibilityTraversalAfter(int) 6072 */ 6073 public int getAccessibilityTraversalAfter() { 6074 return mAccessibilityTraversalAfterId; 6075 } 6076 6077 /** 6078 * Gets the id of a view for which this view serves as a label for 6079 * accessibility purposes. 6080 * 6081 * @return The labeled view id. 6082 */ 6083 @ViewDebug.ExportedProperty(category = "accessibility") 6084 public int getLabelFor() { 6085 return mLabelForId; 6086 } 6087 6088 /** 6089 * Sets the id of a view for which this view serves as a label for 6090 * accessibility purposes. 6091 * 6092 * @param id The labeled view id. 6093 */ 6094 @RemotableViewMethod 6095 public void setLabelFor(@IdRes int id) { 6096 if (mLabelForId == id) { 6097 return; 6098 } 6099 mLabelForId = id; 6100 if (mLabelForId != View.NO_ID 6101 && mID == View.NO_ID) { 6102 mID = generateViewId(); 6103 } 6104 notifyViewAccessibilityStateChangedIfNeeded( 6105 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6106 } 6107 6108 /** 6109 * Invoked whenever this view loses focus, either by losing window focus or by losing 6110 * focus within its window. This method can be used to clear any state tied to the 6111 * focus. For instance, if a button is held pressed with the trackball and the window 6112 * loses focus, this method can be used to cancel the press. 6113 * 6114 * Subclasses of View overriding this method should always call super.onFocusLost(). 6115 * 6116 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6117 * @see #onWindowFocusChanged(boolean) 6118 * 6119 * @hide pending API council approval 6120 */ 6121 @CallSuper 6122 protected void onFocusLost() { 6123 resetPressedState(); 6124 } 6125 6126 private void resetPressedState() { 6127 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6128 return; 6129 } 6130 6131 if (isPressed()) { 6132 setPressed(false); 6133 6134 if (!mHasPerformedLongPress) { 6135 removeLongPressCallback(); 6136 } 6137 } 6138 } 6139 6140 /** 6141 * Returns true if this view has focus 6142 * 6143 * @return True if this view has focus, false otherwise. 6144 */ 6145 @ViewDebug.ExportedProperty(category = "focus") 6146 public boolean isFocused() { 6147 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6148 } 6149 6150 /** 6151 * Find the view in the hierarchy rooted at this view that currently has 6152 * focus. 6153 * 6154 * @return The view that currently has focus, or null if no focused view can 6155 * be found. 6156 */ 6157 public View findFocus() { 6158 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6159 } 6160 6161 /** 6162 * Indicates whether this view is one of the set of scrollable containers in 6163 * its window. 6164 * 6165 * @return whether this view is one of the set of scrollable containers in 6166 * its window 6167 * 6168 * @attr ref android.R.styleable#View_isScrollContainer 6169 */ 6170 public boolean isScrollContainer() { 6171 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6172 } 6173 6174 /** 6175 * Change whether this view is one of the set of scrollable containers in 6176 * its window. This will be used to determine whether the window can 6177 * resize or must pan when a soft input area is open -- scrollable 6178 * containers allow the window to use resize mode since the container 6179 * will appropriately shrink. 6180 * 6181 * @attr ref android.R.styleable#View_isScrollContainer 6182 */ 6183 public void setScrollContainer(boolean isScrollContainer) { 6184 if (isScrollContainer) { 6185 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6186 mAttachInfo.mScrollContainers.add(this); 6187 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6188 } 6189 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6190 } else { 6191 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6192 mAttachInfo.mScrollContainers.remove(this); 6193 } 6194 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6195 } 6196 } 6197 6198 /** 6199 * Returns the quality of the drawing cache. 6200 * 6201 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6202 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6203 * 6204 * @see #setDrawingCacheQuality(int) 6205 * @see #setDrawingCacheEnabled(boolean) 6206 * @see #isDrawingCacheEnabled() 6207 * 6208 * @attr ref android.R.styleable#View_drawingCacheQuality 6209 */ 6210 @DrawingCacheQuality 6211 public int getDrawingCacheQuality() { 6212 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6213 } 6214 6215 /** 6216 * Set the drawing cache quality of this view. This value is used only when the 6217 * drawing cache is enabled 6218 * 6219 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6220 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6221 * 6222 * @see #getDrawingCacheQuality() 6223 * @see #setDrawingCacheEnabled(boolean) 6224 * @see #isDrawingCacheEnabled() 6225 * 6226 * @attr ref android.R.styleable#View_drawingCacheQuality 6227 */ 6228 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6229 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6230 } 6231 6232 /** 6233 * Returns whether the screen should remain on, corresponding to the current 6234 * value of {@link #KEEP_SCREEN_ON}. 6235 * 6236 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6237 * 6238 * @see #setKeepScreenOn(boolean) 6239 * 6240 * @attr ref android.R.styleable#View_keepScreenOn 6241 */ 6242 public boolean getKeepScreenOn() { 6243 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6244 } 6245 6246 /** 6247 * Controls whether the screen should remain on, modifying the 6248 * value of {@link #KEEP_SCREEN_ON}. 6249 * 6250 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6251 * 6252 * @see #getKeepScreenOn() 6253 * 6254 * @attr ref android.R.styleable#View_keepScreenOn 6255 */ 6256 public void setKeepScreenOn(boolean keepScreenOn) { 6257 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6258 } 6259 6260 /** 6261 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6262 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6263 * 6264 * @attr ref android.R.styleable#View_nextFocusLeft 6265 */ 6266 public int getNextFocusLeftId() { 6267 return mNextFocusLeftId; 6268 } 6269 6270 /** 6271 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6272 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6273 * decide automatically. 6274 * 6275 * @attr ref android.R.styleable#View_nextFocusLeft 6276 */ 6277 public void setNextFocusLeftId(int nextFocusLeftId) { 6278 mNextFocusLeftId = nextFocusLeftId; 6279 } 6280 6281 /** 6282 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6283 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6284 * 6285 * @attr ref android.R.styleable#View_nextFocusRight 6286 */ 6287 public int getNextFocusRightId() { 6288 return mNextFocusRightId; 6289 } 6290 6291 /** 6292 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6293 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6294 * decide automatically. 6295 * 6296 * @attr ref android.R.styleable#View_nextFocusRight 6297 */ 6298 public void setNextFocusRightId(int nextFocusRightId) { 6299 mNextFocusRightId = nextFocusRightId; 6300 } 6301 6302 /** 6303 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6304 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6305 * 6306 * @attr ref android.R.styleable#View_nextFocusUp 6307 */ 6308 public int getNextFocusUpId() { 6309 return mNextFocusUpId; 6310 } 6311 6312 /** 6313 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6314 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6315 * decide automatically. 6316 * 6317 * @attr ref android.R.styleable#View_nextFocusUp 6318 */ 6319 public void setNextFocusUpId(int nextFocusUpId) { 6320 mNextFocusUpId = nextFocusUpId; 6321 } 6322 6323 /** 6324 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6325 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6326 * 6327 * @attr ref android.R.styleable#View_nextFocusDown 6328 */ 6329 public int getNextFocusDownId() { 6330 return mNextFocusDownId; 6331 } 6332 6333 /** 6334 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6335 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6336 * decide automatically. 6337 * 6338 * @attr ref android.R.styleable#View_nextFocusDown 6339 */ 6340 public void setNextFocusDownId(int nextFocusDownId) { 6341 mNextFocusDownId = nextFocusDownId; 6342 } 6343 6344 /** 6345 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6346 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6347 * 6348 * @attr ref android.R.styleable#View_nextFocusForward 6349 */ 6350 public int getNextFocusForwardId() { 6351 return mNextFocusForwardId; 6352 } 6353 6354 /** 6355 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6356 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6357 * decide automatically. 6358 * 6359 * @attr ref android.R.styleable#View_nextFocusForward 6360 */ 6361 public void setNextFocusForwardId(int nextFocusForwardId) { 6362 mNextFocusForwardId = nextFocusForwardId; 6363 } 6364 6365 /** 6366 * Returns the visibility of this view and all of its ancestors 6367 * 6368 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6369 */ 6370 public boolean isShown() { 6371 View current = this; 6372 //noinspection ConstantConditions 6373 do { 6374 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6375 return false; 6376 } 6377 ViewParent parent = current.mParent; 6378 if (parent == null) { 6379 return false; // We are not attached to the view root 6380 } 6381 if (!(parent instanceof View)) { 6382 return true; 6383 } 6384 current = (View) parent; 6385 } while (current != null); 6386 6387 return false; 6388 } 6389 6390 /** 6391 * Called by the view hierarchy when the content insets for a window have 6392 * changed, to allow it to adjust its content to fit within those windows. 6393 * The content insets tell you the space that the status bar, input method, 6394 * and other system windows infringe on the application's window. 6395 * 6396 * <p>You do not normally need to deal with this function, since the default 6397 * window decoration given to applications takes care of applying it to the 6398 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6399 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6400 * and your content can be placed under those system elements. You can then 6401 * use this method within your view hierarchy if you have parts of your UI 6402 * which you would like to ensure are not being covered. 6403 * 6404 * <p>The default implementation of this method simply applies the content 6405 * insets to the view's padding, consuming that content (modifying the 6406 * insets to be 0), and returning true. This behavior is off by default, but can 6407 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6408 * 6409 * <p>This function's traversal down the hierarchy is depth-first. The same content 6410 * insets object is propagated down the hierarchy, so any changes made to it will 6411 * be seen by all following views (including potentially ones above in 6412 * the hierarchy since this is a depth-first traversal). The first view 6413 * that returns true will abort the entire traversal. 6414 * 6415 * <p>The default implementation works well for a situation where it is 6416 * used with a container that covers the entire window, allowing it to 6417 * apply the appropriate insets to its content on all edges. If you need 6418 * a more complicated layout (such as two different views fitting system 6419 * windows, one on the top of the window, and one on the bottom), 6420 * you can override the method and handle the insets however you would like. 6421 * Note that the insets provided by the framework are always relative to the 6422 * far edges of the window, not accounting for the location of the called view 6423 * within that window. (In fact when this method is called you do not yet know 6424 * where the layout will place the view, as it is done before layout happens.) 6425 * 6426 * <p>Note: unlike many View methods, there is no dispatch phase to this 6427 * call. If you are overriding it in a ViewGroup and want to allow the 6428 * call to continue to your children, you must be sure to call the super 6429 * implementation. 6430 * 6431 * <p>Here is a sample layout that makes use of fitting system windows 6432 * to have controls for a video view placed inside of the window decorations 6433 * that it hides and shows. This can be used with code like the second 6434 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6435 * 6436 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6437 * 6438 * @param insets Current content insets of the window. Prior to 6439 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6440 * the insets or else you and Android will be unhappy. 6441 * 6442 * @return {@code true} if this view applied the insets and it should not 6443 * continue propagating further down the hierarchy, {@code false} otherwise. 6444 * @see #getFitsSystemWindows() 6445 * @see #setFitsSystemWindows(boolean) 6446 * @see #setSystemUiVisibility(int) 6447 * 6448 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6449 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6450 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6451 * to implement handling their own insets. 6452 */ 6453 protected boolean fitSystemWindows(Rect insets) { 6454 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6455 if (insets == null) { 6456 // Null insets by definition have already been consumed. 6457 // This call cannot apply insets since there are none to apply, 6458 // so return false. 6459 return false; 6460 } 6461 // If we're not in the process of dispatching the newer apply insets call, 6462 // that means we're not in the compatibility path. Dispatch into the newer 6463 // apply insets path and take things from there. 6464 try { 6465 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6466 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6467 } finally { 6468 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6469 } 6470 } else { 6471 // We're being called from the newer apply insets path. 6472 // Perform the standard fallback behavior. 6473 return fitSystemWindowsInt(insets); 6474 } 6475 } 6476 6477 private boolean fitSystemWindowsInt(Rect insets) { 6478 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6479 mUserPaddingStart = UNDEFINED_PADDING; 6480 mUserPaddingEnd = UNDEFINED_PADDING; 6481 Rect localInsets = sThreadLocal.get(); 6482 if (localInsets == null) { 6483 localInsets = new Rect(); 6484 sThreadLocal.set(localInsets); 6485 } 6486 boolean res = computeFitSystemWindows(insets, localInsets); 6487 mUserPaddingLeftInitial = localInsets.left; 6488 mUserPaddingRightInitial = localInsets.right; 6489 internalSetPadding(localInsets.left, localInsets.top, 6490 localInsets.right, localInsets.bottom); 6491 return res; 6492 } 6493 return false; 6494 } 6495 6496 /** 6497 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6498 * 6499 * <p>This method should be overridden by views that wish to apply a policy different from or 6500 * in addition to the default behavior. Clients that wish to force a view subtree 6501 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6502 * 6503 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6504 * it will be called during dispatch instead of this method. The listener may optionally 6505 * call this method from its own implementation if it wishes to apply the view's default 6506 * insets policy in addition to its own.</p> 6507 * 6508 * <p>Implementations of this method should either return the insets parameter unchanged 6509 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6510 * that this view applied itself. This allows new inset types added in future platform 6511 * versions to pass through existing implementations unchanged without being erroneously 6512 * consumed.</p> 6513 * 6514 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6515 * property is set then the view will consume the system window insets and apply them 6516 * as padding for the view.</p> 6517 * 6518 * @param insets Insets to apply 6519 * @return The supplied insets with any applied insets consumed 6520 */ 6521 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6522 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6523 // We weren't called from within a direct call to fitSystemWindows, 6524 // call into it as a fallback in case we're in a class that overrides it 6525 // and has logic to perform. 6526 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6527 return insets.consumeSystemWindowInsets(); 6528 } 6529 } else { 6530 // We were called from within a direct call to fitSystemWindows. 6531 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6532 return insets.consumeSystemWindowInsets(); 6533 } 6534 } 6535 return insets; 6536 } 6537 6538 /** 6539 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6540 * window insets to this view. The listener's 6541 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6542 * method will be called instead of the view's 6543 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6544 * 6545 * @param listener Listener to set 6546 * 6547 * @see #onApplyWindowInsets(WindowInsets) 6548 */ 6549 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6550 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6551 } 6552 6553 /** 6554 * Request to apply the given window insets to this view or another view in its subtree. 6555 * 6556 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6557 * obscured by window decorations or overlays. This can include the status and navigation bars, 6558 * action bars, input methods and more. New inset categories may be added in the future. 6559 * The method returns the insets provided minus any that were applied by this view or its 6560 * children.</p> 6561 * 6562 * <p>Clients wishing to provide custom behavior should override the 6563 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6564 * {@link OnApplyWindowInsetsListener} via the 6565 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6566 * method.</p> 6567 * 6568 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6569 * </p> 6570 * 6571 * @param insets Insets to apply 6572 * @return The provided insets minus the insets that were consumed 6573 */ 6574 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6575 try { 6576 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6577 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6578 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6579 } else { 6580 return onApplyWindowInsets(insets); 6581 } 6582 } finally { 6583 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6584 } 6585 } 6586 6587 /** 6588 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 6589 * only available if the view is attached. 6590 * 6591 * @return WindowInsets from the top of the view hierarchy or null if View is detached 6592 */ 6593 public WindowInsets getRootWindowInsets() { 6594 if (mAttachInfo != null) { 6595 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 6596 } 6597 return null; 6598 } 6599 6600 /** 6601 * @hide Compute the insets that should be consumed by this view and the ones 6602 * that should propagate to those under it. 6603 */ 6604 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6605 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6606 || mAttachInfo == null 6607 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6608 && !mAttachInfo.mOverscanRequested)) { 6609 outLocalInsets.set(inoutInsets); 6610 inoutInsets.set(0, 0, 0, 0); 6611 return true; 6612 } else { 6613 // The application wants to take care of fitting system window for 6614 // the content... however we still need to take care of any overscan here. 6615 final Rect overscan = mAttachInfo.mOverscanInsets; 6616 outLocalInsets.set(overscan); 6617 inoutInsets.left -= overscan.left; 6618 inoutInsets.top -= overscan.top; 6619 inoutInsets.right -= overscan.right; 6620 inoutInsets.bottom -= overscan.bottom; 6621 return false; 6622 } 6623 } 6624 6625 /** 6626 * Compute insets that should be consumed by this view and the ones that should propagate 6627 * to those under it. 6628 * 6629 * @param in Insets currently being processed by this View, likely received as a parameter 6630 * to {@link #onApplyWindowInsets(WindowInsets)}. 6631 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6632 * by this view 6633 * @return Insets that should be passed along to views under this one 6634 */ 6635 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6636 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6637 || mAttachInfo == null 6638 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6639 outLocalInsets.set(in.getSystemWindowInsets()); 6640 return in.consumeSystemWindowInsets(); 6641 } else { 6642 outLocalInsets.set(0, 0, 0, 0); 6643 return in; 6644 } 6645 } 6646 6647 /** 6648 * Sets whether or not this view should account for system screen decorations 6649 * such as the status bar and inset its content; that is, controlling whether 6650 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6651 * executed. See that method for more details. 6652 * 6653 * <p>Note that if you are providing your own implementation of 6654 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6655 * flag to true -- your implementation will be overriding the default 6656 * implementation that checks this flag. 6657 * 6658 * @param fitSystemWindows If true, then the default implementation of 6659 * {@link #fitSystemWindows(Rect)} will be executed. 6660 * 6661 * @attr ref android.R.styleable#View_fitsSystemWindows 6662 * @see #getFitsSystemWindows() 6663 * @see #fitSystemWindows(Rect) 6664 * @see #setSystemUiVisibility(int) 6665 */ 6666 public void setFitsSystemWindows(boolean fitSystemWindows) { 6667 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6668 } 6669 6670 /** 6671 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6672 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6673 * will be executed. 6674 * 6675 * @return {@code true} if the default implementation of 6676 * {@link #fitSystemWindows(Rect)} will be executed. 6677 * 6678 * @attr ref android.R.styleable#View_fitsSystemWindows 6679 * @see #setFitsSystemWindows(boolean) 6680 * @see #fitSystemWindows(Rect) 6681 * @see #setSystemUiVisibility(int) 6682 */ 6683 @ViewDebug.ExportedProperty 6684 public boolean getFitsSystemWindows() { 6685 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6686 } 6687 6688 /** @hide */ 6689 public boolean fitsSystemWindows() { 6690 return getFitsSystemWindows(); 6691 } 6692 6693 /** 6694 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6695 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6696 */ 6697 public void requestFitSystemWindows() { 6698 if (mParent != null) { 6699 mParent.requestFitSystemWindows(); 6700 } 6701 } 6702 6703 /** 6704 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6705 */ 6706 public void requestApplyInsets() { 6707 requestFitSystemWindows(); 6708 } 6709 6710 /** 6711 * For use by PhoneWindow to make its own system window fitting optional. 6712 * @hide 6713 */ 6714 public void makeOptionalFitsSystemWindows() { 6715 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6716 } 6717 6718 /** 6719 * Returns the visibility status for this view. 6720 * 6721 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6722 * @attr ref android.R.styleable#View_visibility 6723 */ 6724 @ViewDebug.ExportedProperty(mapping = { 6725 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6726 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6727 @ViewDebug.IntToString(from = GONE, to = "GONE") 6728 }) 6729 @Visibility 6730 public int getVisibility() { 6731 return mViewFlags & VISIBILITY_MASK; 6732 } 6733 6734 /** 6735 * Set the enabled state of this view. 6736 * 6737 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6738 * @attr ref android.R.styleable#View_visibility 6739 */ 6740 @RemotableViewMethod 6741 public void setVisibility(@Visibility int visibility) { 6742 setFlags(visibility, VISIBILITY_MASK); 6743 } 6744 6745 /** 6746 * Returns the enabled status for this view. The interpretation of the 6747 * enabled state varies by subclass. 6748 * 6749 * @return True if this view is enabled, false otherwise. 6750 */ 6751 @ViewDebug.ExportedProperty 6752 public boolean isEnabled() { 6753 return (mViewFlags & ENABLED_MASK) == ENABLED; 6754 } 6755 6756 /** 6757 * Set the enabled state of this view. The interpretation of the enabled 6758 * state varies by subclass. 6759 * 6760 * @param enabled True if this view is enabled, false otherwise. 6761 */ 6762 @RemotableViewMethod 6763 public void setEnabled(boolean enabled) { 6764 if (enabled == isEnabled()) return; 6765 6766 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6767 6768 /* 6769 * The View most likely has to change its appearance, so refresh 6770 * the drawable state. 6771 */ 6772 refreshDrawableState(); 6773 6774 // Invalidate too, since the default behavior for views is to be 6775 // be drawn at 50% alpha rather than to change the drawable. 6776 invalidate(true); 6777 6778 if (!enabled) { 6779 cancelPendingInputEvents(); 6780 } 6781 } 6782 6783 /** 6784 * Set whether this view can receive the focus. 6785 * 6786 * Setting this to false will also ensure that this view is not focusable 6787 * in touch mode. 6788 * 6789 * @param focusable If true, this view can receive the focus. 6790 * 6791 * @see #setFocusableInTouchMode(boolean) 6792 * @attr ref android.R.styleable#View_focusable 6793 */ 6794 public void setFocusable(boolean focusable) { 6795 if (!focusable) { 6796 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6797 } 6798 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6799 } 6800 6801 /** 6802 * Set whether this view can receive focus while in touch mode. 6803 * 6804 * Setting this to true will also ensure that this view is focusable. 6805 * 6806 * @param focusableInTouchMode If true, this view can receive the focus while 6807 * in touch mode. 6808 * 6809 * @see #setFocusable(boolean) 6810 * @attr ref android.R.styleable#View_focusableInTouchMode 6811 */ 6812 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6813 // Focusable in touch mode should always be set before the focusable flag 6814 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6815 // which, in touch mode, will not successfully request focus on this view 6816 // because the focusable in touch mode flag is not set 6817 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6818 if (focusableInTouchMode) { 6819 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6820 } 6821 } 6822 6823 /** 6824 * Set whether this view should have sound effects enabled for events such as 6825 * clicking and touching. 6826 * 6827 * <p>You may wish to disable sound effects for a view if you already play sounds, 6828 * for instance, a dial key that plays dtmf tones. 6829 * 6830 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6831 * @see #isSoundEffectsEnabled() 6832 * @see #playSoundEffect(int) 6833 * @attr ref android.R.styleable#View_soundEffectsEnabled 6834 */ 6835 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6836 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6837 } 6838 6839 /** 6840 * @return whether this view should have sound effects enabled for events such as 6841 * clicking and touching. 6842 * 6843 * @see #setSoundEffectsEnabled(boolean) 6844 * @see #playSoundEffect(int) 6845 * @attr ref android.R.styleable#View_soundEffectsEnabled 6846 */ 6847 @ViewDebug.ExportedProperty 6848 public boolean isSoundEffectsEnabled() { 6849 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6850 } 6851 6852 /** 6853 * Set whether this view should have haptic feedback for events such as 6854 * long presses. 6855 * 6856 * <p>You may wish to disable haptic feedback if your view already controls 6857 * its own haptic feedback. 6858 * 6859 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6860 * @see #isHapticFeedbackEnabled() 6861 * @see #performHapticFeedback(int) 6862 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6863 */ 6864 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6865 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6866 } 6867 6868 /** 6869 * @return whether this view should have haptic feedback enabled for events 6870 * long presses. 6871 * 6872 * @see #setHapticFeedbackEnabled(boolean) 6873 * @see #performHapticFeedback(int) 6874 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6875 */ 6876 @ViewDebug.ExportedProperty 6877 public boolean isHapticFeedbackEnabled() { 6878 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6879 } 6880 6881 /** 6882 * Returns the layout direction for this view. 6883 * 6884 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6885 * {@link #LAYOUT_DIRECTION_RTL}, 6886 * {@link #LAYOUT_DIRECTION_INHERIT} or 6887 * {@link #LAYOUT_DIRECTION_LOCALE}. 6888 * 6889 * @attr ref android.R.styleable#View_layoutDirection 6890 * 6891 * @hide 6892 */ 6893 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6894 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6895 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6896 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6897 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6898 }) 6899 @LayoutDir 6900 public int getRawLayoutDirection() { 6901 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6902 } 6903 6904 /** 6905 * Set the layout direction for this view. This will propagate a reset of layout direction 6906 * resolution to the view's children and resolve layout direction for this view. 6907 * 6908 * @param layoutDirection the layout direction to set. Should be one of: 6909 * 6910 * {@link #LAYOUT_DIRECTION_LTR}, 6911 * {@link #LAYOUT_DIRECTION_RTL}, 6912 * {@link #LAYOUT_DIRECTION_INHERIT}, 6913 * {@link #LAYOUT_DIRECTION_LOCALE}. 6914 * 6915 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6916 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6917 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6918 * 6919 * @attr ref android.R.styleable#View_layoutDirection 6920 */ 6921 @RemotableViewMethod 6922 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6923 if (getRawLayoutDirection() != layoutDirection) { 6924 // Reset the current layout direction and the resolved one 6925 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6926 resetRtlProperties(); 6927 // Set the new layout direction (filtered) 6928 mPrivateFlags2 |= 6929 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6930 // We need to resolve all RTL properties as they all depend on layout direction 6931 resolveRtlPropertiesIfNeeded(); 6932 requestLayout(); 6933 invalidate(true); 6934 } 6935 } 6936 6937 /** 6938 * Returns the resolved layout direction for this view. 6939 * 6940 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6941 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6942 * 6943 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6944 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6945 * 6946 * @attr ref android.R.styleable#View_layoutDirection 6947 */ 6948 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6949 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6950 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6951 }) 6952 @ResolvedLayoutDir 6953 public int getLayoutDirection() { 6954 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6955 if (targetSdkVersion < JELLY_BEAN_MR1) { 6956 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6957 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6958 } 6959 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6960 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6961 } 6962 6963 /** 6964 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6965 * layout attribute and/or the inherited value from the parent 6966 * 6967 * @return true if the layout is right-to-left. 6968 * 6969 * @hide 6970 */ 6971 @ViewDebug.ExportedProperty(category = "layout") 6972 public boolean isLayoutRtl() { 6973 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6974 } 6975 6976 /** 6977 * Indicates whether the view is currently tracking transient state that the 6978 * app should not need to concern itself with saving and restoring, but that 6979 * the framework should take special note to preserve when possible. 6980 * 6981 * <p>A view with transient state cannot be trivially rebound from an external 6982 * data source, such as an adapter binding item views in a list. This may be 6983 * because the view is performing an animation, tracking user selection 6984 * of content, or similar.</p> 6985 * 6986 * @return true if the view has transient state 6987 */ 6988 @ViewDebug.ExportedProperty(category = "layout") 6989 public boolean hasTransientState() { 6990 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6991 } 6992 6993 /** 6994 * Set whether this view is currently tracking transient state that the 6995 * framework should attempt to preserve when possible. This flag is reference counted, 6996 * so every call to setHasTransientState(true) should be paired with a later call 6997 * to setHasTransientState(false). 6998 * 6999 * <p>A view with transient state cannot be trivially rebound from an external 7000 * data source, such as an adapter binding item views in a list. This may be 7001 * because the view is performing an animation, tracking user selection 7002 * of content, or similar.</p> 7003 * 7004 * @param hasTransientState true if this view has transient state 7005 */ 7006 public void setHasTransientState(boolean hasTransientState) { 7007 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7008 mTransientStateCount - 1; 7009 if (mTransientStateCount < 0) { 7010 mTransientStateCount = 0; 7011 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7012 "unmatched pair of setHasTransientState calls"); 7013 } else if ((hasTransientState && mTransientStateCount == 1) || 7014 (!hasTransientState && mTransientStateCount == 0)) { 7015 // update flag if we've just incremented up from 0 or decremented down to 0 7016 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7017 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7018 if (mParent != null) { 7019 try { 7020 mParent.childHasTransientStateChanged(this, hasTransientState); 7021 } catch (AbstractMethodError e) { 7022 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7023 " does not fully implement ViewParent", e); 7024 } 7025 } 7026 } 7027 } 7028 7029 /** 7030 * Returns true if this view is currently attached to a window. 7031 */ 7032 public boolean isAttachedToWindow() { 7033 return mAttachInfo != null; 7034 } 7035 7036 /** 7037 * Returns true if this view has been through at least one layout since it 7038 * was last attached to or detached from a window. 7039 */ 7040 public boolean isLaidOut() { 7041 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7042 } 7043 7044 /** 7045 * If this view doesn't do any drawing on its own, set this flag to 7046 * allow further optimizations. By default, this flag is not set on 7047 * View, but could be set on some View subclasses such as ViewGroup. 7048 * 7049 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7050 * you should clear this flag. 7051 * 7052 * @param willNotDraw whether or not this View draw on its own 7053 */ 7054 public void setWillNotDraw(boolean willNotDraw) { 7055 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7056 } 7057 7058 /** 7059 * Returns whether or not this View draws on its own. 7060 * 7061 * @return true if this view has nothing to draw, false otherwise 7062 */ 7063 @ViewDebug.ExportedProperty(category = "drawing") 7064 public boolean willNotDraw() { 7065 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7066 } 7067 7068 /** 7069 * When a View's drawing cache is enabled, drawing is redirected to an 7070 * offscreen bitmap. Some views, like an ImageView, must be able to 7071 * bypass this mechanism if they already draw a single bitmap, to avoid 7072 * unnecessary usage of the memory. 7073 * 7074 * @param willNotCacheDrawing true if this view does not cache its 7075 * drawing, false otherwise 7076 */ 7077 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7078 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7079 } 7080 7081 /** 7082 * Returns whether or not this View can cache its drawing or not. 7083 * 7084 * @return true if this view does not cache its drawing, false otherwise 7085 */ 7086 @ViewDebug.ExportedProperty(category = "drawing") 7087 public boolean willNotCacheDrawing() { 7088 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7089 } 7090 7091 /** 7092 * Indicates whether this view reacts to click events or not. 7093 * 7094 * @return true if the view is clickable, false otherwise 7095 * 7096 * @see #setClickable(boolean) 7097 * @attr ref android.R.styleable#View_clickable 7098 */ 7099 @ViewDebug.ExportedProperty 7100 public boolean isClickable() { 7101 return (mViewFlags & CLICKABLE) == CLICKABLE; 7102 } 7103 7104 /** 7105 * Enables or disables click events for this view. When a view 7106 * is clickable it will change its state to "pressed" on every click. 7107 * Subclasses should set the view clickable to visually react to 7108 * user's clicks. 7109 * 7110 * @param clickable true to make the view clickable, false otherwise 7111 * 7112 * @see #isClickable() 7113 * @attr ref android.R.styleable#View_clickable 7114 */ 7115 public void setClickable(boolean clickable) { 7116 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7117 } 7118 7119 /** 7120 * Indicates whether this view reacts to long click events or not. 7121 * 7122 * @return true if the view is long clickable, false otherwise 7123 * 7124 * @see #setLongClickable(boolean) 7125 * @attr ref android.R.styleable#View_longClickable 7126 */ 7127 public boolean isLongClickable() { 7128 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7129 } 7130 7131 /** 7132 * Enables or disables long click events for this view. When a view is long 7133 * clickable it reacts to the user holding down the button for a longer 7134 * duration than a tap. This event can either launch the listener or a 7135 * context menu. 7136 * 7137 * @param longClickable true to make the view long clickable, false otherwise 7138 * @see #isLongClickable() 7139 * @attr ref android.R.styleable#View_longClickable 7140 */ 7141 public void setLongClickable(boolean longClickable) { 7142 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7143 } 7144 7145 /** 7146 * Sets the pressed state for this view and provides a touch coordinate for 7147 * animation hinting. 7148 * 7149 * @param pressed Pass true to set the View's internal state to "pressed", 7150 * or false to reverts the View's internal state from a 7151 * previously set "pressed" state. 7152 * @param x The x coordinate of the touch that caused the press 7153 * @param y The y coordinate of the touch that caused the press 7154 */ 7155 private void setPressed(boolean pressed, float x, float y) { 7156 if (pressed) { 7157 drawableHotspotChanged(x, y); 7158 } 7159 7160 setPressed(pressed); 7161 } 7162 7163 /** 7164 * Sets the pressed state for this view. 7165 * 7166 * @see #isClickable() 7167 * @see #setClickable(boolean) 7168 * 7169 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7170 * the View's internal state from a previously set "pressed" state. 7171 */ 7172 public void setPressed(boolean pressed) { 7173 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7174 7175 if (pressed) { 7176 mPrivateFlags |= PFLAG_PRESSED; 7177 } else { 7178 mPrivateFlags &= ~PFLAG_PRESSED; 7179 } 7180 7181 if (needsRefresh) { 7182 refreshDrawableState(); 7183 } 7184 dispatchSetPressed(pressed); 7185 } 7186 7187 /** 7188 * Dispatch setPressed to all of this View's children. 7189 * 7190 * @see #setPressed(boolean) 7191 * 7192 * @param pressed The new pressed state 7193 */ 7194 protected void dispatchSetPressed(boolean pressed) { 7195 } 7196 7197 /** 7198 * Indicates whether the view is currently in pressed state. Unless 7199 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7200 * the pressed state. 7201 * 7202 * @see #setPressed(boolean) 7203 * @see #isClickable() 7204 * @see #setClickable(boolean) 7205 * 7206 * @return true if the view is currently pressed, false otherwise 7207 */ 7208 @ViewDebug.ExportedProperty 7209 public boolean isPressed() { 7210 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7211 } 7212 7213 /** 7214 * Indicates whether this view will save its state (that is, 7215 * whether its {@link #onSaveInstanceState} method will be called). 7216 * 7217 * @return Returns true if the view state saving is enabled, else false. 7218 * 7219 * @see #setSaveEnabled(boolean) 7220 * @attr ref android.R.styleable#View_saveEnabled 7221 */ 7222 public boolean isSaveEnabled() { 7223 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7224 } 7225 7226 /** 7227 * Controls whether the saving of this view's state is 7228 * enabled (that is, whether its {@link #onSaveInstanceState} method 7229 * will be called). Note that even if freezing is enabled, the 7230 * view still must have an id assigned to it (via {@link #setId(int)}) 7231 * for its state to be saved. This flag can only disable the 7232 * saving of this view; any child views may still have their state saved. 7233 * 7234 * @param enabled Set to false to <em>disable</em> state saving, or true 7235 * (the default) to allow it. 7236 * 7237 * @see #isSaveEnabled() 7238 * @see #setId(int) 7239 * @see #onSaveInstanceState() 7240 * @attr ref android.R.styleable#View_saveEnabled 7241 */ 7242 public void setSaveEnabled(boolean enabled) { 7243 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7244 } 7245 7246 /** 7247 * Gets whether the framework should discard touches when the view's 7248 * window is obscured by another visible window. 7249 * Refer to the {@link View} security documentation for more details. 7250 * 7251 * @return True if touch filtering is enabled. 7252 * 7253 * @see #setFilterTouchesWhenObscured(boolean) 7254 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7255 */ 7256 @ViewDebug.ExportedProperty 7257 public boolean getFilterTouchesWhenObscured() { 7258 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7259 } 7260 7261 /** 7262 * Sets whether the framework should discard touches when the view's 7263 * window is obscured by another visible window. 7264 * Refer to the {@link View} security documentation for more details. 7265 * 7266 * @param enabled True if touch filtering should be enabled. 7267 * 7268 * @see #getFilterTouchesWhenObscured 7269 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7270 */ 7271 public void setFilterTouchesWhenObscured(boolean enabled) { 7272 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7273 FILTER_TOUCHES_WHEN_OBSCURED); 7274 } 7275 7276 /** 7277 * Indicates whether the entire hierarchy under this view will save its 7278 * state when a state saving traversal occurs from its parent. The default 7279 * is true; if false, these views will not be saved unless 7280 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7281 * 7282 * @return Returns true if the view state saving from parent is enabled, else false. 7283 * 7284 * @see #setSaveFromParentEnabled(boolean) 7285 */ 7286 public boolean isSaveFromParentEnabled() { 7287 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7288 } 7289 7290 /** 7291 * Controls whether the entire hierarchy under this view will save its 7292 * state when a state saving traversal occurs from its parent. The default 7293 * is true; if false, these views will not be saved unless 7294 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7295 * 7296 * @param enabled Set to false to <em>disable</em> state saving, or true 7297 * (the default) to allow it. 7298 * 7299 * @see #isSaveFromParentEnabled() 7300 * @see #setId(int) 7301 * @see #onSaveInstanceState() 7302 */ 7303 public void setSaveFromParentEnabled(boolean enabled) { 7304 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7305 } 7306 7307 7308 /** 7309 * Returns whether this View is able to take focus. 7310 * 7311 * @return True if this view can take focus, or false otherwise. 7312 * @attr ref android.R.styleable#View_focusable 7313 */ 7314 @ViewDebug.ExportedProperty(category = "focus") 7315 public final boolean isFocusable() { 7316 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7317 } 7318 7319 /** 7320 * When a view is focusable, it may not want to take focus when in touch mode. 7321 * For example, a button would like focus when the user is navigating via a D-pad 7322 * so that the user can click on it, but once the user starts touching the screen, 7323 * the button shouldn't take focus 7324 * @return Whether the view is focusable in touch mode. 7325 * @attr ref android.R.styleable#View_focusableInTouchMode 7326 */ 7327 @ViewDebug.ExportedProperty 7328 public final boolean isFocusableInTouchMode() { 7329 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7330 } 7331 7332 /** 7333 * Find the nearest view in the specified direction that can take focus. 7334 * This does not actually give focus to that view. 7335 * 7336 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7337 * 7338 * @return The nearest focusable in the specified direction, or null if none 7339 * can be found. 7340 */ 7341 public View focusSearch(@FocusRealDirection int direction) { 7342 if (mParent != null) { 7343 return mParent.focusSearch(this, direction); 7344 } else { 7345 return null; 7346 } 7347 } 7348 7349 /** 7350 * This method is the last chance for the focused view and its ancestors to 7351 * respond to an arrow key. This is called when the focused view did not 7352 * consume the key internally, nor could the view system find a new view in 7353 * the requested direction to give focus to. 7354 * 7355 * @param focused The currently focused view. 7356 * @param direction The direction focus wants to move. One of FOCUS_UP, 7357 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7358 * @return True if the this view consumed this unhandled move. 7359 */ 7360 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7361 return false; 7362 } 7363 7364 /** 7365 * If a user manually specified the next view id for a particular direction, 7366 * use the root to look up the view. 7367 * @param root The root view of the hierarchy containing this view. 7368 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7369 * or FOCUS_BACKWARD. 7370 * @return The user specified next view, or null if there is none. 7371 */ 7372 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7373 switch (direction) { 7374 case FOCUS_LEFT: 7375 if (mNextFocusLeftId == View.NO_ID) return null; 7376 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7377 case FOCUS_RIGHT: 7378 if (mNextFocusRightId == View.NO_ID) return null; 7379 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7380 case FOCUS_UP: 7381 if (mNextFocusUpId == View.NO_ID) return null; 7382 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7383 case FOCUS_DOWN: 7384 if (mNextFocusDownId == View.NO_ID) return null; 7385 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7386 case FOCUS_FORWARD: 7387 if (mNextFocusForwardId == View.NO_ID) return null; 7388 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7389 case FOCUS_BACKWARD: { 7390 if (mID == View.NO_ID) return null; 7391 final int id = mID; 7392 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7393 @Override 7394 public boolean apply(View t) { 7395 return t.mNextFocusForwardId == id; 7396 } 7397 }); 7398 } 7399 } 7400 return null; 7401 } 7402 7403 private View findViewInsideOutShouldExist(View root, int id) { 7404 if (mMatchIdPredicate == null) { 7405 mMatchIdPredicate = new MatchIdPredicate(); 7406 } 7407 mMatchIdPredicate.mId = id; 7408 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7409 if (result == null) { 7410 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7411 } 7412 return result; 7413 } 7414 7415 /** 7416 * Find and return all focusable views that are descendants of this view, 7417 * possibly including this view if it is focusable itself. 7418 * 7419 * @param direction The direction of the focus 7420 * @return A list of focusable views 7421 */ 7422 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7423 ArrayList<View> result = new ArrayList<View>(24); 7424 addFocusables(result, direction); 7425 return result; 7426 } 7427 7428 /** 7429 * Add any focusable views that are descendants of this view (possibly 7430 * including this view if it is focusable itself) to views. If we are in touch mode, 7431 * only add views that are also focusable in touch mode. 7432 * 7433 * @param views Focusable views found so far 7434 * @param direction The direction of the focus 7435 */ 7436 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7437 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7438 } 7439 7440 /** 7441 * Adds any focusable views that are descendants of this view (possibly 7442 * including this view if it is focusable itself) to views. This method 7443 * adds all focusable views regardless if we are in touch mode or 7444 * only views focusable in touch mode if we are in touch mode or 7445 * only views that can take accessibility focus if accessibility is enabled 7446 * depending on the focusable mode parameter. 7447 * 7448 * @param views Focusable views found so far or null if all we are interested is 7449 * the number of focusables. 7450 * @param direction The direction of the focus. 7451 * @param focusableMode The type of focusables to be added. 7452 * 7453 * @see #FOCUSABLES_ALL 7454 * @see #FOCUSABLES_TOUCH_MODE 7455 */ 7456 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7457 @FocusableMode int focusableMode) { 7458 if (views == null) { 7459 return; 7460 } 7461 if (!isFocusable()) { 7462 return; 7463 } 7464 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7465 && isInTouchMode() && !isFocusableInTouchMode()) { 7466 return; 7467 } 7468 views.add(this); 7469 } 7470 7471 /** 7472 * Finds the Views that contain given text. The containment is case insensitive. 7473 * The search is performed by either the text that the View renders or the content 7474 * description that describes the view for accessibility purposes and the view does 7475 * not render or both. Clients can specify how the search is to be performed via 7476 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7477 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7478 * 7479 * @param outViews The output list of matching Views. 7480 * @param searched The text to match against. 7481 * 7482 * @see #FIND_VIEWS_WITH_TEXT 7483 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7484 * @see #setContentDescription(CharSequence) 7485 */ 7486 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7487 @FindViewFlags int flags) { 7488 if (getAccessibilityNodeProvider() != null) { 7489 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7490 outViews.add(this); 7491 } 7492 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7493 && (searched != null && searched.length() > 0) 7494 && (mContentDescription != null && mContentDescription.length() > 0)) { 7495 String searchedLowerCase = searched.toString().toLowerCase(); 7496 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7497 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7498 outViews.add(this); 7499 } 7500 } 7501 } 7502 7503 /** 7504 * Find and return all touchable views that are descendants of this view, 7505 * possibly including this view if it is touchable itself. 7506 * 7507 * @return A list of touchable views 7508 */ 7509 public ArrayList<View> getTouchables() { 7510 ArrayList<View> result = new ArrayList<View>(); 7511 addTouchables(result); 7512 return result; 7513 } 7514 7515 /** 7516 * Add any touchable views that are descendants of this view (possibly 7517 * including this view if it is touchable itself) to views. 7518 * 7519 * @param views Touchable views found so far 7520 */ 7521 public void addTouchables(ArrayList<View> views) { 7522 final int viewFlags = mViewFlags; 7523 7524 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7525 && (viewFlags & ENABLED_MASK) == ENABLED) { 7526 views.add(this); 7527 } 7528 } 7529 7530 /** 7531 * Returns whether this View is accessibility focused. 7532 * 7533 * @return True if this View is accessibility focused. 7534 */ 7535 public boolean isAccessibilityFocused() { 7536 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7537 } 7538 7539 /** 7540 * Call this to try to give accessibility focus to this view. 7541 * 7542 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7543 * returns false or the view is no visible or the view already has accessibility 7544 * focus. 7545 * 7546 * See also {@link #focusSearch(int)}, which is what you call to say that you 7547 * have focus, and you want your parent to look for the next one. 7548 * 7549 * @return Whether this view actually took accessibility focus. 7550 * 7551 * @hide 7552 */ 7553 public boolean requestAccessibilityFocus() { 7554 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7555 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7556 return false; 7557 } 7558 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7559 return false; 7560 } 7561 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7562 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7563 ViewRootImpl viewRootImpl = getViewRootImpl(); 7564 if (viewRootImpl != null) { 7565 viewRootImpl.setAccessibilityFocus(this, null); 7566 } 7567 invalidate(); 7568 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7569 return true; 7570 } 7571 return false; 7572 } 7573 7574 /** 7575 * Call this to try to clear accessibility focus of this view. 7576 * 7577 * See also {@link #focusSearch(int)}, which is what you call to say that you 7578 * have focus, and you want your parent to look for the next one. 7579 * 7580 * @hide 7581 */ 7582 public void clearAccessibilityFocus() { 7583 clearAccessibilityFocusNoCallbacks(); 7584 // Clear the global reference of accessibility focus if this 7585 // view or any of its descendants had accessibility focus. 7586 ViewRootImpl viewRootImpl = getViewRootImpl(); 7587 if (viewRootImpl != null) { 7588 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7589 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7590 viewRootImpl.setAccessibilityFocus(null, null); 7591 } 7592 } 7593 } 7594 7595 private void sendAccessibilityHoverEvent(int eventType) { 7596 // Since we are not delivering to a client accessibility events from not 7597 // important views (unless the clinet request that) we need to fire the 7598 // event from the deepest view exposed to the client. As a consequence if 7599 // the user crosses a not exposed view the client will see enter and exit 7600 // of the exposed predecessor followed by and enter and exit of that same 7601 // predecessor when entering and exiting the not exposed descendant. This 7602 // is fine since the client has a clear idea which view is hovered at the 7603 // price of a couple more events being sent. This is a simple and 7604 // working solution. 7605 View source = this; 7606 while (true) { 7607 if (source.includeForAccessibility()) { 7608 source.sendAccessibilityEvent(eventType); 7609 return; 7610 } 7611 ViewParent parent = source.getParent(); 7612 if (parent instanceof View) { 7613 source = (View) parent; 7614 } else { 7615 return; 7616 } 7617 } 7618 } 7619 7620 /** 7621 * Clears accessibility focus without calling any callback methods 7622 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7623 * is used for clearing accessibility focus when giving this focus to 7624 * another view. 7625 */ 7626 void clearAccessibilityFocusNoCallbacks() { 7627 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7628 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7629 invalidate(); 7630 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7631 } 7632 } 7633 7634 /** 7635 * Call this to try to give focus to a specific view or to one of its 7636 * descendants. 7637 * 7638 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7639 * false), or if it is focusable and it is not focusable in touch mode 7640 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7641 * 7642 * See also {@link #focusSearch(int)}, which is what you call to say that you 7643 * have focus, and you want your parent to look for the next one. 7644 * 7645 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7646 * {@link #FOCUS_DOWN} and <code>null</code>. 7647 * 7648 * @return Whether this view or one of its descendants actually took focus. 7649 */ 7650 public final boolean requestFocus() { 7651 return requestFocus(View.FOCUS_DOWN); 7652 } 7653 7654 /** 7655 * Call this to try to give focus to a specific view or to one of its 7656 * descendants and give it a hint about what direction focus is heading. 7657 * 7658 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7659 * false), or if it is focusable and it is not focusable in touch mode 7660 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7661 * 7662 * See also {@link #focusSearch(int)}, which is what you call to say that you 7663 * have focus, and you want your parent to look for the next one. 7664 * 7665 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7666 * <code>null</code> set for the previously focused rectangle. 7667 * 7668 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7669 * @return Whether this view or one of its descendants actually took focus. 7670 */ 7671 public final boolean requestFocus(int direction) { 7672 return requestFocus(direction, null); 7673 } 7674 7675 /** 7676 * Call this to try to give focus to a specific view or to one of its descendants 7677 * and give it hints about the direction and a specific rectangle that the focus 7678 * is coming from. The rectangle can help give larger views a finer grained hint 7679 * about where focus is coming from, and therefore, where to show selection, or 7680 * forward focus change internally. 7681 * 7682 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7683 * false), or if it is focusable and it is not focusable in touch mode 7684 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7685 * 7686 * A View will not take focus if it is not visible. 7687 * 7688 * A View will not take focus if one of its parents has 7689 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7690 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7691 * 7692 * See also {@link #focusSearch(int)}, which is what you call to say that you 7693 * have focus, and you want your parent to look for the next one. 7694 * 7695 * You may wish to override this method if your custom {@link View} has an internal 7696 * {@link View} that it wishes to forward the request to. 7697 * 7698 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7699 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7700 * to give a finer grained hint about where focus is coming from. May be null 7701 * if there is no hint. 7702 * @return Whether this view or one of its descendants actually took focus. 7703 */ 7704 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7705 return requestFocusNoSearch(direction, previouslyFocusedRect); 7706 } 7707 7708 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7709 // need to be focusable 7710 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7711 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7712 return false; 7713 } 7714 7715 // need to be focusable in touch mode if in touch mode 7716 if (isInTouchMode() && 7717 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7718 return false; 7719 } 7720 7721 // need to not have any parents blocking us 7722 if (hasAncestorThatBlocksDescendantFocus()) { 7723 return false; 7724 } 7725 7726 handleFocusGainInternal(direction, previouslyFocusedRect); 7727 return true; 7728 } 7729 7730 /** 7731 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7732 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 7733 * touch mode to request focus when they are touched. 7734 * 7735 * @return Whether this view or one of its descendants actually took focus. 7736 * 7737 * @see #isInTouchMode() 7738 * 7739 */ 7740 public final boolean requestFocusFromTouch() { 7741 // Leave touch mode if we need to 7742 if (isInTouchMode()) { 7743 ViewRootImpl viewRoot = getViewRootImpl(); 7744 if (viewRoot != null) { 7745 viewRoot.ensureTouchMode(false); 7746 } 7747 } 7748 return requestFocus(View.FOCUS_DOWN); 7749 } 7750 7751 /** 7752 * @return Whether any ancestor of this view blocks descendant focus. 7753 */ 7754 private boolean hasAncestorThatBlocksDescendantFocus() { 7755 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7756 ViewParent ancestor = mParent; 7757 while (ancestor instanceof ViewGroup) { 7758 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7759 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7760 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7761 return true; 7762 } else { 7763 ancestor = vgAncestor.getParent(); 7764 } 7765 } 7766 return false; 7767 } 7768 7769 /** 7770 * Gets the mode for determining whether this View is important for accessibility 7771 * which is if it fires accessibility events and if it is reported to 7772 * accessibility services that query the screen. 7773 * 7774 * @return The mode for determining whether a View is important for accessibility. 7775 * 7776 * @attr ref android.R.styleable#View_importantForAccessibility 7777 * 7778 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7779 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7780 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7781 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7782 */ 7783 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7784 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7785 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7786 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7787 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7788 to = "noHideDescendants") 7789 }) 7790 public int getImportantForAccessibility() { 7791 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7792 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7793 } 7794 7795 /** 7796 * Sets the live region mode for this view. This indicates to accessibility 7797 * services whether they should automatically notify the user about changes 7798 * to the view's content description or text, or to the content descriptions 7799 * or text of the view's children (where applicable). 7800 * <p> 7801 * For example, in a login screen with a TextView that displays an "incorrect 7802 * password" notification, that view should be marked as a live region with 7803 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7804 * <p> 7805 * To disable change notifications for this view, use 7806 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7807 * mode for most views. 7808 * <p> 7809 * To indicate that the user should be notified of changes, use 7810 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7811 * <p> 7812 * If the view's changes should interrupt ongoing speech and notify the user 7813 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7814 * 7815 * @param mode The live region mode for this view, one of: 7816 * <ul> 7817 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7818 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7819 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7820 * </ul> 7821 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7822 */ 7823 public void setAccessibilityLiveRegion(int mode) { 7824 if (mode != getAccessibilityLiveRegion()) { 7825 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7826 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7827 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7828 notifyViewAccessibilityStateChangedIfNeeded( 7829 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7830 } 7831 } 7832 7833 /** 7834 * Gets the live region mode for this View. 7835 * 7836 * @return The live region mode for the view. 7837 * 7838 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7839 * 7840 * @see #setAccessibilityLiveRegion(int) 7841 */ 7842 public int getAccessibilityLiveRegion() { 7843 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7844 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7845 } 7846 7847 /** 7848 * Sets how to determine whether this view is important for accessibility 7849 * which is if it fires accessibility events and if it is reported to 7850 * accessibility services that query the screen. 7851 * 7852 * @param mode How to determine whether this view is important for accessibility. 7853 * 7854 * @attr ref android.R.styleable#View_importantForAccessibility 7855 * 7856 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7857 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7858 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7859 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7860 */ 7861 public void setImportantForAccessibility(int mode) { 7862 final int oldMode = getImportantForAccessibility(); 7863 if (mode != oldMode) { 7864 // If we're moving between AUTO and another state, we might not need 7865 // to send a subtree changed notification. We'll store the computed 7866 // importance, since we'll need to check it later to make sure. 7867 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7868 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7869 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7870 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7871 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7872 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7873 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7874 notifySubtreeAccessibilityStateChangedIfNeeded(); 7875 } else { 7876 notifyViewAccessibilityStateChangedIfNeeded( 7877 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7878 } 7879 } 7880 } 7881 7882 /** 7883 * Computes whether this view should be exposed for accessibility. In 7884 * general, views that are interactive or provide information are exposed 7885 * while views that serve only as containers are hidden. 7886 * <p> 7887 * If an ancestor of this view has importance 7888 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7889 * returns <code>false</code>. 7890 * <p> 7891 * Otherwise, the value is computed according to the view's 7892 * {@link #getImportantForAccessibility()} value: 7893 * <ol> 7894 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7895 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7896 * </code> 7897 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7898 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7899 * view satisfies any of the following: 7900 * <ul> 7901 * <li>Is actionable, e.g. {@link #isClickable()}, 7902 * {@link #isLongClickable()}, or {@link #isFocusable()} 7903 * <li>Has an {@link AccessibilityDelegate} 7904 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7905 * {@link OnKeyListener}, etc. 7906 * <li>Is an accessibility live region, e.g. 7907 * {@link #getAccessibilityLiveRegion()} is not 7908 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7909 * </ul> 7910 * </ol> 7911 * 7912 * @return Whether the view is exposed for accessibility. 7913 * @see #setImportantForAccessibility(int) 7914 * @see #getImportantForAccessibility() 7915 */ 7916 public boolean isImportantForAccessibility() { 7917 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7918 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7919 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7920 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7921 return false; 7922 } 7923 7924 // Check parent mode to ensure we're not hidden. 7925 ViewParent parent = mParent; 7926 while (parent instanceof View) { 7927 if (((View) parent).getImportantForAccessibility() 7928 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7929 return false; 7930 } 7931 parent = parent.getParent(); 7932 } 7933 7934 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7935 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7936 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7937 } 7938 7939 /** 7940 * Gets the parent for accessibility purposes. Note that the parent for 7941 * accessibility is not necessary the immediate parent. It is the first 7942 * predecessor that is important for accessibility. 7943 * 7944 * @return The parent for accessibility purposes. 7945 */ 7946 public ViewParent getParentForAccessibility() { 7947 if (mParent instanceof View) { 7948 View parentView = (View) mParent; 7949 if (parentView.includeForAccessibility()) { 7950 return mParent; 7951 } else { 7952 return mParent.getParentForAccessibility(); 7953 } 7954 } 7955 return null; 7956 } 7957 7958 /** 7959 * Adds the children of a given View for accessibility. Since some Views are 7960 * not important for accessibility the children for accessibility are not 7961 * necessarily direct children of the view, rather they are the first level of 7962 * descendants important for accessibility. 7963 * 7964 * @param children The list of children for accessibility. 7965 */ 7966 public void addChildrenForAccessibility(ArrayList<View> children) { 7967 7968 } 7969 7970 /** 7971 * Whether to regard this view for accessibility. A view is regarded for 7972 * accessibility if it is important for accessibility or the querying 7973 * accessibility service has explicitly requested that view not 7974 * important for accessibility are regarded. 7975 * 7976 * @return Whether to regard the view for accessibility. 7977 * 7978 * @hide 7979 */ 7980 public boolean includeForAccessibility() { 7981 if (mAttachInfo != null) { 7982 return (mAttachInfo.mAccessibilityFetchFlags 7983 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7984 || isImportantForAccessibility(); 7985 } 7986 return false; 7987 } 7988 7989 /** 7990 * Returns whether the View is considered actionable from 7991 * accessibility perspective. Such view are important for 7992 * accessibility. 7993 * 7994 * @return True if the view is actionable for accessibility. 7995 * 7996 * @hide 7997 */ 7998 public boolean isActionableForAccessibility() { 7999 return (isClickable() || isLongClickable() || isFocusable()); 8000 } 8001 8002 /** 8003 * Returns whether the View has registered callbacks which makes it 8004 * important for accessibility. 8005 * 8006 * @return True if the view is actionable for accessibility. 8007 */ 8008 private boolean hasListenersForAccessibility() { 8009 ListenerInfo info = getListenerInfo(); 8010 return mTouchDelegate != null || info.mOnKeyListener != null 8011 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8012 || info.mOnHoverListener != null || info.mOnDragListener != null; 8013 } 8014 8015 /** 8016 * Notifies that the accessibility state of this view changed. The change 8017 * is local to this view and does not represent structural changes such 8018 * as children and parent. For example, the view became focusable. The 8019 * notification is at at most once every 8020 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8021 * to avoid unnecessary load to the system. Also once a view has a pending 8022 * notification this method is a NOP until the notification has been sent. 8023 * 8024 * @hide 8025 */ 8026 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8027 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8028 return; 8029 } 8030 if (mSendViewStateChangedAccessibilityEvent == null) { 8031 mSendViewStateChangedAccessibilityEvent = 8032 new SendViewStateChangedAccessibilityEvent(); 8033 } 8034 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8035 } 8036 8037 /** 8038 * Notifies that the accessibility state of this view changed. The change 8039 * is *not* local to this view and does represent structural changes such 8040 * as children and parent. For example, the view size changed. The 8041 * notification is at at most once every 8042 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8043 * to avoid unnecessary load to the system. Also once a view has a pending 8044 * notification this method is a NOP until the notification has been sent. 8045 * 8046 * @hide 8047 */ 8048 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8049 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8050 return; 8051 } 8052 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8053 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8054 if (mParent != null) { 8055 try { 8056 mParent.notifySubtreeAccessibilityStateChanged( 8057 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8058 } catch (AbstractMethodError e) { 8059 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8060 " does not fully implement ViewParent", e); 8061 } 8062 } 8063 } 8064 } 8065 8066 /** 8067 * Reset the flag indicating the accessibility state of the subtree rooted 8068 * at this view changed. 8069 */ 8070 void resetSubtreeAccessibilityStateChanged() { 8071 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8072 } 8073 8074 /** 8075 * Report an accessibility action to this view's parents for delegated processing. 8076 * 8077 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 8078 * call this method to delegate an accessibility action to a supporting parent. If the parent 8079 * returns true from its 8080 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 8081 * method this method will return true to signify that the action was consumed.</p> 8082 * 8083 * <p>This method is useful for implementing nested scrolling child views. If 8084 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 8085 * a custom view implementation may invoke this method to allow a parent to consume the 8086 * scroll first. If this method returns true the custom view should skip its own scrolling 8087 * behavior.</p> 8088 * 8089 * @param action Accessibility action to delegate 8090 * @param arguments Optional action arguments 8091 * @return true if the action was consumed by a parent 8092 */ 8093 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 8094 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 8095 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 8096 return true; 8097 } 8098 } 8099 return false; 8100 } 8101 8102 /** 8103 * Performs the specified accessibility action on the view. For 8104 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8105 * <p> 8106 * If an {@link AccessibilityDelegate} has been specified via calling 8107 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8108 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8109 * is responsible for handling this call. 8110 * </p> 8111 * 8112 * <p>The default implementation will delegate 8113 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 8114 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 8115 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 8116 * 8117 * @param action The action to perform. 8118 * @param arguments Optional action arguments. 8119 * @return Whether the action was performed. 8120 */ 8121 public boolean performAccessibilityAction(int action, Bundle arguments) { 8122 if (mAccessibilityDelegate != null) { 8123 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8124 } else { 8125 return performAccessibilityActionInternal(action, arguments); 8126 } 8127 } 8128 8129 /** 8130 * @see #performAccessibilityAction(int, Bundle) 8131 * 8132 * Note: Called from the default {@link AccessibilityDelegate}. 8133 * 8134 * @hide 8135 */ 8136 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8137 if (isNestedScrollingEnabled() 8138 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 8139 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { 8140 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 8141 return true; 8142 } 8143 } 8144 8145 switch (action) { 8146 case AccessibilityNodeInfo.ACTION_CLICK: { 8147 if (isClickable()) { 8148 performClick(); 8149 return true; 8150 } 8151 } break; 8152 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8153 if (isLongClickable()) { 8154 performLongClick(); 8155 return true; 8156 } 8157 } break; 8158 case AccessibilityNodeInfo.ACTION_FOCUS: { 8159 if (!hasFocus()) { 8160 // Get out of touch mode since accessibility 8161 // wants to move focus around. 8162 getViewRootImpl().ensureTouchMode(false); 8163 return requestFocus(); 8164 } 8165 } break; 8166 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8167 if (hasFocus()) { 8168 clearFocus(); 8169 return !isFocused(); 8170 } 8171 } break; 8172 case AccessibilityNodeInfo.ACTION_SELECT: { 8173 if (!isSelected()) { 8174 setSelected(true); 8175 return isSelected(); 8176 } 8177 } break; 8178 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8179 if (isSelected()) { 8180 setSelected(false); 8181 return !isSelected(); 8182 } 8183 } break; 8184 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8185 if (!isAccessibilityFocused()) { 8186 return requestAccessibilityFocus(); 8187 } 8188 } break; 8189 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8190 if (isAccessibilityFocused()) { 8191 clearAccessibilityFocus(); 8192 return true; 8193 } 8194 } break; 8195 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8196 if (arguments != null) { 8197 final int granularity = arguments.getInt( 8198 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8199 final boolean extendSelection = arguments.getBoolean( 8200 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8201 return traverseAtGranularity(granularity, true, extendSelection); 8202 } 8203 } break; 8204 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8205 if (arguments != null) { 8206 final int granularity = arguments.getInt( 8207 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8208 final boolean extendSelection = arguments.getBoolean( 8209 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8210 return traverseAtGranularity(granularity, false, extendSelection); 8211 } 8212 } break; 8213 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8214 CharSequence text = getIterableTextForAccessibility(); 8215 if (text == null) { 8216 return false; 8217 } 8218 final int start = (arguments != null) ? arguments.getInt( 8219 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8220 final int end = (arguments != null) ? arguments.getInt( 8221 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8222 // Only cursor position can be specified (selection length == 0) 8223 if ((getAccessibilitySelectionStart() != start 8224 || getAccessibilitySelectionEnd() != end) 8225 && (start == end)) { 8226 setAccessibilitySelection(start, end); 8227 notifyViewAccessibilityStateChangedIfNeeded( 8228 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8229 return true; 8230 } 8231 } break; 8232 } 8233 return false; 8234 } 8235 8236 private boolean traverseAtGranularity(int granularity, boolean forward, 8237 boolean extendSelection) { 8238 CharSequence text = getIterableTextForAccessibility(); 8239 if (text == null || text.length() == 0) { 8240 return false; 8241 } 8242 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8243 if (iterator == null) { 8244 return false; 8245 } 8246 int current = getAccessibilitySelectionEnd(); 8247 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8248 current = forward ? 0 : text.length(); 8249 } 8250 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8251 if (range == null) { 8252 return false; 8253 } 8254 final int segmentStart = range[0]; 8255 final int segmentEnd = range[1]; 8256 int selectionStart; 8257 int selectionEnd; 8258 if (extendSelection && isAccessibilitySelectionExtendable()) { 8259 selectionStart = getAccessibilitySelectionStart(); 8260 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8261 selectionStart = forward ? segmentStart : segmentEnd; 8262 } 8263 selectionEnd = forward ? segmentEnd : segmentStart; 8264 } else { 8265 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8266 } 8267 setAccessibilitySelection(selectionStart, selectionEnd); 8268 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8269 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8270 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8271 return true; 8272 } 8273 8274 /** 8275 * Gets the text reported for accessibility purposes. 8276 * 8277 * @return The accessibility text. 8278 * 8279 * @hide 8280 */ 8281 public CharSequence getIterableTextForAccessibility() { 8282 return getContentDescription(); 8283 } 8284 8285 /** 8286 * Gets whether accessibility selection can be extended. 8287 * 8288 * @return If selection is extensible. 8289 * 8290 * @hide 8291 */ 8292 public boolean isAccessibilitySelectionExtendable() { 8293 return false; 8294 } 8295 8296 /** 8297 * @hide 8298 */ 8299 public int getAccessibilitySelectionStart() { 8300 return mAccessibilityCursorPosition; 8301 } 8302 8303 /** 8304 * @hide 8305 */ 8306 public int getAccessibilitySelectionEnd() { 8307 return getAccessibilitySelectionStart(); 8308 } 8309 8310 /** 8311 * @hide 8312 */ 8313 public void setAccessibilitySelection(int start, int end) { 8314 if (start == end && end == mAccessibilityCursorPosition) { 8315 return; 8316 } 8317 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8318 mAccessibilityCursorPosition = start; 8319 } else { 8320 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8321 } 8322 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8323 } 8324 8325 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8326 int fromIndex, int toIndex) { 8327 if (mParent == null) { 8328 return; 8329 } 8330 AccessibilityEvent event = AccessibilityEvent.obtain( 8331 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8332 onInitializeAccessibilityEvent(event); 8333 onPopulateAccessibilityEvent(event); 8334 event.setFromIndex(fromIndex); 8335 event.setToIndex(toIndex); 8336 event.setAction(action); 8337 event.setMovementGranularity(granularity); 8338 mParent.requestSendAccessibilityEvent(this, event); 8339 } 8340 8341 /** 8342 * @hide 8343 */ 8344 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8345 switch (granularity) { 8346 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8347 CharSequence text = getIterableTextForAccessibility(); 8348 if (text != null && text.length() > 0) { 8349 CharacterTextSegmentIterator iterator = 8350 CharacterTextSegmentIterator.getInstance( 8351 mContext.getResources().getConfiguration().locale); 8352 iterator.initialize(text.toString()); 8353 return iterator; 8354 } 8355 } break; 8356 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8357 CharSequence text = getIterableTextForAccessibility(); 8358 if (text != null && text.length() > 0) { 8359 WordTextSegmentIterator iterator = 8360 WordTextSegmentIterator.getInstance( 8361 mContext.getResources().getConfiguration().locale); 8362 iterator.initialize(text.toString()); 8363 return iterator; 8364 } 8365 } break; 8366 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8367 CharSequence text = getIterableTextForAccessibility(); 8368 if (text != null && text.length() > 0) { 8369 ParagraphTextSegmentIterator iterator = 8370 ParagraphTextSegmentIterator.getInstance(); 8371 iterator.initialize(text.toString()); 8372 return iterator; 8373 } 8374 } break; 8375 } 8376 return null; 8377 } 8378 8379 /** 8380 * @hide 8381 */ 8382 public void dispatchStartTemporaryDetach() { 8383 onStartTemporaryDetach(); 8384 } 8385 8386 /** 8387 * This is called when a container is going to temporarily detach a child, with 8388 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8389 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8390 * {@link #onDetachedFromWindow()} when the container is done. 8391 */ 8392 public void onStartTemporaryDetach() { 8393 removeUnsetPressCallback(); 8394 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8395 } 8396 8397 /** 8398 * @hide 8399 */ 8400 public void dispatchFinishTemporaryDetach() { 8401 onFinishTemporaryDetach(); 8402 } 8403 8404 /** 8405 * Called after {@link #onStartTemporaryDetach} when the container is done 8406 * changing the view. 8407 */ 8408 public void onFinishTemporaryDetach() { 8409 } 8410 8411 /** 8412 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8413 * for this view's window. Returns null if the view is not currently attached 8414 * to the window. Normally you will not need to use this directly, but 8415 * just use the standard high-level event callbacks like 8416 * {@link #onKeyDown(int, KeyEvent)}. 8417 */ 8418 public KeyEvent.DispatcherState getKeyDispatcherState() { 8419 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8420 } 8421 8422 /** 8423 * Dispatch a key event before it is processed by any input method 8424 * associated with the view hierarchy. This can be used to intercept 8425 * key events in special situations before the IME consumes them; a 8426 * typical example would be handling the BACK key to update the application's 8427 * UI instead of allowing the IME to see it and close itself. 8428 * 8429 * @param event The key event to be dispatched. 8430 * @return True if the event was handled, false otherwise. 8431 */ 8432 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8433 return onKeyPreIme(event.getKeyCode(), event); 8434 } 8435 8436 /** 8437 * Dispatch a key event to the next view on the focus path. This path runs 8438 * from the top of the view tree down to the currently focused view. If this 8439 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8440 * the next node down the focus path. This method also fires any key 8441 * listeners. 8442 * 8443 * @param event The key event to be dispatched. 8444 * @return True if the event was handled, false otherwise. 8445 */ 8446 public boolean dispatchKeyEvent(KeyEvent event) { 8447 if (mInputEventConsistencyVerifier != null) { 8448 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8449 } 8450 8451 // Give any attached key listener a first crack at the event. 8452 //noinspection SimplifiableIfStatement 8453 ListenerInfo li = mListenerInfo; 8454 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8455 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8456 return true; 8457 } 8458 8459 if (event.dispatch(this, mAttachInfo != null 8460 ? mAttachInfo.mKeyDispatchState : null, this)) { 8461 return true; 8462 } 8463 8464 if (mInputEventConsistencyVerifier != null) { 8465 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8466 } 8467 return false; 8468 } 8469 8470 /** 8471 * Dispatches a key shortcut event. 8472 * 8473 * @param event The key event to be dispatched. 8474 * @return True if the event was handled by the view, false otherwise. 8475 */ 8476 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8477 return onKeyShortcut(event.getKeyCode(), event); 8478 } 8479 8480 /** 8481 * Pass the touch screen motion event down to the target view, or this 8482 * view if it is the target. 8483 * 8484 * @param event The motion event to be dispatched. 8485 * @return True if the event was handled by the view, false otherwise. 8486 */ 8487 public boolean dispatchTouchEvent(MotionEvent event) { 8488 // If the event should be handled by accessibility focus first. 8489 if (event.isTargetAccessibilityFocus()) { 8490 // We don't have focus or no virtual descendant has it, do not handle the event. 8491 if (!isAccessibilityFocusedViewOrHost()) { 8492 return false; 8493 } 8494 // We have focus and got the event, then use normal event dispatch. 8495 event.setTargetAccessibilityFocus(false); 8496 } 8497 8498 boolean result = false; 8499 8500 if (mInputEventConsistencyVerifier != null) { 8501 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8502 } 8503 8504 final int actionMasked = event.getActionMasked(); 8505 if (actionMasked == MotionEvent.ACTION_DOWN) { 8506 // Defensive cleanup for new gesture 8507 stopNestedScroll(); 8508 } 8509 8510 if (onFilterTouchEventForSecurity(event)) { 8511 //noinspection SimplifiableIfStatement 8512 ListenerInfo li = mListenerInfo; 8513 if (li != null && li.mOnTouchListener != null 8514 && (mViewFlags & ENABLED_MASK) == ENABLED 8515 && li.mOnTouchListener.onTouch(this, event)) { 8516 result = true; 8517 } 8518 8519 if (!result && onTouchEvent(event)) { 8520 result = true; 8521 } 8522 } 8523 8524 if (!result && mInputEventConsistencyVerifier != null) { 8525 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8526 } 8527 8528 // Clean up after nested scrolls if this is the end of a gesture; 8529 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8530 // of the gesture. 8531 if (actionMasked == MotionEvent.ACTION_UP || 8532 actionMasked == MotionEvent.ACTION_CANCEL || 8533 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8534 stopNestedScroll(); 8535 } 8536 8537 return result; 8538 } 8539 8540 boolean isAccessibilityFocusedViewOrHost() { 8541 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 8542 .getAccessibilityFocusedHost() == this); 8543 } 8544 8545 /** 8546 * Filter the touch event to apply security policies. 8547 * 8548 * @param event The motion event to be filtered. 8549 * @return True if the event should be dispatched, false if the event should be dropped. 8550 * 8551 * @see #getFilterTouchesWhenObscured 8552 */ 8553 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8554 //noinspection RedundantIfStatement 8555 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8556 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8557 // Window is obscured, drop this touch. 8558 return false; 8559 } 8560 return true; 8561 } 8562 8563 /** 8564 * Pass a trackball motion event down to the focused view. 8565 * 8566 * @param event The motion event to be dispatched. 8567 * @return True if the event was handled by the view, false otherwise. 8568 */ 8569 public boolean dispatchTrackballEvent(MotionEvent event) { 8570 if (mInputEventConsistencyVerifier != null) { 8571 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8572 } 8573 8574 return onTrackballEvent(event); 8575 } 8576 8577 /** 8578 * Dispatch a generic motion event. 8579 * <p> 8580 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8581 * are delivered to the view under the pointer. All other generic motion events are 8582 * delivered to the focused view. Hover events are handled specially and are delivered 8583 * to {@link #onHoverEvent(MotionEvent)}. 8584 * </p> 8585 * 8586 * @param event The motion event to be dispatched. 8587 * @return True if the event was handled by the view, false otherwise. 8588 */ 8589 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8590 if (mInputEventConsistencyVerifier != null) { 8591 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8592 } 8593 8594 final int source = event.getSource(); 8595 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8596 final int action = event.getAction(); 8597 if (action == MotionEvent.ACTION_HOVER_ENTER 8598 || action == MotionEvent.ACTION_HOVER_MOVE 8599 || action == MotionEvent.ACTION_HOVER_EXIT) { 8600 if (dispatchHoverEvent(event)) { 8601 return true; 8602 } 8603 } else if (dispatchGenericPointerEvent(event)) { 8604 return true; 8605 } 8606 } else if (dispatchGenericFocusedEvent(event)) { 8607 return true; 8608 } 8609 8610 if (dispatchGenericMotionEventInternal(event)) { 8611 return true; 8612 } 8613 8614 if (mInputEventConsistencyVerifier != null) { 8615 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8616 } 8617 return false; 8618 } 8619 8620 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8621 //noinspection SimplifiableIfStatement 8622 ListenerInfo li = mListenerInfo; 8623 if (li != null && li.mOnGenericMotionListener != null 8624 && (mViewFlags & ENABLED_MASK) == ENABLED 8625 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8626 return true; 8627 } 8628 8629 if (onGenericMotionEvent(event)) { 8630 return true; 8631 } 8632 8633 if (mInputEventConsistencyVerifier != null) { 8634 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8635 } 8636 return false; 8637 } 8638 8639 /** 8640 * Dispatch a hover event. 8641 * <p> 8642 * Do not call this method directly. 8643 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8644 * </p> 8645 * 8646 * @param event The motion event to be dispatched. 8647 * @return True if the event was handled by the view, false otherwise. 8648 */ 8649 protected boolean dispatchHoverEvent(MotionEvent event) { 8650 ListenerInfo li = mListenerInfo; 8651 //noinspection SimplifiableIfStatement 8652 if (li != null && li.mOnHoverListener != null 8653 && (mViewFlags & ENABLED_MASK) == ENABLED 8654 && li.mOnHoverListener.onHover(this, event)) { 8655 return true; 8656 } 8657 8658 return onHoverEvent(event); 8659 } 8660 8661 /** 8662 * Returns true if the view has a child to which it has recently sent 8663 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8664 * it does not have a hovered child, then it must be the innermost hovered view. 8665 * @hide 8666 */ 8667 protected boolean hasHoveredChild() { 8668 return false; 8669 } 8670 8671 /** 8672 * Dispatch a generic motion event to the view under the first pointer. 8673 * <p> 8674 * Do not call this method directly. 8675 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8676 * </p> 8677 * 8678 * @param event The motion event to be dispatched. 8679 * @return True if the event was handled by the view, false otherwise. 8680 */ 8681 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8682 return false; 8683 } 8684 8685 /** 8686 * Dispatch a generic motion event to the currently focused view. 8687 * <p> 8688 * Do not call this method directly. 8689 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8690 * </p> 8691 * 8692 * @param event The motion event to be dispatched. 8693 * @return True if the event was handled by the view, false otherwise. 8694 */ 8695 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8696 return false; 8697 } 8698 8699 /** 8700 * Dispatch a pointer event. 8701 * <p> 8702 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8703 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8704 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8705 * and should not be expected to handle other pointing device features. 8706 * </p> 8707 * 8708 * @param event The motion event to be dispatched. 8709 * @return True if the event was handled by the view, false otherwise. 8710 * @hide 8711 */ 8712 public final boolean dispatchPointerEvent(MotionEvent event) { 8713 if (event.isTouchEvent()) { 8714 return dispatchTouchEvent(event); 8715 } else { 8716 return dispatchGenericMotionEvent(event); 8717 } 8718 } 8719 8720 /** 8721 * Called when the window containing this view gains or loses window focus. 8722 * ViewGroups should override to route to their children. 8723 * 8724 * @param hasFocus True if the window containing this view now has focus, 8725 * false otherwise. 8726 */ 8727 public void dispatchWindowFocusChanged(boolean hasFocus) { 8728 onWindowFocusChanged(hasFocus); 8729 } 8730 8731 /** 8732 * Called when the window containing this view gains or loses focus. Note 8733 * that this is separate from view focus: to receive key events, both 8734 * your view and its window must have focus. If a window is displayed 8735 * on top of yours that takes input focus, then your own window will lose 8736 * focus but the view focus will remain unchanged. 8737 * 8738 * @param hasWindowFocus True if the window containing this view now has 8739 * focus, false otherwise. 8740 */ 8741 public void onWindowFocusChanged(boolean hasWindowFocus) { 8742 InputMethodManager imm = InputMethodManager.peekInstance(); 8743 if (!hasWindowFocus) { 8744 if (isPressed()) { 8745 setPressed(false); 8746 } 8747 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8748 imm.focusOut(this); 8749 } 8750 removeLongPressCallback(); 8751 removeTapCallback(); 8752 onFocusLost(); 8753 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8754 imm.focusIn(this); 8755 } 8756 refreshDrawableState(); 8757 } 8758 8759 /** 8760 * Returns true if this view is in a window that currently has window focus. 8761 * Note that this is not the same as the view itself having focus. 8762 * 8763 * @return True if this view is in a window that currently has window focus. 8764 */ 8765 public boolean hasWindowFocus() { 8766 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8767 } 8768 8769 /** 8770 * Dispatch a view visibility change down the view hierarchy. 8771 * ViewGroups should override to route to their children. 8772 * @param changedView The view whose visibility changed. Could be 'this' or 8773 * an ancestor view. 8774 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8775 * {@link #INVISIBLE} or {@link #GONE}. 8776 */ 8777 protected void dispatchVisibilityChanged(@NonNull View changedView, 8778 @Visibility int visibility) { 8779 onVisibilityChanged(changedView, visibility); 8780 } 8781 8782 /** 8783 * Called when the visibility of the view or an ancestor of the view has 8784 * changed. 8785 * 8786 * @param changedView The view whose visibility changed. May be 8787 * {@code this} or an ancestor view. 8788 * @param visibility The new visibility, one of {@link #VISIBLE}, 8789 * {@link #INVISIBLE} or {@link #GONE}. 8790 */ 8791 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8792 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 8793 if (visible) { 8794 if (mAttachInfo != null) { 8795 initialAwakenScrollBars(); 8796 } else { 8797 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8798 } 8799 } 8800 8801 final Drawable dr = mBackground; 8802 if (dr != null && visible != dr.isVisible()) { 8803 dr.setVisible(visible, false); 8804 } 8805 } 8806 8807 /** 8808 * Dispatch a hint about whether this view is displayed. For instance, when 8809 * a View moves out of the screen, it might receives a display hint indicating 8810 * the view is not displayed. Applications should not <em>rely</em> on this hint 8811 * as there is no guarantee that they will receive one. 8812 * 8813 * @param hint A hint about whether or not this view is displayed: 8814 * {@link #VISIBLE} or {@link #INVISIBLE}. 8815 */ 8816 public void dispatchDisplayHint(@Visibility int hint) { 8817 onDisplayHint(hint); 8818 } 8819 8820 /** 8821 * Gives this view a hint about whether is displayed or not. For instance, when 8822 * a View moves out of the screen, it might receives a display hint indicating 8823 * the view is not displayed. Applications should not <em>rely</em> on this hint 8824 * as there is no guarantee that they will receive one. 8825 * 8826 * @param hint A hint about whether or not this view is displayed: 8827 * {@link #VISIBLE} or {@link #INVISIBLE}. 8828 */ 8829 protected void onDisplayHint(@Visibility int hint) { 8830 } 8831 8832 /** 8833 * Dispatch a window visibility change down the view hierarchy. 8834 * ViewGroups should override to route to their children. 8835 * 8836 * @param visibility The new visibility of the window. 8837 * 8838 * @see #onWindowVisibilityChanged(int) 8839 */ 8840 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8841 onWindowVisibilityChanged(visibility); 8842 } 8843 8844 /** 8845 * Called when the window containing has change its visibility 8846 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8847 * that this tells you whether or not your window is being made visible 8848 * to the window manager; this does <em>not</em> tell you whether or not 8849 * your window is obscured by other windows on the screen, even if it 8850 * is itself visible. 8851 * 8852 * @param visibility The new visibility of the window. 8853 */ 8854 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8855 if (visibility == VISIBLE) { 8856 initialAwakenScrollBars(); 8857 } 8858 } 8859 8860 /** 8861 * Returns the current visibility of the window this view is attached to 8862 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8863 * 8864 * @return Returns the current visibility of the view's window. 8865 */ 8866 @Visibility 8867 public int getWindowVisibility() { 8868 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8869 } 8870 8871 /** 8872 * Retrieve the overall visible display size in which the window this view is 8873 * attached to has been positioned in. This takes into account screen 8874 * decorations above the window, for both cases where the window itself 8875 * is being position inside of them or the window is being placed under 8876 * then and covered insets are used for the window to position its content 8877 * inside. In effect, this tells you the available area where content can 8878 * be placed and remain visible to users. 8879 * 8880 * <p>This function requires an IPC back to the window manager to retrieve 8881 * the requested information, so should not be used in performance critical 8882 * code like drawing. 8883 * 8884 * @param outRect Filled in with the visible display frame. If the view 8885 * is not attached to a window, this is simply the raw display size. 8886 */ 8887 public void getWindowVisibleDisplayFrame(Rect outRect) { 8888 if (mAttachInfo != null) { 8889 try { 8890 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8891 } catch (RemoteException e) { 8892 return; 8893 } 8894 // XXX This is really broken, and probably all needs to be done 8895 // in the window manager, and we need to know more about whether 8896 // we want the area behind or in front of the IME. 8897 final Rect insets = mAttachInfo.mVisibleInsets; 8898 outRect.left += insets.left; 8899 outRect.top += insets.top; 8900 outRect.right -= insets.right; 8901 outRect.bottom -= insets.bottom; 8902 return; 8903 } 8904 // The view is not attached to a display so we don't have a context. 8905 // Make a best guess about the display size. 8906 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8907 d.getRectSize(outRect); 8908 } 8909 8910 /** 8911 * Dispatch a notification about a resource configuration change down 8912 * the view hierarchy. 8913 * ViewGroups should override to route to their children. 8914 * 8915 * @param newConfig The new resource configuration. 8916 * 8917 * @see #onConfigurationChanged(android.content.res.Configuration) 8918 */ 8919 public void dispatchConfigurationChanged(Configuration newConfig) { 8920 onConfigurationChanged(newConfig); 8921 } 8922 8923 /** 8924 * Called when the current configuration of the resources being used 8925 * by the application have changed. You can use this to decide when 8926 * to reload resources that can changed based on orientation and other 8927 * configuration characteristics. You only need to use this if you are 8928 * not relying on the normal {@link android.app.Activity} mechanism of 8929 * recreating the activity instance upon a configuration change. 8930 * 8931 * @param newConfig The new resource configuration. 8932 */ 8933 protected void onConfigurationChanged(Configuration newConfig) { 8934 } 8935 8936 /** 8937 * Private function to aggregate all per-view attributes in to the view 8938 * root. 8939 */ 8940 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8941 performCollectViewAttributes(attachInfo, visibility); 8942 } 8943 8944 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8945 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8946 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8947 attachInfo.mKeepScreenOn = true; 8948 } 8949 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8950 ListenerInfo li = mListenerInfo; 8951 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8952 attachInfo.mHasSystemUiListeners = true; 8953 } 8954 } 8955 } 8956 8957 void needGlobalAttributesUpdate(boolean force) { 8958 final AttachInfo ai = mAttachInfo; 8959 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8960 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8961 || ai.mHasSystemUiListeners) { 8962 ai.mRecomputeGlobalAttributes = true; 8963 } 8964 } 8965 } 8966 8967 /** 8968 * Returns whether the device is currently in touch mode. Touch mode is entered 8969 * once the user begins interacting with the device by touch, and affects various 8970 * things like whether focus is always visible to the user. 8971 * 8972 * @return Whether the device is in touch mode. 8973 */ 8974 @ViewDebug.ExportedProperty 8975 public boolean isInTouchMode() { 8976 if (mAttachInfo != null) { 8977 return mAttachInfo.mInTouchMode; 8978 } else { 8979 return ViewRootImpl.isInTouchMode(); 8980 } 8981 } 8982 8983 /** 8984 * Returns the context the view is running in, through which it can 8985 * access the current theme, resources, etc. 8986 * 8987 * @return The view's Context. 8988 */ 8989 @ViewDebug.CapturedViewProperty 8990 public final Context getContext() { 8991 return mContext; 8992 } 8993 8994 /** 8995 * Handle a key event before it is processed by any input method 8996 * associated with the view hierarchy. This can be used to intercept 8997 * key events in special situations before the IME consumes them; a 8998 * typical example would be handling the BACK key to update the application's 8999 * UI instead of allowing the IME to see it and close itself. 9000 * 9001 * @param keyCode The value in event.getKeyCode(). 9002 * @param event Description of the key event. 9003 * @return If you handled the event, return true. If you want to allow the 9004 * event to be handled by the next receiver, return false. 9005 */ 9006 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9007 return false; 9008 } 9009 9010 /** 9011 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9012 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9013 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9014 * is released, if the view is enabled and clickable. 9015 * 9016 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9017 * although some may elect to do so in some situations. Do not rely on this to 9018 * catch software key presses. 9019 * 9020 * @param keyCode A key code that represents the button pressed, from 9021 * {@link android.view.KeyEvent}. 9022 * @param event The KeyEvent object that defines the button action. 9023 */ 9024 public boolean onKeyDown(int keyCode, KeyEvent event) { 9025 boolean result = false; 9026 9027 if (KeyEvent.isConfirmKey(keyCode)) { 9028 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9029 return true; 9030 } 9031 // Long clickable items don't necessarily have to be clickable 9032 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9033 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9034 (event.getRepeatCount() == 0)) { 9035 setPressed(true); 9036 checkForLongClick(0); 9037 return true; 9038 } 9039 } 9040 return result; 9041 } 9042 9043 /** 9044 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9045 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9046 * the event). 9047 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9048 * although some may elect to do so in some situations. Do not rely on this to 9049 * catch software key presses. 9050 */ 9051 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9052 return false; 9053 } 9054 9055 /** 9056 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9057 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9058 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9059 * {@link KeyEvent#KEYCODE_ENTER} is released. 9060 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9061 * although some may elect to do so in some situations. Do not rely on this to 9062 * catch software key presses. 9063 * 9064 * @param keyCode A key code that represents the button pressed, from 9065 * {@link android.view.KeyEvent}. 9066 * @param event The KeyEvent object that defines the button action. 9067 */ 9068 public boolean onKeyUp(int keyCode, KeyEvent event) { 9069 if (KeyEvent.isConfirmKey(keyCode)) { 9070 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9071 return true; 9072 } 9073 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9074 setPressed(false); 9075 9076 if (!mHasPerformedLongPress) { 9077 // This is a tap, so remove the longpress check 9078 removeLongPressCallback(); 9079 return performClick(); 9080 } 9081 } 9082 } 9083 return false; 9084 } 9085 9086 /** 9087 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9088 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9089 * the event). 9090 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9091 * although some may elect to do so in some situations. Do not rely on this to 9092 * catch software key presses. 9093 * 9094 * @param keyCode A key code that represents the button pressed, from 9095 * {@link android.view.KeyEvent}. 9096 * @param repeatCount The number of times the action was made. 9097 * @param event The KeyEvent object that defines the button action. 9098 */ 9099 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9100 return false; 9101 } 9102 9103 /** 9104 * Called on the focused view when a key shortcut event is not handled. 9105 * Override this method to implement local key shortcuts for the View. 9106 * Key shortcuts can also be implemented by setting the 9107 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9108 * 9109 * @param keyCode The value in event.getKeyCode(). 9110 * @param event Description of the key event. 9111 * @return If you handled the event, return true. If you want to allow the 9112 * event to be handled by the next receiver, return false. 9113 */ 9114 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9115 return false; 9116 } 9117 9118 /** 9119 * Check whether the called view is a text editor, in which case it 9120 * would make sense to automatically display a soft input window for 9121 * it. Subclasses should override this if they implement 9122 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9123 * a call on that method would return a non-null InputConnection, and 9124 * they are really a first-class editor that the user would normally 9125 * start typing on when the go into a window containing your view. 9126 * 9127 * <p>The default implementation always returns false. This does 9128 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9129 * will not be called or the user can not otherwise perform edits on your 9130 * view; it is just a hint to the system that this is not the primary 9131 * purpose of this view. 9132 * 9133 * @return Returns true if this view is a text editor, else false. 9134 */ 9135 public boolean onCheckIsTextEditor() { 9136 return false; 9137 } 9138 9139 /** 9140 * Create a new InputConnection for an InputMethod to interact 9141 * with the view. The default implementation returns null, since it doesn't 9142 * support input methods. You can override this to implement such support. 9143 * This is only needed for views that take focus and text input. 9144 * 9145 * <p>When implementing this, you probably also want to implement 9146 * {@link #onCheckIsTextEditor()} to indicate you will return a 9147 * non-null InputConnection.</p> 9148 * 9149 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9150 * object correctly and in its entirety, so that the connected IME can rely 9151 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9152 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9153 * must be filled in with the correct cursor position for IMEs to work correctly 9154 * with your application.</p> 9155 * 9156 * @param outAttrs Fill in with attribute information about the connection. 9157 */ 9158 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9159 return null; 9160 } 9161 9162 /** 9163 * Called by the {@link android.view.inputmethod.InputMethodManager} 9164 * when a view who is not the current 9165 * input connection target is trying to make a call on the manager. The 9166 * default implementation returns false; you can override this to return 9167 * true for certain views if you are performing InputConnection proxying 9168 * to them. 9169 * @param view The View that is making the InputMethodManager call. 9170 * @return Return true to allow the call, false to reject. 9171 */ 9172 public boolean checkInputConnectionProxy(View view) { 9173 return false; 9174 } 9175 9176 /** 9177 * Show the context menu for this view. It is not safe to hold on to the 9178 * menu after returning from this method. 9179 * 9180 * You should normally not overload this method. Overload 9181 * {@link #onCreateContextMenu(ContextMenu)} or define an 9182 * {@link OnCreateContextMenuListener} to add items to the context menu. 9183 * 9184 * @param menu The context menu to populate 9185 */ 9186 public void createContextMenu(ContextMenu menu) { 9187 ContextMenuInfo menuInfo = getContextMenuInfo(); 9188 9189 // Sets the current menu info so all items added to menu will have 9190 // my extra info set. 9191 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9192 9193 onCreateContextMenu(menu); 9194 ListenerInfo li = mListenerInfo; 9195 if (li != null && li.mOnCreateContextMenuListener != null) { 9196 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9197 } 9198 9199 // Clear the extra information so subsequent items that aren't mine don't 9200 // have my extra info. 9201 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9202 9203 if (mParent != null) { 9204 mParent.createContextMenu(menu); 9205 } 9206 } 9207 9208 /** 9209 * Views should implement this if they have extra information to associate 9210 * with the context menu. The return result is supplied as a parameter to 9211 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9212 * callback. 9213 * 9214 * @return Extra information about the item for which the context menu 9215 * should be shown. This information will vary across different 9216 * subclasses of View. 9217 */ 9218 protected ContextMenuInfo getContextMenuInfo() { 9219 return null; 9220 } 9221 9222 /** 9223 * Views should implement this if the view itself is going to add items to 9224 * the context menu. 9225 * 9226 * @param menu the context menu to populate 9227 */ 9228 protected void onCreateContextMenu(ContextMenu menu) { 9229 } 9230 9231 /** 9232 * Implement this method to handle trackball motion events. The 9233 * <em>relative</em> movement of the trackball since the last event 9234 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9235 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9236 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9237 * they will often be fractional values, representing the more fine-grained 9238 * movement information available from a trackball). 9239 * 9240 * @param event The motion event. 9241 * @return True if the event was handled, false otherwise. 9242 */ 9243 public boolean onTrackballEvent(MotionEvent event) { 9244 return false; 9245 } 9246 9247 /** 9248 * Implement this method to handle generic motion events. 9249 * <p> 9250 * Generic motion events describe joystick movements, mouse hovers, track pad 9251 * touches, scroll wheel movements and other input events. The 9252 * {@link MotionEvent#getSource() source} of the motion event specifies 9253 * the class of input that was received. Implementations of this method 9254 * must examine the bits in the source before processing the event. 9255 * The following code example shows how this is done. 9256 * </p><p> 9257 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9258 * are delivered to the view under the pointer. All other generic motion events are 9259 * delivered to the focused view. 9260 * </p> 9261 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9262 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9263 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9264 * // process the joystick movement... 9265 * return true; 9266 * } 9267 * } 9268 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9269 * switch (event.getAction()) { 9270 * case MotionEvent.ACTION_HOVER_MOVE: 9271 * // process the mouse hover movement... 9272 * return true; 9273 * case MotionEvent.ACTION_SCROLL: 9274 * // process the scroll wheel movement... 9275 * return true; 9276 * } 9277 * } 9278 * return super.onGenericMotionEvent(event); 9279 * }</pre> 9280 * 9281 * @param event The generic motion event being processed. 9282 * @return True if the event was handled, false otherwise. 9283 */ 9284 public boolean onGenericMotionEvent(MotionEvent event) { 9285 return false; 9286 } 9287 9288 /** 9289 * Implement this method to handle hover events. 9290 * <p> 9291 * This method is called whenever a pointer is hovering into, over, or out of the 9292 * bounds of a view and the view is not currently being touched. 9293 * Hover events are represented as pointer events with action 9294 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9295 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9296 * </p> 9297 * <ul> 9298 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9299 * when the pointer enters the bounds of the view.</li> 9300 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9301 * when the pointer has already entered the bounds of the view and has moved.</li> 9302 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9303 * when the pointer has exited the bounds of the view or when the pointer is 9304 * about to go down due to a button click, tap, or similar user action that 9305 * causes the view to be touched.</li> 9306 * </ul> 9307 * <p> 9308 * The view should implement this method to return true to indicate that it is 9309 * handling the hover event, such as by changing its drawable state. 9310 * </p><p> 9311 * The default implementation calls {@link #setHovered} to update the hovered state 9312 * of the view when a hover enter or hover exit event is received, if the view 9313 * is enabled and is clickable. The default implementation also sends hover 9314 * accessibility events. 9315 * </p> 9316 * 9317 * @param event The motion event that describes the hover. 9318 * @return True if the view handled the hover event. 9319 * 9320 * @see #isHovered 9321 * @see #setHovered 9322 * @see #onHoverChanged 9323 */ 9324 public boolean onHoverEvent(MotionEvent event) { 9325 // The root view may receive hover (or touch) events that are outside the bounds of 9326 // the window. This code ensures that we only send accessibility events for 9327 // hovers that are actually within the bounds of the root view. 9328 final int action = event.getActionMasked(); 9329 if (!mSendingHoverAccessibilityEvents) { 9330 if ((action == MotionEvent.ACTION_HOVER_ENTER 9331 || action == MotionEvent.ACTION_HOVER_MOVE) 9332 && !hasHoveredChild() 9333 && pointInView(event.getX(), event.getY())) { 9334 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9335 mSendingHoverAccessibilityEvents = true; 9336 } 9337 } else { 9338 if (action == MotionEvent.ACTION_HOVER_EXIT 9339 || (action == MotionEvent.ACTION_MOVE 9340 && !pointInView(event.getX(), event.getY()))) { 9341 mSendingHoverAccessibilityEvents = false; 9342 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9343 } 9344 } 9345 9346 if (isHoverable()) { 9347 switch (action) { 9348 case MotionEvent.ACTION_HOVER_ENTER: 9349 setHovered(true); 9350 break; 9351 case MotionEvent.ACTION_HOVER_EXIT: 9352 setHovered(false); 9353 break; 9354 } 9355 9356 // Dispatch the event to onGenericMotionEvent before returning true. 9357 // This is to provide compatibility with existing applications that 9358 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9359 // break because of the new default handling for hoverable views 9360 // in onHoverEvent. 9361 // Note that onGenericMotionEvent will be called by default when 9362 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9363 dispatchGenericMotionEventInternal(event); 9364 // The event was already handled by calling setHovered(), so always 9365 // return true. 9366 return true; 9367 } 9368 9369 return false; 9370 } 9371 9372 /** 9373 * Returns true if the view should handle {@link #onHoverEvent} 9374 * by calling {@link #setHovered} to change its hovered state. 9375 * 9376 * @return True if the view is hoverable. 9377 */ 9378 private boolean isHoverable() { 9379 final int viewFlags = mViewFlags; 9380 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9381 return false; 9382 } 9383 9384 return (viewFlags & CLICKABLE) == CLICKABLE 9385 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9386 } 9387 9388 /** 9389 * Returns true if the view is currently hovered. 9390 * 9391 * @return True if the view is currently hovered. 9392 * 9393 * @see #setHovered 9394 * @see #onHoverChanged 9395 */ 9396 @ViewDebug.ExportedProperty 9397 public boolean isHovered() { 9398 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9399 } 9400 9401 /** 9402 * Sets whether the view is currently hovered. 9403 * <p> 9404 * Calling this method also changes the drawable state of the view. This 9405 * enables the view to react to hover by using different drawable resources 9406 * to change its appearance. 9407 * </p><p> 9408 * The {@link #onHoverChanged} method is called when the hovered state changes. 9409 * </p> 9410 * 9411 * @param hovered True if the view is hovered. 9412 * 9413 * @see #isHovered 9414 * @see #onHoverChanged 9415 */ 9416 public void setHovered(boolean hovered) { 9417 if (hovered) { 9418 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9419 mPrivateFlags |= PFLAG_HOVERED; 9420 refreshDrawableState(); 9421 onHoverChanged(true); 9422 } 9423 } else { 9424 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9425 mPrivateFlags &= ~PFLAG_HOVERED; 9426 refreshDrawableState(); 9427 onHoverChanged(false); 9428 } 9429 } 9430 } 9431 9432 /** 9433 * Implement this method to handle hover state changes. 9434 * <p> 9435 * This method is called whenever the hover state changes as a result of a 9436 * call to {@link #setHovered}. 9437 * </p> 9438 * 9439 * @param hovered The current hover state, as returned by {@link #isHovered}. 9440 * 9441 * @see #isHovered 9442 * @see #setHovered 9443 */ 9444 public void onHoverChanged(boolean hovered) { 9445 } 9446 9447 /** 9448 * Implement this method to handle touch screen motion events. 9449 * <p> 9450 * If this method is used to detect click actions, it is recommended that 9451 * the actions be performed by implementing and calling 9452 * {@link #performClick()}. This will ensure consistent system behavior, 9453 * including: 9454 * <ul> 9455 * <li>obeying click sound preferences 9456 * <li>dispatching OnClickListener calls 9457 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9458 * accessibility features are enabled 9459 * </ul> 9460 * 9461 * @param event The motion event. 9462 * @return True if the event was handled, false otherwise. 9463 */ 9464 public boolean onTouchEvent(MotionEvent event) { 9465 final float x = event.getX(); 9466 final float y = event.getY(); 9467 final int viewFlags = mViewFlags; 9468 9469 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9470 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9471 setPressed(false); 9472 } 9473 // A disabled view that is clickable still consumes the touch 9474 // events, it just doesn't respond to them. 9475 return (((viewFlags & CLICKABLE) == CLICKABLE || 9476 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9477 } 9478 9479 if (mTouchDelegate != null) { 9480 if (mTouchDelegate.onTouchEvent(event)) { 9481 return true; 9482 } 9483 } 9484 9485 if (((viewFlags & CLICKABLE) == CLICKABLE || 9486 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9487 switch (event.getAction()) { 9488 case MotionEvent.ACTION_UP: 9489 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9490 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9491 // take focus if we don't have it already and we should in 9492 // touch mode. 9493 boolean focusTaken = false; 9494 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9495 focusTaken = requestFocus(); 9496 } 9497 9498 if (prepressed) { 9499 // The button is being released before we actually 9500 // showed it as pressed. Make it show the pressed 9501 // state now (before scheduling the click) to ensure 9502 // the user sees it. 9503 setPressed(true, x, y); 9504 } 9505 9506 if (!mHasPerformedLongPress) { 9507 // This is a tap, so remove the longpress check 9508 removeLongPressCallback(); 9509 9510 // Only perform take click actions if we were in the pressed state 9511 if (!focusTaken) { 9512 // Use a Runnable and post this rather than calling 9513 // performClick directly. This lets other visual state 9514 // of the view update before click actions start. 9515 if (mPerformClick == null) { 9516 mPerformClick = new PerformClick(); 9517 } 9518 if (!post(mPerformClick)) { 9519 performClick(); 9520 } 9521 } 9522 } 9523 9524 if (mUnsetPressedState == null) { 9525 mUnsetPressedState = new UnsetPressedState(); 9526 } 9527 9528 if (prepressed) { 9529 postDelayed(mUnsetPressedState, 9530 ViewConfiguration.getPressedStateDuration()); 9531 } else if (!post(mUnsetPressedState)) { 9532 // If the post failed, unpress right now 9533 mUnsetPressedState.run(); 9534 } 9535 9536 removeTapCallback(); 9537 } 9538 break; 9539 9540 case MotionEvent.ACTION_DOWN: 9541 mHasPerformedLongPress = false; 9542 9543 if (performButtonActionOnTouchDown(event)) { 9544 break; 9545 } 9546 9547 // Walk up the hierarchy to determine if we're inside a scrolling container. 9548 boolean isInScrollingContainer = isInScrollingContainer(); 9549 9550 // For views inside a scrolling container, delay the pressed feedback for 9551 // a short period in case this is a scroll. 9552 if (isInScrollingContainer) { 9553 mPrivateFlags |= PFLAG_PREPRESSED; 9554 if (mPendingCheckForTap == null) { 9555 mPendingCheckForTap = new CheckForTap(); 9556 } 9557 mPendingCheckForTap.x = event.getX(); 9558 mPendingCheckForTap.y = event.getY(); 9559 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9560 } else { 9561 // Not inside a scrolling container, so show the feedback right away 9562 setPressed(true, x, y); 9563 checkForLongClick(0); 9564 } 9565 break; 9566 9567 case MotionEvent.ACTION_CANCEL: 9568 setPressed(false); 9569 removeTapCallback(); 9570 removeLongPressCallback(); 9571 break; 9572 9573 case MotionEvent.ACTION_MOVE: 9574 drawableHotspotChanged(x, y); 9575 9576 // Be lenient about moving outside of buttons 9577 if (!pointInView(x, y, mTouchSlop)) { 9578 // Outside button 9579 removeTapCallback(); 9580 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9581 // Remove any future long press/tap checks 9582 removeLongPressCallback(); 9583 9584 setPressed(false); 9585 } 9586 } 9587 break; 9588 } 9589 9590 return true; 9591 } 9592 9593 return false; 9594 } 9595 9596 /** 9597 * @hide 9598 */ 9599 public boolean isInScrollingContainer() { 9600 ViewParent p = getParent(); 9601 while (p != null && p instanceof ViewGroup) { 9602 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9603 return true; 9604 } 9605 p = p.getParent(); 9606 } 9607 return false; 9608 } 9609 9610 /** 9611 * Remove the longpress detection timer. 9612 */ 9613 private void removeLongPressCallback() { 9614 if (mPendingCheckForLongPress != null) { 9615 removeCallbacks(mPendingCheckForLongPress); 9616 } 9617 } 9618 9619 /** 9620 * Remove the pending click action 9621 */ 9622 private void removePerformClickCallback() { 9623 if (mPerformClick != null) { 9624 removeCallbacks(mPerformClick); 9625 } 9626 } 9627 9628 /** 9629 * Remove the prepress detection timer. 9630 */ 9631 private void removeUnsetPressCallback() { 9632 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9633 setPressed(false); 9634 removeCallbacks(mUnsetPressedState); 9635 } 9636 } 9637 9638 /** 9639 * Remove the tap detection timer. 9640 */ 9641 private void removeTapCallback() { 9642 if (mPendingCheckForTap != null) { 9643 mPrivateFlags &= ~PFLAG_PREPRESSED; 9644 removeCallbacks(mPendingCheckForTap); 9645 } 9646 } 9647 9648 /** 9649 * Cancels a pending long press. Your subclass can use this if you 9650 * want the context menu to come up if the user presses and holds 9651 * at the same place, but you don't want it to come up if they press 9652 * and then move around enough to cause scrolling. 9653 */ 9654 public void cancelLongPress() { 9655 removeLongPressCallback(); 9656 9657 /* 9658 * The prepressed state handled by the tap callback is a display 9659 * construct, but the tap callback will post a long press callback 9660 * less its own timeout. Remove it here. 9661 */ 9662 removeTapCallback(); 9663 } 9664 9665 /** 9666 * Remove the pending callback for sending a 9667 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9668 */ 9669 private void removeSendViewScrolledAccessibilityEventCallback() { 9670 if (mSendViewScrolledAccessibilityEvent != null) { 9671 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9672 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9673 } 9674 } 9675 9676 /** 9677 * Sets the TouchDelegate for this View. 9678 */ 9679 public void setTouchDelegate(TouchDelegate delegate) { 9680 mTouchDelegate = delegate; 9681 } 9682 9683 /** 9684 * Gets the TouchDelegate for this View. 9685 */ 9686 public TouchDelegate getTouchDelegate() { 9687 return mTouchDelegate; 9688 } 9689 9690 /** 9691 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9692 * 9693 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9694 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9695 * available. This method should only be called for touch events. 9696 * 9697 * <p class="note">This api is not intended for most applications. Buffered dispatch 9698 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9699 * streams will not improve your input latency. Side effects include: increased latency, 9700 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9701 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9702 * you.</p> 9703 */ 9704 public final void requestUnbufferedDispatch(MotionEvent event) { 9705 final int action = event.getAction(); 9706 if (mAttachInfo == null 9707 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9708 || !event.isTouchEvent()) { 9709 return; 9710 } 9711 mAttachInfo.mUnbufferedDispatchRequested = true; 9712 } 9713 9714 /** 9715 * Set flags controlling behavior of this view. 9716 * 9717 * @param flags Constant indicating the value which should be set 9718 * @param mask Constant indicating the bit range that should be changed 9719 */ 9720 void setFlags(int flags, int mask) { 9721 final boolean accessibilityEnabled = 9722 AccessibilityManager.getInstance(mContext).isEnabled(); 9723 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9724 9725 int old = mViewFlags; 9726 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9727 9728 int changed = mViewFlags ^ old; 9729 if (changed == 0) { 9730 return; 9731 } 9732 int privateFlags = mPrivateFlags; 9733 9734 /* Check if the FOCUSABLE bit has changed */ 9735 if (((changed & FOCUSABLE_MASK) != 0) && 9736 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9737 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9738 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9739 /* Give up focus if we are no longer focusable */ 9740 clearFocus(); 9741 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9742 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9743 /* 9744 * Tell the view system that we are now available to take focus 9745 * if no one else already has it. 9746 */ 9747 if (mParent != null) mParent.focusableViewAvailable(this); 9748 } 9749 } 9750 9751 final int newVisibility = flags & VISIBILITY_MASK; 9752 if (newVisibility == VISIBLE) { 9753 if ((changed & VISIBILITY_MASK) != 0) { 9754 /* 9755 * If this view is becoming visible, invalidate it in case it changed while 9756 * it was not visible. Marking it drawn ensures that the invalidation will 9757 * go through. 9758 */ 9759 mPrivateFlags |= PFLAG_DRAWN; 9760 invalidate(true); 9761 9762 needGlobalAttributesUpdate(true); 9763 9764 // a view becoming visible is worth notifying the parent 9765 // about in case nothing has focus. even if this specific view 9766 // isn't focusable, it may contain something that is, so let 9767 // the root view try to give this focus if nothing else does. 9768 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9769 mParent.focusableViewAvailable(this); 9770 } 9771 } 9772 } 9773 9774 /* Check if the GONE bit has changed */ 9775 if ((changed & GONE) != 0) { 9776 needGlobalAttributesUpdate(false); 9777 requestLayout(); 9778 9779 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9780 if (hasFocus()) clearFocus(); 9781 clearAccessibilityFocus(); 9782 destroyDrawingCache(); 9783 if (mParent instanceof View) { 9784 // GONE views noop invalidation, so invalidate the parent 9785 ((View) mParent).invalidate(true); 9786 } 9787 // Mark the view drawn to ensure that it gets invalidated properly the next 9788 // time it is visible and gets invalidated 9789 mPrivateFlags |= PFLAG_DRAWN; 9790 } 9791 if (mAttachInfo != null) { 9792 mAttachInfo.mViewVisibilityChanged = true; 9793 } 9794 } 9795 9796 /* Check if the VISIBLE bit has changed */ 9797 if ((changed & INVISIBLE) != 0) { 9798 needGlobalAttributesUpdate(false); 9799 /* 9800 * If this view is becoming invisible, set the DRAWN flag so that 9801 * the next invalidate() will not be skipped. 9802 */ 9803 mPrivateFlags |= PFLAG_DRAWN; 9804 9805 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9806 // root view becoming invisible shouldn't clear focus and accessibility focus 9807 if (getRootView() != this) { 9808 if (hasFocus()) clearFocus(); 9809 clearAccessibilityFocus(); 9810 } 9811 } 9812 if (mAttachInfo != null) { 9813 mAttachInfo.mViewVisibilityChanged = true; 9814 } 9815 } 9816 9817 if ((changed & VISIBILITY_MASK) != 0) { 9818 // If the view is invisible, cleanup its display list to free up resources 9819 if (newVisibility != VISIBLE && mAttachInfo != null) { 9820 cleanupDraw(); 9821 } 9822 9823 if (mParent instanceof ViewGroup) { 9824 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9825 (changed & VISIBILITY_MASK), newVisibility); 9826 ((View) mParent).invalidate(true); 9827 } else if (mParent != null) { 9828 mParent.invalidateChild(this, null); 9829 } 9830 dispatchVisibilityChanged(this, newVisibility); 9831 9832 notifySubtreeAccessibilityStateChangedIfNeeded(); 9833 } 9834 9835 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9836 destroyDrawingCache(); 9837 } 9838 9839 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9840 destroyDrawingCache(); 9841 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9842 invalidateParentCaches(); 9843 } 9844 9845 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9846 destroyDrawingCache(); 9847 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9848 } 9849 9850 if ((changed & DRAW_MASK) != 0) { 9851 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9852 if (mBackground != null) { 9853 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9854 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9855 } else { 9856 mPrivateFlags |= PFLAG_SKIP_DRAW; 9857 } 9858 } else { 9859 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9860 } 9861 requestLayout(); 9862 invalidate(true); 9863 } 9864 9865 if ((changed & KEEP_SCREEN_ON) != 0) { 9866 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9867 mParent.recomputeViewAttributes(this); 9868 } 9869 } 9870 9871 if (accessibilityEnabled) { 9872 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9873 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9874 if (oldIncludeForAccessibility != includeForAccessibility()) { 9875 notifySubtreeAccessibilityStateChangedIfNeeded(); 9876 } else { 9877 notifyViewAccessibilityStateChangedIfNeeded( 9878 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9879 } 9880 } else if ((changed & ENABLED_MASK) != 0) { 9881 notifyViewAccessibilityStateChangedIfNeeded( 9882 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9883 } 9884 } 9885 } 9886 9887 /** 9888 * Change the view's z order in the tree, so it's on top of other sibling 9889 * views. This ordering change may affect layout, if the parent container 9890 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9891 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9892 * method should be followed by calls to {@link #requestLayout()} and 9893 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9894 * with the new child ordering. 9895 * 9896 * @see ViewGroup#bringChildToFront(View) 9897 */ 9898 public void bringToFront() { 9899 if (mParent != null) { 9900 mParent.bringChildToFront(this); 9901 } 9902 } 9903 9904 /** 9905 * This is called in response to an internal scroll in this view (i.e., the 9906 * view scrolled its own contents). This is typically as a result of 9907 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9908 * called. 9909 * 9910 * @param l Current horizontal scroll origin. 9911 * @param t Current vertical scroll origin. 9912 * @param oldl Previous horizontal scroll origin. 9913 * @param oldt Previous vertical scroll origin. 9914 */ 9915 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9916 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9917 postSendViewScrolledAccessibilityEventCallback(); 9918 } 9919 9920 mBackgroundSizeChanged = true; 9921 9922 final AttachInfo ai = mAttachInfo; 9923 if (ai != null) { 9924 ai.mViewScrollChanged = true; 9925 } 9926 9927 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 9928 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 9929 } 9930 } 9931 9932 /** 9933 * Interface definition for a callback to be invoked when the scroll 9934 * X or Y positions of a view change. 9935 * <p> 9936 * <b>Note:</b> Some views handle scrolling independently from View and may 9937 * have their own separate listeners for scroll-type events. For example, 9938 * {@link android.widget.ListView ListView} allows clients to register an 9939 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 9940 * to listen for changes in list scroll position. 9941 * 9942 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 9943 */ 9944 public interface OnScrollChangeListener { 9945 /** 9946 * Called when the scroll position of a view changes. 9947 * 9948 * @param v The view whose scroll position has changed. 9949 * @param scrollX Current horizontal scroll origin. 9950 * @param scrollY Current vertical scroll origin. 9951 * @param oldScrollX Previous horizontal scroll origin. 9952 * @param oldScrollY Previous vertical scroll origin. 9953 */ 9954 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 9955 } 9956 9957 /** 9958 * Interface definition for a callback to be invoked when the layout bounds of a view 9959 * changes due to layout processing. 9960 */ 9961 public interface OnLayoutChangeListener { 9962 /** 9963 * Called when the layout bounds of a view changes due to layout processing. 9964 * 9965 * @param v The view whose bounds have changed. 9966 * @param left The new value of the view's left property. 9967 * @param top The new value of the view's top property. 9968 * @param right The new value of the view's right property. 9969 * @param bottom The new value of the view's bottom property. 9970 * @param oldLeft The previous value of the view's left property. 9971 * @param oldTop The previous value of the view's top property. 9972 * @param oldRight The previous value of the view's right property. 9973 * @param oldBottom The previous value of the view's bottom property. 9974 */ 9975 void onLayoutChange(View v, int left, int top, int right, int bottom, 9976 int oldLeft, int oldTop, int oldRight, int oldBottom); 9977 } 9978 9979 /** 9980 * This is called during layout when the size of this view has changed. If 9981 * you were just added to the view hierarchy, you're called with the old 9982 * values of 0. 9983 * 9984 * @param w Current width of this view. 9985 * @param h Current height of this view. 9986 * @param oldw Old width of this view. 9987 * @param oldh Old height of this view. 9988 */ 9989 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9990 } 9991 9992 /** 9993 * Called by draw to draw the child views. This may be overridden 9994 * by derived classes to gain control just before its children are drawn 9995 * (but after its own view has been drawn). 9996 * @param canvas the canvas on which to draw the view 9997 */ 9998 protected void dispatchDraw(Canvas canvas) { 9999 10000 } 10001 10002 /** 10003 * Gets the parent of this view. Note that the parent is a 10004 * ViewParent and not necessarily a View. 10005 * 10006 * @return Parent of this view. 10007 */ 10008 public final ViewParent getParent() { 10009 return mParent; 10010 } 10011 10012 /** 10013 * Set the horizontal scrolled position of your view. This will cause a call to 10014 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10015 * invalidated. 10016 * @param value the x position to scroll to 10017 */ 10018 public void setScrollX(int value) { 10019 scrollTo(value, mScrollY); 10020 } 10021 10022 /** 10023 * Set the vertical scrolled position of your view. This will cause a call to 10024 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10025 * invalidated. 10026 * @param value the y position to scroll to 10027 */ 10028 public void setScrollY(int value) { 10029 scrollTo(mScrollX, value); 10030 } 10031 10032 /** 10033 * Return the scrolled left position of this view. This is the left edge of 10034 * the displayed part of your view. You do not need to draw any pixels 10035 * farther left, since those are outside of the frame of your view on 10036 * screen. 10037 * 10038 * @return The left edge of the displayed part of your view, in pixels. 10039 */ 10040 public final int getScrollX() { 10041 return mScrollX; 10042 } 10043 10044 /** 10045 * Return the scrolled top position of this view. This is the top edge of 10046 * the displayed part of your view. You do not need to draw any pixels above 10047 * it, since those are outside of the frame of your view on screen. 10048 * 10049 * @return The top edge of the displayed part of your view, in pixels. 10050 */ 10051 public final int getScrollY() { 10052 return mScrollY; 10053 } 10054 10055 /** 10056 * Return the width of the your view. 10057 * 10058 * @return The width of your view, in pixels. 10059 */ 10060 @ViewDebug.ExportedProperty(category = "layout") 10061 public final int getWidth() { 10062 return mRight - mLeft; 10063 } 10064 10065 /** 10066 * Return the height of your view. 10067 * 10068 * @return The height of your view, in pixels. 10069 */ 10070 @ViewDebug.ExportedProperty(category = "layout") 10071 public final int getHeight() { 10072 return mBottom - mTop; 10073 } 10074 10075 /** 10076 * Return the visible drawing bounds of your view. Fills in the output 10077 * rectangle with the values from getScrollX(), getScrollY(), 10078 * getWidth(), and getHeight(). These bounds do not account for any 10079 * transformation properties currently set on the view, such as 10080 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10081 * 10082 * @param outRect The (scrolled) drawing bounds of the view. 10083 */ 10084 public void getDrawingRect(Rect outRect) { 10085 outRect.left = mScrollX; 10086 outRect.top = mScrollY; 10087 outRect.right = mScrollX + (mRight - mLeft); 10088 outRect.bottom = mScrollY + (mBottom - mTop); 10089 } 10090 10091 /** 10092 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10093 * raw width component (that is the result is masked by 10094 * {@link #MEASURED_SIZE_MASK}). 10095 * 10096 * @return The raw measured width of this view. 10097 */ 10098 public final int getMeasuredWidth() { 10099 return mMeasuredWidth & MEASURED_SIZE_MASK; 10100 } 10101 10102 /** 10103 * Return the full width measurement information for this view as computed 10104 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10105 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10106 * This should be used during measurement and layout calculations only. Use 10107 * {@link #getWidth()} to see how wide a view is after layout. 10108 * 10109 * @return The measured width of this view as a bit mask. 10110 */ 10111 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10112 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10113 name = "MEASURED_STATE_TOO_SMALL"), 10114 }) 10115 public final int getMeasuredWidthAndState() { 10116 return mMeasuredWidth; 10117 } 10118 10119 /** 10120 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10121 * raw width component (that is the result is masked by 10122 * {@link #MEASURED_SIZE_MASK}). 10123 * 10124 * @return The raw measured height of this view. 10125 */ 10126 public final int getMeasuredHeight() { 10127 return mMeasuredHeight & MEASURED_SIZE_MASK; 10128 } 10129 10130 /** 10131 * Return the full height measurement information for this view as computed 10132 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10133 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10134 * This should be used during measurement and layout calculations only. Use 10135 * {@link #getHeight()} to see how wide a view is after layout. 10136 * 10137 * @return The measured width of this view as a bit mask. 10138 */ 10139 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10140 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10141 name = "MEASURED_STATE_TOO_SMALL"), 10142 }) 10143 public final int getMeasuredHeightAndState() { 10144 return mMeasuredHeight; 10145 } 10146 10147 /** 10148 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10149 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10150 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10151 * and the height component is at the shifted bits 10152 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10153 */ 10154 public final int getMeasuredState() { 10155 return (mMeasuredWidth&MEASURED_STATE_MASK) 10156 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10157 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10158 } 10159 10160 /** 10161 * The transform matrix of this view, which is calculated based on the current 10162 * rotation, scale, and pivot properties. 10163 * 10164 * @see #getRotation() 10165 * @see #getScaleX() 10166 * @see #getScaleY() 10167 * @see #getPivotX() 10168 * @see #getPivotY() 10169 * @return The current transform matrix for the view 10170 */ 10171 public Matrix getMatrix() { 10172 ensureTransformationInfo(); 10173 final Matrix matrix = mTransformationInfo.mMatrix; 10174 mRenderNode.getMatrix(matrix); 10175 return matrix; 10176 } 10177 10178 /** 10179 * Returns true if the transform matrix is the identity matrix. 10180 * Recomputes the matrix if necessary. 10181 * 10182 * @return True if the transform matrix is the identity matrix, false otherwise. 10183 */ 10184 final boolean hasIdentityMatrix() { 10185 return mRenderNode.hasIdentityMatrix(); 10186 } 10187 10188 void ensureTransformationInfo() { 10189 if (mTransformationInfo == null) { 10190 mTransformationInfo = new TransformationInfo(); 10191 } 10192 } 10193 10194 /** 10195 * Utility method to retrieve the inverse of the current mMatrix property. 10196 * We cache the matrix to avoid recalculating it when transform properties 10197 * have not changed. 10198 * 10199 * @return The inverse of the current matrix of this view. 10200 * @hide 10201 */ 10202 public final Matrix getInverseMatrix() { 10203 ensureTransformationInfo(); 10204 if (mTransformationInfo.mInverseMatrix == null) { 10205 mTransformationInfo.mInverseMatrix = new Matrix(); 10206 } 10207 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10208 mRenderNode.getInverseMatrix(matrix); 10209 return matrix; 10210 } 10211 10212 /** 10213 * Gets the distance along the Z axis from the camera to this view. 10214 * 10215 * @see #setCameraDistance(float) 10216 * 10217 * @return The distance along the Z axis. 10218 */ 10219 public float getCameraDistance() { 10220 final float dpi = mResources.getDisplayMetrics().densityDpi; 10221 return -(mRenderNode.getCameraDistance() * dpi); 10222 } 10223 10224 /** 10225 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10226 * views are drawn) from the camera to this view. The camera's distance 10227 * affects 3D transformations, for instance rotations around the X and Y 10228 * axis. If the rotationX or rotationY properties are changed and this view is 10229 * large (more than half the size of the screen), it is recommended to always 10230 * use a camera distance that's greater than the height (X axis rotation) or 10231 * the width (Y axis rotation) of this view.</p> 10232 * 10233 * <p>The distance of the camera from the view plane can have an affect on the 10234 * perspective distortion of the view when it is rotated around the x or y axis. 10235 * For example, a large distance will result in a large viewing angle, and there 10236 * will not be much perspective distortion of the view as it rotates. A short 10237 * distance may cause much more perspective distortion upon rotation, and can 10238 * also result in some drawing artifacts if the rotated view ends up partially 10239 * behind the camera (which is why the recommendation is to use a distance at 10240 * least as far as the size of the view, if the view is to be rotated.)</p> 10241 * 10242 * <p>The distance is expressed in "depth pixels." The default distance depends 10243 * on the screen density. For instance, on a medium density display, the 10244 * default distance is 1280. On a high density display, the default distance 10245 * is 1920.</p> 10246 * 10247 * <p>If you want to specify a distance that leads to visually consistent 10248 * results across various densities, use the following formula:</p> 10249 * <pre> 10250 * float scale = context.getResources().getDisplayMetrics().density; 10251 * view.setCameraDistance(distance * scale); 10252 * </pre> 10253 * 10254 * <p>The density scale factor of a high density display is 1.5, 10255 * and 1920 = 1280 * 1.5.</p> 10256 * 10257 * @param distance The distance in "depth pixels", if negative the opposite 10258 * value is used 10259 * 10260 * @see #setRotationX(float) 10261 * @see #setRotationY(float) 10262 */ 10263 public void setCameraDistance(float distance) { 10264 final float dpi = mResources.getDisplayMetrics().densityDpi; 10265 10266 invalidateViewProperty(true, false); 10267 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10268 invalidateViewProperty(false, false); 10269 10270 invalidateParentIfNeededAndWasQuickRejected(); 10271 } 10272 10273 /** 10274 * The degrees that the view is rotated around the pivot point. 10275 * 10276 * @see #setRotation(float) 10277 * @see #getPivotX() 10278 * @see #getPivotY() 10279 * 10280 * @return The degrees of rotation. 10281 */ 10282 @ViewDebug.ExportedProperty(category = "drawing") 10283 public float getRotation() { 10284 return mRenderNode.getRotation(); 10285 } 10286 10287 /** 10288 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10289 * result in clockwise rotation. 10290 * 10291 * @param rotation The degrees of rotation. 10292 * 10293 * @see #getRotation() 10294 * @see #getPivotX() 10295 * @see #getPivotY() 10296 * @see #setRotationX(float) 10297 * @see #setRotationY(float) 10298 * 10299 * @attr ref android.R.styleable#View_rotation 10300 */ 10301 public void setRotation(float rotation) { 10302 if (rotation != getRotation()) { 10303 // Double-invalidation is necessary to capture view's old and new areas 10304 invalidateViewProperty(true, false); 10305 mRenderNode.setRotation(rotation); 10306 invalidateViewProperty(false, true); 10307 10308 invalidateParentIfNeededAndWasQuickRejected(); 10309 notifySubtreeAccessibilityStateChangedIfNeeded(); 10310 } 10311 } 10312 10313 /** 10314 * The degrees that the view is rotated around the vertical axis through the pivot point. 10315 * 10316 * @see #getPivotX() 10317 * @see #getPivotY() 10318 * @see #setRotationY(float) 10319 * 10320 * @return The degrees of Y rotation. 10321 */ 10322 @ViewDebug.ExportedProperty(category = "drawing") 10323 public float getRotationY() { 10324 return mRenderNode.getRotationY(); 10325 } 10326 10327 /** 10328 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10329 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10330 * down the y axis. 10331 * 10332 * When rotating large views, it is recommended to adjust the camera distance 10333 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10334 * 10335 * @param rotationY The degrees of Y rotation. 10336 * 10337 * @see #getRotationY() 10338 * @see #getPivotX() 10339 * @see #getPivotY() 10340 * @see #setRotation(float) 10341 * @see #setRotationX(float) 10342 * @see #setCameraDistance(float) 10343 * 10344 * @attr ref android.R.styleable#View_rotationY 10345 */ 10346 public void setRotationY(float rotationY) { 10347 if (rotationY != getRotationY()) { 10348 invalidateViewProperty(true, false); 10349 mRenderNode.setRotationY(rotationY); 10350 invalidateViewProperty(false, true); 10351 10352 invalidateParentIfNeededAndWasQuickRejected(); 10353 notifySubtreeAccessibilityStateChangedIfNeeded(); 10354 } 10355 } 10356 10357 /** 10358 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10359 * 10360 * @see #getPivotX() 10361 * @see #getPivotY() 10362 * @see #setRotationX(float) 10363 * 10364 * @return The degrees of X rotation. 10365 */ 10366 @ViewDebug.ExportedProperty(category = "drawing") 10367 public float getRotationX() { 10368 return mRenderNode.getRotationX(); 10369 } 10370 10371 /** 10372 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10373 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10374 * x axis. 10375 * 10376 * When rotating large views, it is recommended to adjust the camera distance 10377 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10378 * 10379 * @param rotationX The degrees of X rotation. 10380 * 10381 * @see #getRotationX() 10382 * @see #getPivotX() 10383 * @see #getPivotY() 10384 * @see #setRotation(float) 10385 * @see #setRotationY(float) 10386 * @see #setCameraDistance(float) 10387 * 10388 * @attr ref android.R.styleable#View_rotationX 10389 */ 10390 public void setRotationX(float rotationX) { 10391 if (rotationX != getRotationX()) { 10392 invalidateViewProperty(true, false); 10393 mRenderNode.setRotationX(rotationX); 10394 invalidateViewProperty(false, true); 10395 10396 invalidateParentIfNeededAndWasQuickRejected(); 10397 notifySubtreeAccessibilityStateChangedIfNeeded(); 10398 } 10399 } 10400 10401 /** 10402 * The amount that the view is scaled in x around the pivot point, as a proportion of 10403 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10404 * 10405 * <p>By default, this is 1.0f. 10406 * 10407 * @see #getPivotX() 10408 * @see #getPivotY() 10409 * @return The scaling factor. 10410 */ 10411 @ViewDebug.ExportedProperty(category = "drawing") 10412 public float getScaleX() { 10413 return mRenderNode.getScaleX(); 10414 } 10415 10416 /** 10417 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10418 * the view's unscaled width. A value of 1 means that no scaling is applied. 10419 * 10420 * @param scaleX The scaling factor. 10421 * @see #getPivotX() 10422 * @see #getPivotY() 10423 * 10424 * @attr ref android.R.styleable#View_scaleX 10425 */ 10426 public void setScaleX(float scaleX) { 10427 if (scaleX != getScaleX()) { 10428 invalidateViewProperty(true, false); 10429 mRenderNode.setScaleX(scaleX); 10430 invalidateViewProperty(false, true); 10431 10432 invalidateParentIfNeededAndWasQuickRejected(); 10433 notifySubtreeAccessibilityStateChangedIfNeeded(); 10434 } 10435 } 10436 10437 /** 10438 * The amount that the view is scaled in y around the pivot point, as a proportion of 10439 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10440 * 10441 * <p>By default, this is 1.0f. 10442 * 10443 * @see #getPivotX() 10444 * @see #getPivotY() 10445 * @return The scaling factor. 10446 */ 10447 @ViewDebug.ExportedProperty(category = "drawing") 10448 public float getScaleY() { 10449 return mRenderNode.getScaleY(); 10450 } 10451 10452 /** 10453 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10454 * the view's unscaled width. A value of 1 means that no scaling is applied. 10455 * 10456 * @param scaleY The scaling factor. 10457 * @see #getPivotX() 10458 * @see #getPivotY() 10459 * 10460 * @attr ref android.R.styleable#View_scaleY 10461 */ 10462 public void setScaleY(float scaleY) { 10463 if (scaleY != getScaleY()) { 10464 invalidateViewProperty(true, false); 10465 mRenderNode.setScaleY(scaleY); 10466 invalidateViewProperty(false, true); 10467 10468 invalidateParentIfNeededAndWasQuickRejected(); 10469 notifySubtreeAccessibilityStateChangedIfNeeded(); 10470 } 10471 } 10472 10473 /** 10474 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10475 * and {@link #setScaleX(float) scaled}. 10476 * 10477 * @see #getRotation() 10478 * @see #getScaleX() 10479 * @see #getScaleY() 10480 * @see #getPivotY() 10481 * @return The x location of the pivot point. 10482 * 10483 * @attr ref android.R.styleable#View_transformPivotX 10484 */ 10485 @ViewDebug.ExportedProperty(category = "drawing") 10486 public float getPivotX() { 10487 return mRenderNode.getPivotX(); 10488 } 10489 10490 /** 10491 * Sets the x location of the point around which the view is 10492 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10493 * By default, the pivot point is centered on the object. 10494 * Setting this property disables this behavior and causes the view to use only the 10495 * explicitly set pivotX and pivotY values. 10496 * 10497 * @param pivotX The x location of the pivot point. 10498 * @see #getRotation() 10499 * @see #getScaleX() 10500 * @see #getScaleY() 10501 * @see #getPivotY() 10502 * 10503 * @attr ref android.R.styleable#View_transformPivotX 10504 */ 10505 public void setPivotX(float pivotX) { 10506 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10507 invalidateViewProperty(true, false); 10508 mRenderNode.setPivotX(pivotX); 10509 invalidateViewProperty(false, true); 10510 10511 invalidateParentIfNeededAndWasQuickRejected(); 10512 } 10513 } 10514 10515 /** 10516 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10517 * and {@link #setScaleY(float) scaled}. 10518 * 10519 * @see #getRotation() 10520 * @see #getScaleX() 10521 * @see #getScaleY() 10522 * @see #getPivotY() 10523 * @return The y location of the pivot point. 10524 * 10525 * @attr ref android.R.styleable#View_transformPivotY 10526 */ 10527 @ViewDebug.ExportedProperty(category = "drawing") 10528 public float getPivotY() { 10529 return mRenderNode.getPivotY(); 10530 } 10531 10532 /** 10533 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10534 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10535 * Setting this property disables this behavior and causes the view to use only the 10536 * explicitly set pivotX and pivotY values. 10537 * 10538 * @param pivotY The y location of the pivot point. 10539 * @see #getRotation() 10540 * @see #getScaleX() 10541 * @see #getScaleY() 10542 * @see #getPivotY() 10543 * 10544 * @attr ref android.R.styleable#View_transformPivotY 10545 */ 10546 public void setPivotY(float pivotY) { 10547 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10548 invalidateViewProperty(true, false); 10549 mRenderNode.setPivotY(pivotY); 10550 invalidateViewProperty(false, true); 10551 10552 invalidateParentIfNeededAndWasQuickRejected(); 10553 } 10554 } 10555 10556 /** 10557 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10558 * completely transparent and 1 means the view is completely opaque. 10559 * 10560 * <p>By default this is 1.0f. 10561 * @return The opacity of the view. 10562 */ 10563 @ViewDebug.ExportedProperty(category = "drawing") 10564 public float getAlpha() { 10565 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10566 } 10567 10568 /** 10569 * Returns whether this View has content which overlaps. 10570 * 10571 * <p>This function, intended to be overridden by specific View types, is an optimization when 10572 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10573 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10574 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10575 * directly. An example of overlapping rendering is a TextView with a background image, such as 10576 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10577 * ImageView with only the foreground image. The default implementation returns true; subclasses 10578 * should override if they have cases which can be optimized.</p> 10579 * 10580 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10581 * necessitates that a View return true if it uses the methods internally without passing the 10582 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10583 * 10584 * @return true if the content in this view might overlap, false otherwise. 10585 */ 10586 @ViewDebug.ExportedProperty(category = "drawing") 10587 public boolean hasOverlappingRendering() { 10588 return true; 10589 } 10590 10591 /** 10592 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10593 * completely transparent and 1 means the view is completely opaque.</p> 10594 * 10595 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10596 * performance implications, especially for large views. It is best to use the alpha property 10597 * sparingly and transiently, as in the case of fading animations.</p> 10598 * 10599 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10600 * strongly recommended for performance reasons to either override 10601 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10602 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10603 * 10604 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10605 * responsible for applying the opacity itself.</p> 10606 * 10607 * <p>Note that if the view is backed by a 10608 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10609 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10610 * 1.0 will supersede the alpha of the layer paint.</p> 10611 * 10612 * @param alpha The opacity of the view. 10613 * 10614 * @see #hasOverlappingRendering() 10615 * @see #setLayerType(int, android.graphics.Paint) 10616 * 10617 * @attr ref android.R.styleable#View_alpha 10618 */ 10619 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 10620 ensureTransformationInfo(); 10621 if (mTransformationInfo.mAlpha != alpha) { 10622 mTransformationInfo.mAlpha = alpha; 10623 if (onSetAlpha((int) (alpha * 255))) { 10624 mPrivateFlags |= PFLAG_ALPHA_SET; 10625 // subclass is handling alpha - don't optimize rendering cache invalidation 10626 invalidateParentCaches(); 10627 invalidate(true); 10628 } else { 10629 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10630 invalidateViewProperty(true, false); 10631 mRenderNode.setAlpha(getFinalAlpha()); 10632 notifyViewAccessibilityStateChangedIfNeeded( 10633 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10634 } 10635 } 10636 } 10637 10638 /** 10639 * Faster version of setAlpha() which performs the same steps except there are 10640 * no calls to invalidate(). The caller of this function should perform proper invalidation 10641 * on the parent and this object. The return value indicates whether the subclass handles 10642 * alpha (the return value for onSetAlpha()). 10643 * 10644 * @param alpha The new value for the alpha property 10645 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10646 * the new value for the alpha property is different from the old value 10647 */ 10648 boolean setAlphaNoInvalidation(float alpha) { 10649 ensureTransformationInfo(); 10650 if (mTransformationInfo.mAlpha != alpha) { 10651 mTransformationInfo.mAlpha = alpha; 10652 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10653 if (subclassHandlesAlpha) { 10654 mPrivateFlags |= PFLAG_ALPHA_SET; 10655 return true; 10656 } else { 10657 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10658 mRenderNode.setAlpha(getFinalAlpha()); 10659 } 10660 } 10661 return false; 10662 } 10663 10664 /** 10665 * This property is hidden and intended only for use by the Fade transition, which 10666 * animates it to produce a visual translucency that does not side-effect (or get 10667 * affected by) the real alpha property. This value is composited with the other 10668 * alpha value (and the AlphaAnimation value, when that is present) to produce 10669 * a final visual translucency result, which is what is passed into the DisplayList. 10670 * 10671 * @hide 10672 */ 10673 public void setTransitionAlpha(float alpha) { 10674 ensureTransformationInfo(); 10675 if (mTransformationInfo.mTransitionAlpha != alpha) { 10676 mTransformationInfo.mTransitionAlpha = alpha; 10677 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10678 invalidateViewProperty(true, false); 10679 mRenderNode.setAlpha(getFinalAlpha()); 10680 } 10681 } 10682 10683 /** 10684 * Calculates the visual alpha of this view, which is a combination of the actual 10685 * alpha value and the transitionAlpha value (if set). 10686 */ 10687 private float getFinalAlpha() { 10688 if (mTransformationInfo != null) { 10689 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10690 } 10691 return 1; 10692 } 10693 10694 /** 10695 * This property is hidden and intended only for use by the Fade transition, which 10696 * animates it to produce a visual translucency that does not side-effect (or get 10697 * affected by) the real alpha property. This value is composited with the other 10698 * alpha value (and the AlphaAnimation value, when that is present) to produce 10699 * a final visual translucency result, which is what is passed into the DisplayList. 10700 * 10701 * @hide 10702 */ 10703 @ViewDebug.ExportedProperty(category = "drawing") 10704 public float getTransitionAlpha() { 10705 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10706 } 10707 10708 /** 10709 * Top position of this view relative to its parent. 10710 * 10711 * @return The top of this view, in pixels. 10712 */ 10713 @ViewDebug.CapturedViewProperty 10714 public final int getTop() { 10715 return mTop; 10716 } 10717 10718 /** 10719 * Sets the top position of this view relative to its parent. This method is meant to be called 10720 * by the layout system and should not generally be called otherwise, because the property 10721 * may be changed at any time by the layout. 10722 * 10723 * @param top The top of this view, in pixels. 10724 */ 10725 public final void setTop(int top) { 10726 if (top != mTop) { 10727 final boolean matrixIsIdentity = hasIdentityMatrix(); 10728 if (matrixIsIdentity) { 10729 if (mAttachInfo != null) { 10730 int minTop; 10731 int yLoc; 10732 if (top < mTop) { 10733 minTop = top; 10734 yLoc = top - mTop; 10735 } else { 10736 minTop = mTop; 10737 yLoc = 0; 10738 } 10739 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10740 } 10741 } else { 10742 // Double-invalidation is necessary to capture view's old and new areas 10743 invalidate(true); 10744 } 10745 10746 int width = mRight - mLeft; 10747 int oldHeight = mBottom - mTop; 10748 10749 mTop = top; 10750 mRenderNode.setTop(mTop); 10751 10752 sizeChange(width, mBottom - mTop, width, oldHeight); 10753 10754 if (!matrixIsIdentity) { 10755 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10756 invalidate(true); 10757 } 10758 mBackgroundSizeChanged = true; 10759 invalidateParentIfNeeded(); 10760 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10761 // View was rejected last time it was drawn by its parent; this may have changed 10762 invalidateParentIfNeeded(); 10763 } 10764 } 10765 } 10766 10767 /** 10768 * Bottom position of this view relative to its parent. 10769 * 10770 * @return The bottom of this view, in pixels. 10771 */ 10772 @ViewDebug.CapturedViewProperty 10773 public final int getBottom() { 10774 return mBottom; 10775 } 10776 10777 /** 10778 * True if this view has changed since the last time being drawn. 10779 * 10780 * @return The dirty state of this view. 10781 */ 10782 public boolean isDirty() { 10783 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10784 } 10785 10786 /** 10787 * Sets the bottom position of this view relative to its parent. This method is meant to be 10788 * called by the layout system and should not generally be called otherwise, because the 10789 * property may be changed at any time by the layout. 10790 * 10791 * @param bottom The bottom of this view, in pixels. 10792 */ 10793 public final void setBottom(int bottom) { 10794 if (bottom != mBottom) { 10795 final boolean matrixIsIdentity = hasIdentityMatrix(); 10796 if (matrixIsIdentity) { 10797 if (mAttachInfo != null) { 10798 int maxBottom; 10799 if (bottom < mBottom) { 10800 maxBottom = mBottom; 10801 } else { 10802 maxBottom = bottom; 10803 } 10804 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10805 } 10806 } else { 10807 // Double-invalidation is necessary to capture view's old and new areas 10808 invalidate(true); 10809 } 10810 10811 int width = mRight - mLeft; 10812 int oldHeight = mBottom - mTop; 10813 10814 mBottom = bottom; 10815 mRenderNode.setBottom(mBottom); 10816 10817 sizeChange(width, mBottom - mTop, width, oldHeight); 10818 10819 if (!matrixIsIdentity) { 10820 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10821 invalidate(true); 10822 } 10823 mBackgroundSizeChanged = true; 10824 invalidateParentIfNeeded(); 10825 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10826 // View was rejected last time it was drawn by its parent; this may have changed 10827 invalidateParentIfNeeded(); 10828 } 10829 } 10830 } 10831 10832 /** 10833 * Left position of this view relative to its parent. 10834 * 10835 * @return The left edge of this view, in pixels. 10836 */ 10837 @ViewDebug.CapturedViewProperty 10838 public final int getLeft() { 10839 return mLeft; 10840 } 10841 10842 /** 10843 * Sets the left position of this view relative to its parent. This method is meant to be called 10844 * by the layout system and should not generally be called otherwise, because the property 10845 * may be changed at any time by the layout. 10846 * 10847 * @param left The left of this view, in pixels. 10848 */ 10849 public final void setLeft(int left) { 10850 if (left != mLeft) { 10851 final boolean matrixIsIdentity = hasIdentityMatrix(); 10852 if (matrixIsIdentity) { 10853 if (mAttachInfo != null) { 10854 int minLeft; 10855 int xLoc; 10856 if (left < mLeft) { 10857 minLeft = left; 10858 xLoc = left - mLeft; 10859 } else { 10860 minLeft = mLeft; 10861 xLoc = 0; 10862 } 10863 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10864 } 10865 } else { 10866 // Double-invalidation is necessary to capture view's old and new areas 10867 invalidate(true); 10868 } 10869 10870 int oldWidth = mRight - mLeft; 10871 int height = mBottom - mTop; 10872 10873 mLeft = left; 10874 mRenderNode.setLeft(left); 10875 10876 sizeChange(mRight - mLeft, height, oldWidth, height); 10877 10878 if (!matrixIsIdentity) { 10879 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10880 invalidate(true); 10881 } 10882 mBackgroundSizeChanged = true; 10883 invalidateParentIfNeeded(); 10884 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10885 // View was rejected last time it was drawn by its parent; this may have changed 10886 invalidateParentIfNeeded(); 10887 } 10888 } 10889 } 10890 10891 /** 10892 * Right position of this view relative to its parent. 10893 * 10894 * @return The right edge of this view, in pixels. 10895 */ 10896 @ViewDebug.CapturedViewProperty 10897 public final int getRight() { 10898 return mRight; 10899 } 10900 10901 /** 10902 * Sets the right position of this view relative to its parent. This method is meant to be called 10903 * by the layout system and should not generally be called otherwise, because the property 10904 * may be changed at any time by the layout. 10905 * 10906 * @param right The right of this view, in pixels. 10907 */ 10908 public final void setRight(int right) { 10909 if (right != mRight) { 10910 final boolean matrixIsIdentity = hasIdentityMatrix(); 10911 if (matrixIsIdentity) { 10912 if (mAttachInfo != null) { 10913 int maxRight; 10914 if (right < mRight) { 10915 maxRight = mRight; 10916 } else { 10917 maxRight = right; 10918 } 10919 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10920 } 10921 } else { 10922 // Double-invalidation is necessary to capture view's old and new areas 10923 invalidate(true); 10924 } 10925 10926 int oldWidth = mRight - mLeft; 10927 int height = mBottom - mTop; 10928 10929 mRight = right; 10930 mRenderNode.setRight(mRight); 10931 10932 sizeChange(mRight - mLeft, height, oldWidth, height); 10933 10934 if (!matrixIsIdentity) { 10935 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10936 invalidate(true); 10937 } 10938 mBackgroundSizeChanged = true; 10939 invalidateParentIfNeeded(); 10940 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10941 // View was rejected last time it was drawn by its parent; this may have changed 10942 invalidateParentIfNeeded(); 10943 } 10944 } 10945 } 10946 10947 /** 10948 * The visual x position of this view, in pixels. This is equivalent to the 10949 * {@link #setTranslationX(float) translationX} property plus the current 10950 * {@link #getLeft() left} property. 10951 * 10952 * @return The visual x position of this view, in pixels. 10953 */ 10954 @ViewDebug.ExportedProperty(category = "drawing") 10955 public float getX() { 10956 return mLeft + getTranslationX(); 10957 } 10958 10959 /** 10960 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10961 * {@link #setTranslationX(float) translationX} property to be the difference between 10962 * the x value passed in and the current {@link #getLeft() left} property. 10963 * 10964 * @param x The visual x position of this view, in pixels. 10965 */ 10966 public void setX(float x) { 10967 setTranslationX(x - mLeft); 10968 } 10969 10970 /** 10971 * The visual y position of this view, in pixels. This is equivalent to the 10972 * {@link #setTranslationY(float) translationY} property plus the current 10973 * {@link #getTop() top} property. 10974 * 10975 * @return The visual y position of this view, in pixels. 10976 */ 10977 @ViewDebug.ExportedProperty(category = "drawing") 10978 public float getY() { 10979 return mTop + getTranslationY(); 10980 } 10981 10982 /** 10983 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10984 * {@link #setTranslationY(float) translationY} property to be the difference between 10985 * the y value passed in and the current {@link #getTop() top} property. 10986 * 10987 * @param y The visual y position of this view, in pixels. 10988 */ 10989 public void setY(float y) { 10990 setTranslationY(y - mTop); 10991 } 10992 10993 /** 10994 * The visual z position of this view, in pixels. This is equivalent to the 10995 * {@link #setTranslationZ(float) translationZ} property plus the current 10996 * {@link #getElevation() elevation} property. 10997 * 10998 * @return The visual z position of this view, in pixels. 10999 */ 11000 @ViewDebug.ExportedProperty(category = "drawing") 11001 public float getZ() { 11002 return getElevation() + getTranslationZ(); 11003 } 11004 11005 /** 11006 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11007 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11008 * the x value passed in and the current {@link #getElevation() elevation} property. 11009 * 11010 * @param z The visual z position of this view, in pixels. 11011 */ 11012 public void setZ(float z) { 11013 setTranslationZ(z - getElevation()); 11014 } 11015 11016 /** 11017 * The base elevation of this view relative to its parent, in pixels. 11018 * 11019 * @return The base depth position of the view, in pixels. 11020 */ 11021 @ViewDebug.ExportedProperty(category = "drawing") 11022 public float getElevation() { 11023 return mRenderNode.getElevation(); 11024 } 11025 11026 /** 11027 * Sets the base elevation of this view, in pixels. 11028 * 11029 * @attr ref android.R.styleable#View_elevation 11030 */ 11031 public void setElevation(float elevation) { 11032 if (elevation != getElevation()) { 11033 invalidateViewProperty(true, false); 11034 mRenderNode.setElevation(elevation); 11035 invalidateViewProperty(false, true); 11036 11037 invalidateParentIfNeededAndWasQuickRejected(); 11038 } 11039 } 11040 11041 /** 11042 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11043 * This position is post-layout, in addition to wherever the object's 11044 * layout placed it. 11045 * 11046 * @return The horizontal position of this view relative to its left position, in pixels. 11047 */ 11048 @ViewDebug.ExportedProperty(category = "drawing") 11049 public float getTranslationX() { 11050 return mRenderNode.getTranslationX(); 11051 } 11052 11053 /** 11054 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11055 * This effectively positions the object post-layout, in addition to wherever the object's 11056 * layout placed it. 11057 * 11058 * @param translationX The horizontal position of this view relative to its left position, 11059 * in pixels. 11060 * 11061 * @attr ref android.R.styleable#View_translationX 11062 */ 11063 public void setTranslationX(float translationX) { 11064 if (translationX != getTranslationX()) { 11065 invalidateViewProperty(true, false); 11066 mRenderNode.setTranslationX(translationX); 11067 invalidateViewProperty(false, true); 11068 11069 invalidateParentIfNeededAndWasQuickRejected(); 11070 notifySubtreeAccessibilityStateChangedIfNeeded(); 11071 } 11072 } 11073 11074 /** 11075 * The vertical location of this view relative to its {@link #getTop() top} position. 11076 * This position is post-layout, in addition to wherever the object's 11077 * layout placed it. 11078 * 11079 * @return The vertical position of this view relative to its top position, 11080 * in pixels. 11081 */ 11082 @ViewDebug.ExportedProperty(category = "drawing") 11083 public float getTranslationY() { 11084 return mRenderNode.getTranslationY(); 11085 } 11086 11087 /** 11088 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11089 * This effectively positions the object post-layout, in addition to wherever the object's 11090 * layout placed it. 11091 * 11092 * @param translationY The vertical position of this view relative to its top position, 11093 * in pixels. 11094 * 11095 * @attr ref android.R.styleable#View_translationY 11096 */ 11097 public void setTranslationY(float translationY) { 11098 if (translationY != getTranslationY()) { 11099 invalidateViewProperty(true, false); 11100 mRenderNode.setTranslationY(translationY); 11101 invalidateViewProperty(false, true); 11102 11103 invalidateParentIfNeededAndWasQuickRejected(); 11104 } 11105 } 11106 11107 /** 11108 * The depth location of this view relative to its {@link #getElevation() elevation}. 11109 * 11110 * @return The depth of this view relative to its elevation. 11111 */ 11112 @ViewDebug.ExportedProperty(category = "drawing") 11113 public float getTranslationZ() { 11114 return mRenderNode.getTranslationZ(); 11115 } 11116 11117 /** 11118 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11119 * 11120 * @attr ref android.R.styleable#View_translationZ 11121 */ 11122 public void setTranslationZ(float translationZ) { 11123 if (translationZ != getTranslationZ()) { 11124 invalidateViewProperty(true, false); 11125 mRenderNode.setTranslationZ(translationZ); 11126 invalidateViewProperty(false, true); 11127 11128 invalidateParentIfNeededAndWasQuickRejected(); 11129 } 11130 } 11131 11132 /** @hide */ 11133 public void setAnimationMatrix(Matrix matrix) { 11134 invalidateViewProperty(true, false); 11135 mRenderNode.setAnimationMatrix(matrix); 11136 invalidateViewProperty(false, true); 11137 11138 invalidateParentIfNeededAndWasQuickRejected(); 11139 } 11140 11141 /** 11142 * Returns the current StateListAnimator if exists. 11143 * 11144 * @return StateListAnimator or null if it does not exists 11145 * @see #setStateListAnimator(android.animation.StateListAnimator) 11146 */ 11147 public StateListAnimator getStateListAnimator() { 11148 return mStateListAnimator; 11149 } 11150 11151 /** 11152 * Attaches the provided StateListAnimator to this View. 11153 * <p> 11154 * Any previously attached StateListAnimator will be detached. 11155 * 11156 * @param stateListAnimator The StateListAnimator to update the view 11157 * @see {@link android.animation.StateListAnimator} 11158 */ 11159 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11160 if (mStateListAnimator == stateListAnimator) { 11161 return; 11162 } 11163 if (mStateListAnimator != null) { 11164 mStateListAnimator.setTarget(null); 11165 } 11166 mStateListAnimator = stateListAnimator; 11167 if (stateListAnimator != null) { 11168 stateListAnimator.setTarget(this); 11169 if (isAttachedToWindow()) { 11170 stateListAnimator.setState(getDrawableState()); 11171 } 11172 } 11173 } 11174 11175 /** 11176 * Returns whether the Outline should be used to clip the contents of the View. 11177 * <p> 11178 * Note that this flag will only be respected if the View's Outline returns true from 11179 * {@link Outline#canClip()}. 11180 * 11181 * @see #setOutlineProvider(ViewOutlineProvider) 11182 * @see #setClipToOutline(boolean) 11183 */ 11184 public final boolean getClipToOutline() { 11185 return mRenderNode.getClipToOutline(); 11186 } 11187 11188 /** 11189 * Sets whether the View's Outline should be used to clip the contents of the View. 11190 * <p> 11191 * Only a single non-rectangular clip can be applied on a View at any time. 11192 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11193 * circular reveal} animation take priority over Outline clipping, and 11194 * child Outline clipping takes priority over Outline clipping done by a 11195 * parent. 11196 * <p> 11197 * Note that this flag will only be respected if the View's Outline returns true from 11198 * {@link Outline#canClip()}. 11199 * 11200 * @see #setOutlineProvider(ViewOutlineProvider) 11201 * @see #getClipToOutline() 11202 */ 11203 public void setClipToOutline(boolean clipToOutline) { 11204 damageInParent(); 11205 if (getClipToOutline() != clipToOutline) { 11206 mRenderNode.setClipToOutline(clipToOutline); 11207 } 11208 } 11209 11210 // correspond to the enum values of View_outlineProvider 11211 private static final int PROVIDER_BACKGROUND = 0; 11212 private static final int PROVIDER_NONE = 1; 11213 private static final int PROVIDER_BOUNDS = 2; 11214 private static final int PROVIDER_PADDED_BOUNDS = 3; 11215 private void setOutlineProviderFromAttribute(int providerInt) { 11216 switch (providerInt) { 11217 case PROVIDER_BACKGROUND: 11218 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11219 break; 11220 case PROVIDER_NONE: 11221 setOutlineProvider(null); 11222 break; 11223 case PROVIDER_BOUNDS: 11224 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11225 break; 11226 case PROVIDER_PADDED_BOUNDS: 11227 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11228 break; 11229 } 11230 } 11231 11232 /** 11233 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11234 * the shape of the shadow it casts, and enables outline clipping. 11235 * <p> 11236 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11237 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11238 * outline provider with this method allows this behavior to be overridden. 11239 * <p> 11240 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11241 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11242 * <p> 11243 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11244 * 11245 * @see #setClipToOutline(boolean) 11246 * @see #getClipToOutline() 11247 * @see #getOutlineProvider() 11248 */ 11249 public void setOutlineProvider(ViewOutlineProvider provider) { 11250 mOutlineProvider = provider; 11251 invalidateOutline(); 11252 } 11253 11254 /** 11255 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11256 * that defines the shape of the shadow it casts, and enables outline clipping. 11257 * 11258 * @see #setOutlineProvider(ViewOutlineProvider) 11259 */ 11260 public ViewOutlineProvider getOutlineProvider() { 11261 return mOutlineProvider; 11262 } 11263 11264 /** 11265 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11266 * 11267 * @see #setOutlineProvider(ViewOutlineProvider) 11268 */ 11269 public void invalidateOutline() { 11270 rebuildOutline(); 11271 11272 notifySubtreeAccessibilityStateChangedIfNeeded(); 11273 invalidateViewProperty(false, false); 11274 } 11275 11276 /** 11277 * Internal version of {@link #invalidateOutline()} which invalidates the 11278 * outline without invalidating the view itself. This is intended to be called from 11279 * within methods in the View class itself which are the result of the view being 11280 * invalidated already. For example, when we are drawing the background of a View, 11281 * we invalidate the outline in case it changed in the meantime, but we do not 11282 * need to invalidate the view because we're already drawing the background as part 11283 * of drawing the view in response to an earlier invalidation of the view. 11284 */ 11285 private void rebuildOutline() { 11286 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11287 if (mAttachInfo == null) return; 11288 11289 if (mOutlineProvider == null) { 11290 // no provider, remove outline 11291 mRenderNode.setOutline(null); 11292 } else { 11293 final Outline outline = mAttachInfo.mTmpOutline; 11294 outline.setEmpty(); 11295 outline.setAlpha(1.0f); 11296 11297 mOutlineProvider.getOutline(this, outline); 11298 mRenderNode.setOutline(outline); 11299 } 11300 } 11301 11302 /** 11303 * HierarchyViewer only 11304 * 11305 * @hide 11306 */ 11307 @ViewDebug.ExportedProperty(category = "drawing") 11308 public boolean hasShadow() { 11309 return mRenderNode.hasShadow(); 11310 } 11311 11312 11313 /** @hide */ 11314 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11315 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11316 invalidateViewProperty(false, false); 11317 } 11318 11319 /** 11320 * Hit rectangle in parent's coordinates 11321 * 11322 * @param outRect The hit rectangle of the view. 11323 */ 11324 public void getHitRect(Rect outRect) { 11325 if (hasIdentityMatrix() || mAttachInfo == null) { 11326 outRect.set(mLeft, mTop, mRight, mBottom); 11327 } else { 11328 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11329 tmpRect.set(0, 0, getWidth(), getHeight()); 11330 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11331 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11332 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11333 } 11334 } 11335 11336 /** 11337 * Determines whether the given point, in local coordinates is inside the view. 11338 */ 11339 /*package*/ final boolean pointInView(float localX, float localY) { 11340 return localX >= 0 && localX < (mRight - mLeft) 11341 && localY >= 0 && localY < (mBottom - mTop); 11342 } 11343 11344 /** 11345 * Utility method to determine whether the given point, in local coordinates, 11346 * is inside the view, where the area of the view is expanded by the slop factor. 11347 * This method is called while processing touch-move events to determine if the event 11348 * is still within the view. 11349 * 11350 * @hide 11351 */ 11352 public boolean pointInView(float localX, float localY, float slop) { 11353 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11354 localY < ((mBottom - mTop) + slop); 11355 } 11356 11357 /** 11358 * When a view has focus and the user navigates away from it, the next view is searched for 11359 * starting from the rectangle filled in by this method. 11360 * 11361 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11362 * of the view. However, if your view maintains some idea of internal selection, 11363 * such as a cursor, or a selected row or column, you should override this method and 11364 * fill in a more specific rectangle. 11365 * 11366 * @param r The rectangle to fill in, in this view's coordinates. 11367 */ 11368 public void getFocusedRect(Rect r) { 11369 getDrawingRect(r); 11370 } 11371 11372 /** 11373 * If some part of this view is not clipped by any of its parents, then 11374 * return that area in r in global (root) coordinates. To convert r to local 11375 * coordinates (without taking possible View rotations into account), offset 11376 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11377 * If the view is completely clipped or translated out, return false. 11378 * 11379 * @param r If true is returned, r holds the global coordinates of the 11380 * visible portion of this view. 11381 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11382 * between this view and its root. globalOffet may be null. 11383 * @return true if r is non-empty (i.e. part of the view is visible at the 11384 * root level. 11385 */ 11386 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11387 int width = mRight - mLeft; 11388 int height = mBottom - mTop; 11389 if (width > 0 && height > 0) { 11390 r.set(0, 0, width, height); 11391 if (globalOffset != null) { 11392 globalOffset.set(-mScrollX, -mScrollY); 11393 } 11394 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11395 } 11396 return false; 11397 } 11398 11399 public final boolean getGlobalVisibleRect(Rect r) { 11400 return getGlobalVisibleRect(r, null); 11401 } 11402 11403 public final boolean getLocalVisibleRect(Rect r) { 11404 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11405 if (getGlobalVisibleRect(r, offset)) { 11406 r.offset(-offset.x, -offset.y); // make r local 11407 return true; 11408 } 11409 return false; 11410 } 11411 11412 /** 11413 * Offset this view's vertical location by the specified number of pixels. 11414 * 11415 * @param offset the number of pixels to offset the view by 11416 */ 11417 public void offsetTopAndBottom(int offset) { 11418 if (offset != 0) { 11419 final boolean matrixIsIdentity = hasIdentityMatrix(); 11420 if (matrixIsIdentity) { 11421 if (isHardwareAccelerated()) { 11422 invalidateViewProperty(false, false); 11423 } else { 11424 final ViewParent p = mParent; 11425 if (p != null && mAttachInfo != null) { 11426 final Rect r = mAttachInfo.mTmpInvalRect; 11427 int minTop; 11428 int maxBottom; 11429 int yLoc; 11430 if (offset < 0) { 11431 minTop = mTop + offset; 11432 maxBottom = mBottom; 11433 yLoc = offset; 11434 } else { 11435 minTop = mTop; 11436 maxBottom = mBottom + offset; 11437 yLoc = 0; 11438 } 11439 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11440 p.invalidateChild(this, r); 11441 } 11442 } 11443 } else { 11444 invalidateViewProperty(false, false); 11445 } 11446 11447 mTop += offset; 11448 mBottom += offset; 11449 mRenderNode.offsetTopAndBottom(offset); 11450 if (isHardwareAccelerated()) { 11451 invalidateViewProperty(false, false); 11452 } else { 11453 if (!matrixIsIdentity) { 11454 invalidateViewProperty(false, true); 11455 } 11456 invalidateParentIfNeeded(); 11457 } 11458 notifySubtreeAccessibilityStateChangedIfNeeded(); 11459 } 11460 } 11461 11462 /** 11463 * Offset this view's horizontal location by the specified amount of pixels. 11464 * 11465 * @param offset the number of pixels to offset the view by 11466 */ 11467 public void offsetLeftAndRight(int offset) { 11468 if (offset != 0) { 11469 final boolean matrixIsIdentity = hasIdentityMatrix(); 11470 if (matrixIsIdentity) { 11471 if (isHardwareAccelerated()) { 11472 invalidateViewProperty(false, false); 11473 } else { 11474 final ViewParent p = mParent; 11475 if (p != null && mAttachInfo != null) { 11476 final Rect r = mAttachInfo.mTmpInvalRect; 11477 int minLeft; 11478 int maxRight; 11479 if (offset < 0) { 11480 minLeft = mLeft + offset; 11481 maxRight = mRight; 11482 } else { 11483 minLeft = mLeft; 11484 maxRight = mRight + offset; 11485 } 11486 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11487 p.invalidateChild(this, r); 11488 } 11489 } 11490 } else { 11491 invalidateViewProperty(false, false); 11492 } 11493 11494 mLeft += offset; 11495 mRight += offset; 11496 mRenderNode.offsetLeftAndRight(offset); 11497 if (isHardwareAccelerated()) { 11498 invalidateViewProperty(false, false); 11499 } else { 11500 if (!matrixIsIdentity) { 11501 invalidateViewProperty(false, true); 11502 } 11503 invalidateParentIfNeeded(); 11504 } 11505 notifySubtreeAccessibilityStateChangedIfNeeded(); 11506 } 11507 } 11508 11509 /** 11510 * Get the LayoutParams associated with this view. All views should have 11511 * layout parameters. These supply parameters to the <i>parent</i> of this 11512 * view specifying how it should be arranged. There are many subclasses of 11513 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11514 * of ViewGroup that are responsible for arranging their children. 11515 * 11516 * This method may return null if this View is not attached to a parent 11517 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11518 * was not invoked successfully. When a View is attached to a parent 11519 * ViewGroup, this method must not return null. 11520 * 11521 * @return The LayoutParams associated with this view, or null if no 11522 * parameters have been set yet 11523 */ 11524 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11525 public ViewGroup.LayoutParams getLayoutParams() { 11526 return mLayoutParams; 11527 } 11528 11529 /** 11530 * Set the layout parameters associated with this view. These supply 11531 * parameters to the <i>parent</i> of this view specifying how it should be 11532 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11533 * correspond to the different subclasses of ViewGroup that are responsible 11534 * for arranging their children. 11535 * 11536 * @param params The layout parameters for this view, cannot be null 11537 */ 11538 public void setLayoutParams(ViewGroup.LayoutParams params) { 11539 if (params == null) { 11540 throw new NullPointerException("Layout parameters cannot be null"); 11541 } 11542 mLayoutParams = params; 11543 resolveLayoutParams(); 11544 if (mParent instanceof ViewGroup) { 11545 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11546 } 11547 requestLayout(); 11548 } 11549 11550 /** 11551 * Resolve the layout parameters depending on the resolved layout direction 11552 * 11553 * @hide 11554 */ 11555 public void resolveLayoutParams() { 11556 if (mLayoutParams != null) { 11557 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11558 } 11559 } 11560 11561 /** 11562 * Set the scrolled position of your view. This will cause a call to 11563 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11564 * invalidated. 11565 * @param x the x position to scroll to 11566 * @param y the y position to scroll to 11567 */ 11568 public void scrollTo(int x, int y) { 11569 if (mScrollX != x || mScrollY != y) { 11570 int oldX = mScrollX; 11571 int oldY = mScrollY; 11572 mScrollX = x; 11573 mScrollY = y; 11574 invalidateParentCaches(); 11575 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11576 if (!awakenScrollBars()) { 11577 postInvalidateOnAnimation(); 11578 } 11579 } 11580 } 11581 11582 /** 11583 * Move the scrolled position of your view. This will cause a call to 11584 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11585 * invalidated. 11586 * @param x the amount of pixels to scroll by horizontally 11587 * @param y the amount of pixels to scroll by vertically 11588 */ 11589 public void scrollBy(int x, int y) { 11590 scrollTo(mScrollX + x, mScrollY + y); 11591 } 11592 11593 /** 11594 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11595 * animation to fade the scrollbars out after a default delay. If a subclass 11596 * provides animated scrolling, the start delay should equal the duration 11597 * of the scrolling animation.</p> 11598 * 11599 * <p>The animation starts only if at least one of the scrollbars is 11600 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11601 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11602 * this method returns true, and false otherwise. If the animation is 11603 * started, this method calls {@link #invalidate()}; in that case the 11604 * caller should not call {@link #invalidate()}.</p> 11605 * 11606 * <p>This method should be invoked every time a subclass directly updates 11607 * the scroll parameters.</p> 11608 * 11609 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11610 * and {@link #scrollTo(int, int)}.</p> 11611 * 11612 * @return true if the animation is played, false otherwise 11613 * 11614 * @see #awakenScrollBars(int) 11615 * @see #scrollBy(int, int) 11616 * @see #scrollTo(int, int) 11617 * @see #isHorizontalScrollBarEnabled() 11618 * @see #isVerticalScrollBarEnabled() 11619 * @see #setHorizontalScrollBarEnabled(boolean) 11620 * @see #setVerticalScrollBarEnabled(boolean) 11621 */ 11622 protected boolean awakenScrollBars() { 11623 return mScrollCache != null && 11624 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11625 } 11626 11627 /** 11628 * Trigger the scrollbars to draw. 11629 * This method differs from awakenScrollBars() only in its default duration. 11630 * initialAwakenScrollBars() will show the scroll bars for longer than 11631 * usual to give the user more of a chance to notice them. 11632 * 11633 * @return true if the animation is played, false otherwise. 11634 */ 11635 private boolean initialAwakenScrollBars() { 11636 return mScrollCache != null && 11637 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11638 } 11639 11640 /** 11641 * <p> 11642 * Trigger the scrollbars to draw. When invoked this method starts an 11643 * animation to fade the scrollbars out after a fixed delay. If a subclass 11644 * provides animated scrolling, the start delay should equal the duration of 11645 * the scrolling animation. 11646 * </p> 11647 * 11648 * <p> 11649 * The animation starts only if at least one of the scrollbars is enabled, 11650 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11651 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11652 * this method returns true, and false otherwise. If the animation is 11653 * started, this method calls {@link #invalidate()}; in that case the caller 11654 * should not call {@link #invalidate()}. 11655 * </p> 11656 * 11657 * <p> 11658 * This method should be invoked every time a subclass directly updates the 11659 * scroll parameters. 11660 * </p> 11661 * 11662 * @param startDelay the delay, in milliseconds, after which the animation 11663 * should start; when the delay is 0, the animation starts 11664 * immediately 11665 * @return true if the animation is played, false otherwise 11666 * 11667 * @see #scrollBy(int, int) 11668 * @see #scrollTo(int, int) 11669 * @see #isHorizontalScrollBarEnabled() 11670 * @see #isVerticalScrollBarEnabled() 11671 * @see #setHorizontalScrollBarEnabled(boolean) 11672 * @see #setVerticalScrollBarEnabled(boolean) 11673 */ 11674 protected boolean awakenScrollBars(int startDelay) { 11675 return awakenScrollBars(startDelay, true); 11676 } 11677 11678 /** 11679 * <p> 11680 * Trigger the scrollbars to draw. When invoked this method starts an 11681 * animation to fade the scrollbars out after a fixed delay. If a subclass 11682 * provides animated scrolling, the start delay should equal the duration of 11683 * the scrolling animation. 11684 * </p> 11685 * 11686 * <p> 11687 * The animation starts only if at least one of the scrollbars is enabled, 11688 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11689 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11690 * this method returns true, and false otherwise. If the animation is 11691 * started, this method calls {@link #invalidate()} if the invalidate parameter 11692 * is set to true; in that case the caller 11693 * should not call {@link #invalidate()}. 11694 * </p> 11695 * 11696 * <p> 11697 * This method should be invoked every time a subclass directly updates the 11698 * scroll parameters. 11699 * </p> 11700 * 11701 * @param startDelay the delay, in milliseconds, after which the animation 11702 * should start; when the delay is 0, the animation starts 11703 * immediately 11704 * 11705 * @param invalidate Whether this method should call invalidate 11706 * 11707 * @return true if the animation is played, false otherwise 11708 * 11709 * @see #scrollBy(int, int) 11710 * @see #scrollTo(int, int) 11711 * @see #isHorizontalScrollBarEnabled() 11712 * @see #isVerticalScrollBarEnabled() 11713 * @see #setHorizontalScrollBarEnabled(boolean) 11714 * @see #setVerticalScrollBarEnabled(boolean) 11715 */ 11716 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11717 final ScrollabilityCache scrollCache = mScrollCache; 11718 11719 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11720 return false; 11721 } 11722 11723 if (scrollCache.scrollBar == null) { 11724 scrollCache.scrollBar = new ScrollBarDrawable(); 11725 scrollCache.scrollBar.setCallback(this); 11726 scrollCache.scrollBar.setState(getDrawableState()); 11727 } 11728 11729 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11730 11731 if (invalidate) { 11732 // Invalidate to show the scrollbars 11733 postInvalidateOnAnimation(); 11734 } 11735 11736 if (scrollCache.state == ScrollabilityCache.OFF) { 11737 // FIXME: this is copied from WindowManagerService. 11738 // We should get this value from the system when it 11739 // is possible to do so. 11740 final int KEY_REPEAT_FIRST_DELAY = 750; 11741 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11742 } 11743 11744 // Tell mScrollCache when we should start fading. This may 11745 // extend the fade start time if one was already scheduled 11746 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11747 scrollCache.fadeStartTime = fadeStartTime; 11748 scrollCache.state = ScrollabilityCache.ON; 11749 11750 // Schedule our fader to run, unscheduling any old ones first 11751 if (mAttachInfo != null) { 11752 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11753 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11754 } 11755 11756 return true; 11757 } 11758 11759 return false; 11760 } 11761 11762 /** 11763 * Do not invalidate views which are not visible and which are not running an animation. They 11764 * will not get drawn and they should not set dirty flags as if they will be drawn 11765 */ 11766 private boolean skipInvalidate() { 11767 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11768 (!(mParent instanceof ViewGroup) || 11769 !((ViewGroup) mParent).isViewTransitioning(this)); 11770 } 11771 11772 /** 11773 * Mark the area defined by dirty as needing to be drawn. If the view is 11774 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11775 * point in the future. 11776 * <p> 11777 * This must be called from a UI thread. To call from a non-UI thread, call 11778 * {@link #postInvalidate()}. 11779 * <p> 11780 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11781 * {@code dirty}. 11782 * 11783 * @param dirty the rectangle representing the bounds of the dirty region 11784 */ 11785 public void invalidate(Rect dirty) { 11786 final int scrollX = mScrollX; 11787 final int scrollY = mScrollY; 11788 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11789 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11790 } 11791 11792 /** 11793 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11794 * coordinates of the dirty rect are relative to the view. If the view is 11795 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11796 * point in the future. 11797 * <p> 11798 * This must be called from a UI thread. To call from a non-UI thread, call 11799 * {@link #postInvalidate()}. 11800 * 11801 * @param l the left position of the dirty region 11802 * @param t the top position of the dirty region 11803 * @param r the right position of the dirty region 11804 * @param b the bottom position of the dirty region 11805 */ 11806 public void invalidate(int l, int t, int r, int b) { 11807 final int scrollX = mScrollX; 11808 final int scrollY = mScrollY; 11809 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11810 } 11811 11812 /** 11813 * Invalidate the whole view. If the view is visible, 11814 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11815 * the future. 11816 * <p> 11817 * This must be called from a UI thread. To call from a non-UI thread, call 11818 * {@link #postInvalidate()}. 11819 */ 11820 public void invalidate() { 11821 invalidate(true); 11822 } 11823 11824 /** 11825 * This is where the invalidate() work actually happens. A full invalidate() 11826 * causes the drawing cache to be invalidated, but this function can be 11827 * called with invalidateCache set to false to skip that invalidation step 11828 * for cases that do not need it (for example, a component that remains at 11829 * the same dimensions with the same content). 11830 * 11831 * @param invalidateCache Whether the drawing cache for this view should be 11832 * invalidated as well. This is usually true for a full 11833 * invalidate, but may be set to false if the View's contents or 11834 * dimensions have not changed. 11835 */ 11836 void invalidate(boolean invalidateCache) { 11837 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11838 } 11839 11840 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11841 boolean fullInvalidate) { 11842 if (mGhostView != null) { 11843 mGhostView.invalidate(true); 11844 return; 11845 } 11846 11847 if (skipInvalidate()) { 11848 return; 11849 } 11850 11851 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11852 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11853 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11854 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11855 if (fullInvalidate) { 11856 mLastIsOpaque = isOpaque(); 11857 mPrivateFlags &= ~PFLAG_DRAWN; 11858 } 11859 11860 mPrivateFlags |= PFLAG_DIRTY; 11861 11862 if (invalidateCache) { 11863 mPrivateFlags |= PFLAG_INVALIDATED; 11864 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11865 } 11866 11867 // Propagate the damage rectangle to the parent view. 11868 final AttachInfo ai = mAttachInfo; 11869 final ViewParent p = mParent; 11870 if (p != null && ai != null && l < r && t < b) { 11871 final Rect damage = ai.mTmpInvalRect; 11872 damage.set(l, t, r, b); 11873 p.invalidateChild(this, damage); 11874 } 11875 11876 // Damage the entire projection receiver, if necessary. 11877 if (mBackground != null && mBackground.isProjected()) { 11878 final View receiver = getProjectionReceiver(); 11879 if (receiver != null) { 11880 receiver.damageInParent(); 11881 } 11882 } 11883 11884 // Damage the entire IsolatedZVolume receiving this view's shadow. 11885 if (isHardwareAccelerated() && getZ() != 0) { 11886 damageShadowReceiver(); 11887 } 11888 } 11889 } 11890 11891 /** 11892 * @return this view's projection receiver, or {@code null} if none exists 11893 */ 11894 private View getProjectionReceiver() { 11895 ViewParent p = getParent(); 11896 while (p != null && p instanceof View) { 11897 final View v = (View) p; 11898 if (v.isProjectionReceiver()) { 11899 return v; 11900 } 11901 p = p.getParent(); 11902 } 11903 11904 return null; 11905 } 11906 11907 /** 11908 * @return whether the view is a projection receiver 11909 */ 11910 private boolean isProjectionReceiver() { 11911 return mBackground != null; 11912 } 11913 11914 /** 11915 * Damage area of the screen that can be covered by this View's shadow. 11916 * 11917 * This method will guarantee that any changes to shadows cast by a View 11918 * are damaged on the screen for future redraw. 11919 */ 11920 private void damageShadowReceiver() { 11921 final AttachInfo ai = mAttachInfo; 11922 if (ai != null) { 11923 ViewParent p = getParent(); 11924 if (p != null && p instanceof ViewGroup) { 11925 final ViewGroup vg = (ViewGroup) p; 11926 vg.damageInParent(); 11927 } 11928 } 11929 } 11930 11931 /** 11932 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11933 * set any flags or handle all of the cases handled by the default invalidation methods. 11934 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11935 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11936 * walk up the hierarchy, transforming the dirty rect as necessary. 11937 * 11938 * The method also handles normal invalidation logic if display list properties are not 11939 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11940 * backup approach, to handle these cases used in the various property-setting methods. 11941 * 11942 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11943 * are not being used in this view 11944 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11945 * list properties are not being used in this view 11946 */ 11947 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11948 if (!isHardwareAccelerated() 11949 || !mRenderNode.isValid() 11950 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11951 if (invalidateParent) { 11952 invalidateParentCaches(); 11953 } 11954 if (forceRedraw) { 11955 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11956 } 11957 invalidate(false); 11958 } else { 11959 damageInParent(); 11960 } 11961 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11962 damageShadowReceiver(); 11963 } 11964 } 11965 11966 /** 11967 * Tells the parent view to damage this view's bounds. 11968 * 11969 * @hide 11970 */ 11971 protected void damageInParent() { 11972 final AttachInfo ai = mAttachInfo; 11973 final ViewParent p = mParent; 11974 if (p != null && ai != null) { 11975 final Rect r = ai.mTmpInvalRect; 11976 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11977 if (mParent instanceof ViewGroup) { 11978 ((ViewGroup) mParent).damageChild(this, r); 11979 } else { 11980 mParent.invalidateChild(this, r); 11981 } 11982 } 11983 } 11984 11985 /** 11986 * Utility method to transform a given Rect by the current matrix of this view. 11987 */ 11988 void transformRect(final Rect rect) { 11989 if (!getMatrix().isIdentity()) { 11990 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11991 boundingRect.set(rect); 11992 getMatrix().mapRect(boundingRect); 11993 rect.set((int) Math.floor(boundingRect.left), 11994 (int) Math.floor(boundingRect.top), 11995 (int) Math.ceil(boundingRect.right), 11996 (int) Math.ceil(boundingRect.bottom)); 11997 } 11998 } 11999 12000 /** 12001 * Used to indicate that the parent of this view should clear its caches. This functionality 12002 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12003 * which is necessary when various parent-managed properties of the view change, such as 12004 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12005 * clears the parent caches and does not causes an invalidate event. 12006 * 12007 * @hide 12008 */ 12009 protected void invalidateParentCaches() { 12010 if (mParent instanceof View) { 12011 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12012 } 12013 } 12014 12015 /** 12016 * Used to indicate that the parent of this view should be invalidated. This functionality 12017 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12018 * which is necessary when various parent-managed properties of the view change, such as 12019 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12020 * an invalidation event to the parent. 12021 * 12022 * @hide 12023 */ 12024 protected void invalidateParentIfNeeded() { 12025 if (isHardwareAccelerated() && mParent instanceof View) { 12026 ((View) mParent).invalidate(true); 12027 } 12028 } 12029 12030 /** 12031 * @hide 12032 */ 12033 protected void invalidateParentIfNeededAndWasQuickRejected() { 12034 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12035 // View was rejected last time it was drawn by its parent; this may have changed 12036 invalidateParentIfNeeded(); 12037 } 12038 } 12039 12040 /** 12041 * Indicates whether this View is opaque. An opaque View guarantees that it will 12042 * draw all the pixels overlapping its bounds using a fully opaque color. 12043 * 12044 * Subclasses of View should override this method whenever possible to indicate 12045 * whether an instance is opaque. Opaque Views are treated in a special way by 12046 * the View hierarchy, possibly allowing it to perform optimizations during 12047 * invalidate/draw passes. 12048 * 12049 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12050 */ 12051 @ViewDebug.ExportedProperty(category = "drawing") 12052 public boolean isOpaque() { 12053 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12054 getFinalAlpha() >= 1.0f; 12055 } 12056 12057 /** 12058 * @hide 12059 */ 12060 protected void computeOpaqueFlags() { 12061 // Opaque if: 12062 // - Has a background 12063 // - Background is opaque 12064 // - Doesn't have scrollbars or scrollbars overlay 12065 12066 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12067 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12068 } else { 12069 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12070 } 12071 12072 final int flags = mViewFlags; 12073 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12074 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12075 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12076 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12077 } else { 12078 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12079 } 12080 } 12081 12082 /** 12083 * @hide 12084 */ 12085 protected boolean hasOpaqueScrollbars() { 12086 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12087 } 12088 12089 /** 12090 * @return A handler associated with the thread running the View. This 12091 * handler can be used to pump events in the UI events queue. 12092 */ 12093 public Handler getHandler() { 12094 final AttachInfo attachInfo = mAttachInfo; 12095 if (attachInfo != null) { 12096 return attachInfo.mHandler; 12097 } 12098 return null; 12099 } 12100 12101 /** 12102 * Gets the view root associated with the View. 12103 * @return The view root, or null if none. 12104 * @hide 12105 */ 12106 public ViewRootImpl getViewRootImpl() { 12107 if (mAttachInfo != null) { 12108 return mAttachInfo.mViewRootImpl; 12109 } 12110 return null; 12111 } 12112 12113 /** 12114 * @hide 12115 */ 12116 public HardwareRenderer getHardwareRenderer() { 12117 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12118 } 12119 12120 /** 12121 * <p>Causes the Runnable to be added to the message queue. 12122 * The runnable will be run on the user interface thread.</p> 12123 * 12124 * @param action The Runnable that will be executed. 12125 * 12126 * @return Returns true if the Runnable was successfully placed in to the 12127 * message queue. Returns false on failure, usually because the 12128 * looper processing the message queue is exiting. 12129 * 12130 * @see #postDelayed 12131 * @see #removeCallbacks 12132 */ 12133 public boolean post(Runnable action) { 12134 final AttachInfo attachInfo = mAttachInfo; 12135 if (attachInfo != null) { 12136 return attachInfo.mHandler.post(action); 12137 } 12138 // Assume that post will succeed later 12139 ViewRootImpl.getRunQueue().post(action); 12140 return true; 12141 } 12142 12143 /** 12144 * <p>Causes the Runnable to be added to the message queue, to be run 12145 * after the specified amount of time elapses. 12146 * The runnable will be run on the user interface thread.</p> 12147 * 12148 * @param action The Runnable that will be executed. 12149 * @param delayMillis The delay (in milliseconds) until the Runnable 12150 * will be executed. 12151 * 12152 * @return true if the Runnable was successfully placed in to the 12153 * message queue. Returns false on failure, usually because the 12154 * looper processing the message queue is exiting. Note that a 12155 * result of true does not mean the Runnable will be processed -- 12156 * if the looper is quit before the delivery time of the message 12157 * occurs then the message will be dropped. 12158 * 12159 * @see #post 12160 * @see #removeCallbacks 12161 */ 12162 public boolean postDelayed(Runnable action, long delayMillis) { 12163 final AttachInfo attachInfo = mAttachInfo; 12164 if (attachInfo != null) { 12165 return attachInfo.mHandler.postDelayed(action, delayMillis); 12166 } 12167 // Assume that post will succeed later 12168 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12169 return true; 12170 } 12171 12172 /** 12173 * <p>Causes the Runnable to execute on the next animation time step. 12174 * The runnable will be run on the user interface thread.</p> 12175 * 12176 * @param action The Runnable that will be executed. 12177 * 12178 * @see #postOnAnimationDelayed 12179 * @see #removeCallbacks 12180 */ 12181 public void postOnAnimation(Runnable action) { 12182 final AttachInfo attachInfo = mAttachInfo; 12183 if (attachInfo != null) { 12184 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12185 Choreographer.CALLBACK_ANIMATION, action, null); 12186 } else { 12187 // Assume that post will succeed later 12188 ViewRootImpl.getRunQueue().post(action); 12189 } 12190 } 12191 12192 /** 12193 * <p>Causes the Runnable to execute on the next animation time step, 12194 * after the specified amount of time elapses. 12195 * The runnable will be run on the user interface thread.</p> 12196 * 12197 * @param action The Runnable that will be executed. 12198 * @param delayMillis The delay (in milliseconds) until the Runnable 12199 * will be executed. 12200 * 12201 * @see #postOnAnimation 12202 * @see #removeCallbacks 12203 */ 12204 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12205 final AttachInfo attachInfo = mAttachInfo; 12206 if (attachInfo != null) { 12207 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12208 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12209 } else { 12210 // Assume that post will succeed later 12211 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12212 } 12213 } 12214 12215 /** 12216 * <p>Removes the specified Runnable from the message queue.</p> 12217 * 12218 * @param action The Runnable to remove from the message handling queue 12219 * 12220 * @return true if this view could ask the Handler to remove the Runnable, 12221 * false otherwise. When the returned value is true, the Runnable 12222 * may or may not have been actually removed from the message queue 12223 * (for instance, if the Runnable was not in the queue already.) 12224 * 12225 * @see #post 12226 * @see #postDelayed 12227 * @see #postOnAnimation 12228 * @see #postOnAnimationDelayed 12229 */ 12230 public boolean removeCallbacks(Runnable action) { 12231 if (action != null) { 12232 final AttachInfo attachInfo = mAttachInfo; 12233 if (attachInfo != null) { 12234 attachInfo.mHandler.removeCallbacks(action); 12235 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12236 Choreographer.CALLBACK_ANIMATION, action, null); 12237 } 12238 // Assume that post will succeed later 12239 ViewRootImpl.getRunQueue().removeCallbacks(action); 12240 } 12241 return true; 12242 } 12243 12244 /** 12245 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12246 * Use this to invalidate the View from a non-UI thread.</p> 12247 * 12248 * <p>This method can be invoked from outside of the UI thread 12249 * only when this View is attached to a window.</p> 12250 * 12251 * @see #invalidate() 12252 * @see #postInvalidateDelayed(long) 12253 */ 12254 public void postInvalidate() { 12255 postInvalidateDelayed(0); 12256 } 12257 12258 /** 12259 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12260 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12261 * 12262 * <p>This method can be invoked from outside of the UI thread 12263 * only when this View is attached to a window.</p> 12264 * 12265 * @param left The left coordinate of the rectangle to invalidate. 12266 * @param top The top coordinate of the rectangle to invalidate. 12267 * @param right The right coordinate of the rectangle to invalidate. 12268 * @param bottom The bottom coordinate of the rectangle to invalidate. 12269 * 12270 * @see #invalidate(int, int, int, int) 12271 * @see #invalidate(Rect) 12272 * @see #postInvalidateDelayed(long, int, int, int, int) 12273 */ 12274 public void postInvalidate(int left, int top, int right, int bottom) { 12275 postInvalidateDelayed(0, left, top, right, bottom); 12276 } 12277 12278 /** 12279 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12280 * loop. Waits for the specified amount of time.</p> 12281 * 12282 * <p>This method can be invoked from outside of the UI thread 12283 * only when this View is attached to a window.</p> 12284 * 12285 * @param delayMilliseconds the duration in milliseconds to delay the 12286 * invalidation by 12287 * 12288 * @see #invalidate() 12289 * @see #postInvalidate() 12290 */ 12291 public void postInvalidateDelayed(long delayMilliseconds) { 12292 // We try only with the AttachInfo because there's no point in invalidating 12293 // if we are not attached to our window 12294 final AttachInfo attachInfo = mAttachInfo; 12295 if (attachInfo != null) { 12296 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12297 } 12298 } 12299 12300 /** 12301 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12302 * through the event loop. Waits for the specified amount of time.</p> 12303 * 12304 * <p>This method can be invoked from outside of the UI thread 12305 * only when this View is attached to a window.</p> 12306 * 12307 * @param delayMilliseconds the duration in milliseconds to delay the 12308 * invalidation by 12309 * @param left The left coordinate of the rectangle to invalidate. 12310 * @param top The top coordinate of the rectangle to invalidate. 12311 * @param right The right coordinate of the rectangle to invalidate. 12312 * @param bottom The bottom coordinate of the rectangle to invalidate. 12313 * 12314 * @see #invalidate(int, int, int, int) 12315 * @see #invalidate(Rect) 12316 * @see #postInvalidate(int, int, int, int) 12317 */ 12318 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12319 int right, int bottom) { 12320 12321 // We try only with the AttachInfo because there's no point in invalidating 12322 // if we are not attached to our window 12323 final AttachInfo attachInfo = mAttachInfo; 12324 if (attachInfo != null) { 12325 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12326 info.target = this; 12327 info.left = left; 12328 info.top = top; 12329 info.right = right; 12330 info.bottom = bottom; 12331 12332 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12333 } 12334 } 12335 12336 /** 12337 * <p>Cause an invalidate to happen on the next animation time step, typically the 12338 * next display frame.</p> 12339 * 12340 * <p>This method can be invoked from outside of the UI thread 12341 * only when this View is attached to a window.</p> 12342 * 12343 * @see #invalidate() 12344 */ 12345 public void postInvalidateOnAnimation() { 12346 // We try only with the AttachInfo because there's no point in invalidating 12347 // if we are not attached to our window 12348 final AttachInfo attachInfo = mAttachInfo; 12349 if (attachInfo != null) { 12350 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12351 } 12352 } 12353 12354 /** 12355 * <p>Cause an invalidate of the specified area to happen on the next animation 12356 * time step, typically the next display frame.</p> 12357 * 12358 * <p>This method can be invoked from outside of the UI thread 12359 * only when this View is attached to a window.</p> 12360 * 12361 * @param left The left coordinate of the rectangle to invalidate. 12362 * @param top The top coordinate of the rectangle to invalidate. 12363 * @param right The right coordinate of the rectangle to invalidate. 12364 * @param bottom The bottom coordinate of the rectangle to invalidate. 12365 * 12366 * @see #invalidate(int, int, int, int) 12367 * @see #invalidate(Rect) 12368 */ 12369 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12370 // We try only with the AttachInfo because there's no point in invalidating 12371 // if we are not attached to our window 12372 final AttachInfo attachInfo = mAttachInfo; 12373 if (attachInfo != null) { 12374 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12375 info.target = this; 12376 info.left = left; 12377 info.top = top; 12378 info.right = right; 12379 info.bottom = bottom; 12380 12381 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12382 } 12383 } 12384 12385 /** 12386 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12387 * This event is sent at most once every 12388 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12389 */ 12390 private void postSendViewScrolledAccessibilityEventCallback() { 12391 if (mSendViewScrolledAccessibilityEvent == null) { 12392 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12393 } 12394 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12395 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12396 postDelayed(mSendViewScrolledAccessibilityEvent, 12397 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12398 } 12399 } 12400 12401 /** 12402 * Called by a parent to request that a child update its values for mScrollX 12403 * and mScrollY if necessary. This will typically be done if the child is 12404 * animating a scroll using a {@link android.widget.Scroller Scroller} 12405 * object. 12406 */ 12407 public void computeScroll() { 12408 } 12409 12410 /** 12411 * <p>Indicate whether the horizontal edges are faded when the view is 12412 * scrolled horizontally.</p> 12413 * 12414 * @return true if the horizontal edges should are faded on scroll, false 12415 * otherwise 12416 * 12417 * @see #setHorizontalFadingEdgeEnabled(boolean) 12418 * 12419 * @attr ref android.R.styleable#View_requiresFadingEdge 12420 */ 12421 public boolean isHorizontalFadingEdgeEnabled() { 12422 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12423 } 12424 12425 /** 12426 * <p>Define whether the horizontal edges should be faded when this view 12427 * is scrolled horizontally.</p> 12428 * 12429 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12430 * be faded when the view is scrolled 12431 * horizontally 12432 * 12433 * @see #isHorizontalFadingEdgeEnabled() 12434 * 12435 * @attr ref android.R.styleable#View_requiresFadingEdge 12436 */ 12437 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12438 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12439 if (horizontalFadingEdgeEnabled) { 12440 initScrollCache(); 12441 } 12442 12443 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12444 } 12445 } 12446 12447 /** 12448 * <p>Indicate whether the vertical edges are faded when the view is 12449 * scrolled horizontally.</p> 12450 * 12451 * @return true if the vertical edges should are faded on scroll, false 12452 * otherwise 12453 * 12454 * @see #setVerticalFadingEdgeEnabled(boolean) 12455 * 12456 * @attr ref android.R.styleable#View_requiresFadingEdge 12457 */ 12458 public boolean isVerticalFadingEdgeEnabled() { 12459 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12460 } 12461 12462 /** 12463 * <p>Define whether the vertical edges should be faded when this view 12464 * is scrolled vertically.</p> 12465 * 12466 * @param verticalFadingEdgeEnabled true if the vertical edges should 12467 * be faded when the view is scrolled 12468 * vertically 12469 * 12470 * @see #isVerticalFadingEdgeEnabled() 12471 * 12472 * @attr ref android.R.styleable#View_requiresFadingEdge 12473 */ 12474 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12475 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12476 if (verticalFadingEdgeEnabled) { 12477 initScrollCache(); 12478 } 12479 12480 mViewFlags ^= FADING_EDGE_VERTICAL; 12481 } 12482 } 12483 12484 /** 12485 * Returns the strength, or intensity, of the top faded edge. The strength is 12486 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12487 * returns 0.0 or 1.0 but no value in between. 12488 * 12489 * Subclasses should override this method to provide a smoother fade transition 12490 * when scrolling occurs. 12491 * 12492 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12493 */ 12494 protected float getTopFadingEdgeStrength() { 12495 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12496 } 12497 12498 /** 12499 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12500 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12501 * returns 0.0 or 1.0 but no value in between. 12502 * 12503 * Subclasses should override this method to provide a smoother fade transition 12504 * when scrolling occurs. 12505 * 12506 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12507 */ 12508 protected float getBottomFadingEdgeStrength() { 12509 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12510 computeVerticalScrollRange() ? 1.0f : 0.0f; 12511 } 12512 12513 /** 12514 * Returns the strength, or intensity, of the left faded edge. The strength is 12515 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12516 * returns 0.0 or 1.0 but no value in between. 12517 * 12518 * Subclasses should override this method to provide a smoother fade transition 12519 * when scrolling occurs. 12520 * 12521 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12522 */ 12523 protected float getLeftFadingEdgeStrength() { 12524 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12525 } 12526 12527 /** 12528 * Returns the strength, or intensity, of the right faded edge. The strength is 12529 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12530 * returns 0.0 or 1.0 but no value in between. 12531 * 12532 * Subclasses should override this method to provide a smoother fade transition 12533 * when scrolling occurs. 12534 * 12535 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12536 */ 12537 protected float getRightFadingEdgeStrength() { 12538 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12539 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12540 } 12541 12542 /** 12543 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12544 * scrollbar is not drawn by default.</p> 12545 * 12546 * @return true if the horizontal scrollbar should be painted, false 12547 * otherwise 12548 * 12549 * @see #setHorizontalScrollBarEnabled(boolean) 12550 */ 12551 public boolean isHorizontalScrollBarEnabled() { 12552 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12553 } 12554 12555 /** 12556 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12557 * scrollbar is not drawn by default.</p> 12558 * 12559 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12560 * be painted 12561 * 12562 * @see #isHorizontalScrollBarEnabled() 12563 */ 12564 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12565 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12566 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12567 computeOpaqueFlags(); 12568 resolvePadding(); 12569 } 12570 } 12571 12572 /** 12573 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12574 * scrollbar is not drawn by default.</p> 12575 * 12576 * @return true if the vertical scrollbar should be painted, false 12577 * otherwise 12578 * 12579 * @see #setVerticalScrollBarEnabled(boolean) 12580 */ 12581 public boolean isVerticalScrollBarEnabled() { 12582 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12583 } 12584 12585 /** 12586 * <p>Define whether the vertical scrollbar should be drawn or not. The 12587 * scrollbar is not drawn by default.</p> 12588 * 12589 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12590 * be painted 12591 * 12592 * @see #isVerticalScrollBarEnabled() 12593 */ 12594 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12595 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12596 mViewFlags ^= SCROLLBARS_VERTICAL; 12597 computeOpaqueFlags(); 12598 resolvePadding(); 12599 } 12600 } 12601 12602 /** 12603 * @hide 12604 */ 12605 protected void recomputePadding() { 12606 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12607 } 12608 12609 /** 12610 * Define whether scrollbars will fade when the view is not scrolling. 12611 * 12612 * @param fadeScrollbars whether to enable fading 12613 * 12614 * @attr ref android.R.styleable#View_fadeScrollbars 12615 */ 12616 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12617 initScrollCache(); 12618 final ScrollabilityCache scrollabilityCache = mScrollCache; 12619 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12620 if (fadeScrollbars) { 12621 scrollabilityCache.state = ScrollabilityCache.OFF; 12622 } else { 12623 scrollabilityCache.state = ScrollabilityCache.ON; 12624 } 12625 } 12626 12627 /** 12628 * 12629 * Returns true if scrollbars will fade when this view is not scrolling 12630 * 12631 * @return true if scrollbar fading is enabled 12632 * 12633 * @attr ref android.R.styleable#View_fadeScrollbars 12634 */ 12635 public boolean isScrollbarFadingEnabled() { 12636 return mScrollCache != null && mScrollCache.fadeScrollBars; 12637 } 12638 12639 /** 12640 * 12641 * Returns the delay before scrollbars fade. 12642 * 12643 * @return the delay before scrollbars fade 12644 * 12645 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12646 */ 12647 public int getScrollBarDefaultDelayBeforeFade() { 12648 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12649 mScrollCache.scrollBarDefaultDelayBeforeFade; 12650 } 12651 12652 /** 12653 * Define the delay before scrollbars fade. 12654 * 12655 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12656 * 12657 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12658 */ 12659 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12660 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12661 } 12662 12663 /** 12664 * 12665 * Returns the scrollbar fade duration. 12666 * 12667 * @return the scrollbar fade duration 12668 * 12669 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12670 */ 12671 public int getScrollBarFadeDuration() { 12672 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12673 mScrollCache.scrollBarFadeDuration; 12674 } 12675 12676 /** 12677 * Define the scrollbar fade duration. 12678 * 12679 * @param scrollBarFadeDuration - the scrollbar fade duration 12680 * 12681 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12682 */ 12683 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12684 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12685 } 12686 12687 /** 12688 * 12689 * Returns the scrollbar size. 12690 * 12691 * @return the scrollbar size 12692 * 12693 * @attr ref android.R.styleable#View_scrollbarSize 12694 */ 12695 public int getScrollBarSize() { 12696 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12697 mScrollCache.scrollBarSize; 12698 } 12699 12700 /** 12701 * Define the scrollbar size. 12702 * 12703 * @param scrollBarSize - the scrollbar size 12704 * 12705 * @attr ref android.R.styleable#View_scrollbarSize 12706 */ 12707 public void setScrollBarSize(int scrollBarSize) { 12708 getScrollCache().scrollBarSize = scrollBarSize; 12709 } 12710 12711 /** 12712 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12713 * inset. When inset, they add to the padding of the view. And the scrollbars 12714 * can be drawn inside the padding area or on the edge of the view. For example, 12715 * if a view has a background drawable and you want to draw the scrollbars 12716 * inside the padding specified by the drawable, you can use 12717 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12718 * appear at the edge of the view, ignoring the padding, then you can use 12719 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12720 * @param style the style of the scrollbars. Should be one of 12721 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12722 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12723 * @see #SCROLLBARS_INSIDE_OVERLAY 12724 * @see #SCROLLBARS_INSIDE_INSET 12725 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12726 * @see #SCROLLBARS_OUTSIDE_INSET 12727 * 12728 * @attr ref android.R.styleable#View_scrollbarStyle 12729 */ 12730 public void setScrollBarStyle(@ScrollBarStyle int style) { 12731 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12732 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12733 computeOpaqueFlags(); 12734 resolvePadding(); 12735 } 12736 } 12737 12738 /** 12739 * <p>Returns the current scrollbar style.</p> 12740 * @return the current scrollbar style 12741 * @see #SCROLLBARS_INSIDE_OVERLAY 12742 * @see #SCROLLBARS_INSIDE_INSET 12743 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12744 * @see #SCROLLBARS_OUTSIDE_INSET 12745 * 12746 * @attr ref android.R.styleable#View_scrollbarStyle 12747 */ 12748 @ViewDebug.ExportedProperty(mapping = { 12749 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12750 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12751 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12752 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12753 }) 12754 @ScrollBarStyle 12755 public int getScrollBarStyle() { 12756 return mViewFlags & SCROLLBARS_STYLE_MASK; 12757 } 12758 12759 /** 12760 * <p>Compute the horizontal range that the horizontal scrollbar 12761 * represents.</p> 12762 * 12763 * <p>The range is expressed in arbitrary units that must be the same as the 12764 * units used by {@link #computeHorizontalScrollExtent()} and 12765 * {@link #computeHorizontalScrollOffset()}.</p> 12766 * 12767 * <p>The default range is the drawing width of this view.</p> 12768 * 12769 * @return the total horizontal range represented by the horizontal 12770 * scrollbar 12771 * 12772 * @see #computeHorizontalScrollExtent() 12773 * @see #computeHorizontalScrollOffset() 12774 * @see android.widget.ScrollBarDrawable 12775 */ 12776 protected int computeHorizontalScrollRange() { 12777 return getWidth(); 12778 } 12779 12780 /** 12781 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12782 * within the horizontal range. This value is used to compute the position 12783 * of the thumb within the scrollbar's track.</p> 12784 * 12785 * <p>The range is expressed in arbitrary units that must be the same as the 12786 * units used by {@link #computeHorizontalScrollRange()} and 12787 * {@link #computeHorizontalScrollExtent()}.</p> 12788 * 12789 * <p>The default offset is the scroll offset of this view.</p> 12790 * 12791 * @return the horizontal offset of the scrollbar's thumb 12792 * 12793 * @see #computeHorizontalScrollRange() 12794 * @see #computeHorizontalScrollExtent() 12795 * @see android.widget.ScrollBarDrawable 12796 */ 12797 protected int computeHorizontalScrollOffset() { 12798 return mScrollX; 12799 } 12800 12801 /** 12802 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12803 * within the horizontal range. This value is used to compute the length 12804 * of the thumb within the scrollbar's track.</p> 12805 * 12806 * <p>The range is expressed in arbitrary units that must be the same as the 12807 * units used by {@link #computeHorizontalScrollRange()} and 12808 * {@link #computeHorizontalScrollOffset()}.</p> 12809 * 12810 * <p>The default extent is the drawing width of this view.</p> 12811 * 12812 * @return the horizontal extent of the scrollbar's thumb 12813 * 12814 * @see #computeHorizontalScrollRange() 12815 * @see #computeHorizontalScrollOffset() 12816 * @see android.widget.ScrollBarDrawable 12817 */ 12818 protected int computeHorizontalScrollExtent() { 12819 return getWidth(); 12820 } 12821 12822 /** 12823 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12824 * 12825 * <p>The range is expressed in arbitrary units that must be the same as the 12826 * units used by {@link #computeVerticalScrollExtent()} and 12827 * {@link #computeVerticalScrollOffset()}.</p> 12828 * 12829 * @return the total vertical range represented by the vertical scrollbar 12830 * 12831 * <p>The default range is the drawing height of this view.</p> 12832 * 12833 * @see #computeVerticalScrollExtent() 12834 * @see #computeVerticalScrollOffset() 12835 * @see android.widget.ScrollBarDrawable 12836 */ 12837 protected int computeVerticalScrollRange() { 12838 return getHeight(); 12839 } 12840 12841 /** 12842 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12843 * within the horizontal range. This value is used to compute the position 12844 * of the thumb within the scrollbar's track.</p> 12845 * 12846 * <p>The range is expressed in arbitrary units that must be the same as the 12847 * units used by {@link #computeVerticalScrollRange()} and 12848 * {@link #computeVerticalScrollExtent()}.</p> 12849 * 12850 * <p>The default offset is the scroll offset of this view.</p> 12851 * 12852 * @return the vertical offset of the scrollbar's thumb 12853 * 12854 * @see #computeVerticalScrollRange() 12855 * @see #computeVerticalScrollExtent() 12856 * @see android.widget.ScrollBarDrawable 12857 */ 12858 protected int computeVerticalScrollOffset() { 12859 return mScrollY; 12860 } 12861 12862 /** 12863 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12864 * within the vertical range. This value is used to compute the length 12865 * of the thumb within the scrollbar's track.</p> 12866 * 12867 * <p>The range is expressed in arbitrary units that must be the same as the 12868 * units used by {@link #computeVerticalScrollRange()} and 12869 * {@link #computeVerticalScrollOffset()}.</p> 12870 * 12871 * <p>The default extent is the drawing height of this view.</p> 12872 * 12873 * @return the vertical extent of the scrollbar's thumb 12874 * 12875 * @see #computeVerticalScrollRange() 12876 * @see #computeVerticalScrollOffset() 12877 * @see android.widget.ScrollBarDrawable 12878 */ 12879 protected int computeVerticalScrollExtent() { 12880 return getHeight(); 12881 } 12882 12883 /** 12884 * Check if this view can be scrolled horizontally in a certain direction. 12885 * 12886 * @param direction Negative to check scrolling left, positive to check scrolling right. 12887 * @return true if this view can be scrolled in the specified direction, false otherwise. 12888 */ 12889 public boolean canScrollHorizontally(int direction) { 12890 final int offset = computeHorizontalScrollOffset(); 12891 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12892 if (range == 0) return false; 12893 if (direction < 0) { 12894 return offset > 0; 12895 } else { 12896 return offset < range - 1; 12897 } 12898 } 12899 12900 /** 12901 * Check if this view can be scrolled vertically in a certain direction. 12902 * 12903 * @param direction Negative to check scrolling up, positive to check scrolling down. 12904 * @return true if this view can be scrolled in the specified direction, false otherwise. 12905 */ 12906 public boolean canScrollVertically(int direction) { 12907 final int offset = computeVerticalScrollOffset(); 12908 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12909 if (range == 0) return false; 12910 if (direction < 0) { 12911 return offset > 0; 12912 } else { 12913 return offset < range - 1; 12914 } 12915 } 12916 12917 /** 12918 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12919 * scrollbars are painted only if they have been awakened first.</p> 12920 * 12921 * @param canvas the canvas on which to draw the scrollbars 12922 * 12923 * @see #awakenScrollBars(int) 12924 */ 12925 protected final void onDrawScrollBars(Canvas canvas) { 12926 // scrollbars are drawn only when the animation is running 12927 final ScrollabilityCache cache = mScrollCache; 12928 if (cache != null) { 12929 12930 int state = cache.state; 12931 12932 if (state == ScrollabilityCache.OFF) { 12933 return; 12934 } 12935 12936 boolean invalidate = false; 12937 12938 if (state == ScrollabilityCache.FADING) { 12939 // We're fading -- get our fade interpolation 12940 if (cache.interpolatorValues == null) { 12941 cache.interpolatorValues = new float[1]; 12942 } 12943 12944 float[] values = cache.interpolatorValues; 12945 12946 // Stops the animation if we're done 12947 if (cache.scrollBarInterpolator.timeToValues(values) == 12948 Interpolator.Result.FREEZE_END) { 12949 cache.state = ScrollabilityCache.OFF; 12950 } else { 12951 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 12952 } 12953 12954 // This will make the scroll bars inval themselves after 12955 // drawing. We only want this when we're fading so that 12956 // we prevent excessive redraws 12957 invalidate = true; 12958 } else { 12959 // We're just on -- but we may have been fading before so 12960 // reset alpha 12961 cache.scrollBar.mutate().setAlpha(255); 12962 } 12963 12964 12965 final int viewFlags = mViewFlags; 12966 12967 final boolean drawHorizontalScrollBar = 12968 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12969 final boolean drawVerticalScrollBar = 12970 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12971 && !isVerticalScrollBarHidden(); 12972 12973 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12974 final int width = mRight - mLeft; 12975 final int height = mBottom - mTop; 12976 12977 final ScrollBarDrawable scrollBar = cache.scrollBar; 12978 12979 final int scrollX = mScrollX; 12980 final int scrollY = mScrollY; 12981 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12982 12983 int left; 12984 int top; 12985 int right; 12986 int bottom; 12987 12988 if (drawHorizontalScrollBar) { 12989 int size = scrollBar.getSize(false); 12990 if (size <= 0) { 12991 size = cache.scrollBarSize; 12992 } 12993 12994 scrollBar.setParameters(computeHorizontalScrollRange(), 12995 computeHorizontalScrollOffset(), 12996 computeHorizontalScrollExtent(), false); 12997 final int verticalScrollBarGap = drawVerticalScrollBar ? 12998 getVerticalScrollbarWidth() : 0; 12999 top = scrollY + height - size - (mUserPaddingBottom & inside); 13000 left = scrollX + (mPaddingLeft & inside); 13001 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13002 bottom = top + size; 13003 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13004 if (invalidate) { 13005 invalidate(left, top, right, bottom); 13006 } 13007 } 13008 13009 if (drawVerticalScrollBar) { 13010 int size = scrollBar.getSize(true); 13011 if (size <= 0) { 13012 size = cache.scrollBarSize; 13013 } 13014 13015 scrollBar.setParameters(computeVerticalScrollRange(), 13016 computeVerticalScrollOffset(), 13017 computeVerticalScrollExtent(), true); 13018 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13019 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13020 verticalScrollbarPosition = isLayoutRtl() ? 13021 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13022 } 13023 switch (verticalScrollbarPosition) { 13024 default: 13025 case SCROLLBAR_POSITION_RIGHT: 13026 left = scrollX + width - size - (mUserPaddingRight & inside); 13027 break; 13028 case SCROLLBAR_POSITION_LEFT: 13029 left = scrollX + (mUserPaddingLeft & inside); 13030 break; 13031 } 13032 top = scrollY + (mPaddingTop & inside); 13033 right = left + size; 13034 bottom = scrollY + height - (mUserPaddingBottom & inside); 13035 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13036 if (invalidate) { 13037 invalidate(left, top, right, bottom); 13038 } 13039 } 13040 } 13041 } 13042 } 13043 13044 /** 13045 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13046 * FastScroller is visible. 13047 * @return whether to temporarily hide the vertical scrollbar 13048 * @hide 13049 */ 13050 protected boolean isVerticalScrollBarHidden() { 13051 return false; 13052 } 13053 13054 /** 13055 * <p>Draw the horizontal scrollbar if 13056 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13057 * 13058 * @param canvas the canvas on which to draw the scrollbar 13059 * @param scrollBar the scrollbar's drawable 13060 * 13061 * @see #isHorizontalScrollBarEnabled() 13062 * @see #computeHorizontalScrollRange() 13063 * @see #computeHorizontalScrollExtent() 13064 * @see #computeHorizontalScrollOffset() 13065 * @see android.widget.ScrollBarDrawable 13066 * @hide 13067 */ 13068 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13069 int l, int t, int r, int b) { 13070 scrollBar.setBounds(l, t, r, b); 13071 scrollBar.draw(canvas); 13072 } 13073 13074 /** 13075 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13076 * returns true.</p> 13077 * 13078 * @param canvas the canvas on which to draw the scrollbar 13079 * @param scrollBar the scrollbar's drawable 13080 * 13081 * @see #isVerticalScrollBarEnabled() 13082 * @see #computeVerticalScrollRange() 13083 * @see #computeVerticalScrollExtent() 13084 * @see #computeVerticalScrollOffset() 13085 * @see android.widget.ScrollBarDrawable 13086 * @hide 13087 */ 13088 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13089 int l, int t, int r, int b) { 13090 scrollBar.setBounds(l, t, r, b); 13091 scrollBar.draw(canvas); 13092 } 13093 13094 /** 13095 * Implement this to do your drawing. 13096 * 13097 * @param canvas the canvas on which the background will be drawn 13098 */ 13099 protected void onDraw(Canvas canvas) { 13100 } 13101 13102 /* 13103 * Caller is responsible for calling requestLayout if necessary. 13104 * (This allows addViewInLayout to not request a new layout.) 13105 */ 13106 void assignParent(ViewParent parent) { 13107 if (mParent == null) { 13108 mParent = parent; 13109 } else if (parent == null) { 13110 mParent = null; 13111 } else { 13112 throw new RuntimeException("view " + this + " being added, but" 13113 + " it already has a parent"); 13114 } 13115 } 13116 13117 /** 13118 * This is called when the view is attached to a window. At this point it 13119 * has a Surface and will start drawing. Note that this function is 13120 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13121 * however it may be called any time before the first onDraw -- including 13122 * before or after {@link #onMeasure(int, int)}. 13123 * 13124 * @see #onDetachedFromWindow() 13125 */ 13126 @CallSuper 13127 protected void onAttachedToWindow() { 13128 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13129 mParent.requestTransparentRegion(this); 13130 } 13131 13132 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13133 initialAwakenScrollBars(); 13134 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13135 } 13136 13137 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13138 13139 jumpDrawablesToCurrentState(); 13140 13141 resetSubtreeAccessibilityStateChanged(); 13142 13143 // rebuild, since Outline not maintained while View is detached 13144 rebuildOutline(); 13145 13146 if (isFocused()) { 13147 InputMethodManager imm = InputMethodManager.peekInstance(); 13148 if (imm != null) { 13149 imm.focusIn(this); 13150 } 13151 } 13152 } 13153 13154 /** 13155 * Resolve all RTL related properties. 13156 * 13157 * @return true if resolution of RTL properties has been done 13158 * 13159 * @hide 13160 */ 13161 public boolean resolveRtlPropertiesIfNeeded() { 13162 if (!needRtlPropertiesResolution()) return false; 13163 13164 // Order is important here: LayoutDirection MUST be resolved first 13165 if (!isLayoutDirectionResolved()) { 13166 resolveLayoutDirection(); 13167 resolveLayoutParams(); 13168 } 13169 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 13170 if (!isTextDirectionResolved()) { 13171 resolveTextDirection(); 13172 } 13173 if (!isTextAlignmentResolved()) { 13174 resolveTextAlignment(); 13175 } 13176 // Should resolve Drawables before Padding because we need the layout direction of the 13177 // Drawable to correctly resolve Padding. 13178 if (!areDrawablesResolved()) { 13179 resolveDrawables(); 13180 } 13181 if (!isPaddingResolved()) { 13182 resolvePadding(); 13183 } 13184 onRtlPropertiesChanged(getLayoutDirection()); 13185 return true; 13186 } 13187 13188 /** 13189 * Reset resolution of all RTL related properties. 13190 * 13191 * @hide 13192 */ 13193 public void resetRtlProperties() { 13194 resetResolvedLayoutDirection(); 13195 resetResolvedTextDirection(); 13196 resetResolvedTextAlignment(); 13197 resetResolvedPadding(); 13198 resetResolvedDrawables(); 13199 } 13200 13201 /** 13202 * @see #onScreenStateChanged(int) 13203 */ 13204 void dispatchScreenStateChanged(int screenState) { 13205 onScreenStateChanged(screenState); 13206 } 13207 13208 /** 13209 * This method is called whenever the state of the screen this view is 13210 * attached to changes. A state change will usually occurs when the screen 13211 * turns on or off (whether it happens automatically or the user does it 13212 * manually.) 13213 * 13214 * @param screenState The new state of the screen. Can be either 13215 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13216 */ 13217 public void onScreenStateChanged(int screenState) { 13218 } 13219 13220 /** 13221 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13222 */ 13223 private boolean hasRtlSupport() { 13224 return mContext.getApplicationInfo().hasRtlSupport(); 13225 } 13226 13227 /** 13228 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13229 * RTL not supported) 13230 */ 13231 private boolean isRtlCompatibilityMode() { 13232 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13233 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13234 } 13235 13236 /** 13237 * @return true if RTL properties need resolution. 13238 * 13239 */ 13240 private boolean needRtlPropertiesResolution() { 13241 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13242 } 13243 13244 /** 13245 * Called when any RTL property (layout direction or text direction or text alignment) has 13246 * been changed. 13247 * 13248 * Subclasses need to override this method to take care of cached information that depends on the 13249 * resolved layout direction, or to inform child views that inherit their layout direction. 13250 * 13251 * The default implementation does nothing. 13252 * 13253 * @param layoutDirection the direction of the layout 13254 * 13255 * @see #LAYOUT_DIRECTION_LTR 13256 * @see #LAYOUT_DIRECTION_RTL 13257 */ 13258 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13259 } 13260 13261 /** 13262 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13263 * that the parent directionality can and will be resolved before its children. 13264 * 13265 * @return true if resolution has been done, false otherwise. 13266 * 13267 * @hide 13268 */ 13269 public boolean resolveLayoutDirection() { 13270 // Clear any previous layout direction resolution 13271 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13272 13273 if (hasRtlSupport()) { 13274 // Set resolved depending on layout direction 13275 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13276 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13277 case LAYOUT_DIRECTION_INHERIT: 13278 // We cannot resolve yet. LTR is by default and let the resolution happen again 13279 // later to get the correct resolved value 13280 if (!canResolveLayoutDirection()) return false; 13281 13282 // Parent has not yet resolved, LTR is still the default 13283 try { 13284 if (!mParent.isLayoutDirectionResolved()) return false; 13285 13286 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13287 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13288 } 13289 } catch (AbstractMethodError e) { 13290 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13291 " does not fully implement ViewParent", e); 13292 } 13293 break; 13294 case LAYOUT_DIRECTION_RTL: 13295 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13296 break; 13297 case LAYOUT_DIRECTION_LOCALE: 13298 if((LAYOUT_DIRECTION_RTL == 13299 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13300 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13301 } 13302 break; 13303 default: 13304 // Nothing to do, LTR by default 13305 } 13306 } 13307 13308 // Set to resolved 13309 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13310 return true; 13311 } 13312 13313 /** 13314 * Check if layout direction resolution can be done. 13315 * 13316 * @return true if layout direction resolution can be done otherwise return false. 13317 */ 13318 public boolean canResolveLayoutDirection() { 13319 switch (getRawLayoutDirection()) { 13320 case LAYOUT_DIRECTION_INHERIT: 13321 if (mParent != null) { 13322 try { 13323 return mParent.canResolveLayoutDirection(); 13324 } catch (AbstractMethodError e) { 13325 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13326 " does not fully implement ViewParent", e); 13327 } 13328 } 13329 return false; 13330 13331 default: 13332 return true; 13333 } 13334 } 13335 13336 /** 13337 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13338 * {@link #onMeasure(int, int)}. 13339 * 13340 * @hide 13341 */ 13342 public void resetResolvedLayoutDirection() { 13343 // Reset the current resolved bits 13344 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13345 } 13346 13347 /** 13348 * @return true if the layout direction is inherited. 13349 * 13350 * @hide 13351 */ 13352 public boolean isLayoutDirectionInherited() { 13353 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13354 } 13355 13356 /** 13357 * @return true if layout direction has been resolved. 13358 */ 13359 public boolean isLayoutDirectionResolved() { 13360 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13361 } 13362 13363 /** 13364 * Return if padding has been resolved 13365 * 13366 * @hide 13367 */ 13368 boolean isPaddingResolved() { 13369 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13370 } 13371 13372 /** 13373 * Resolves padding depending on layout direction, if applicable, and 13374 * recomputes internal padding values to adjust for scroll bars. 13375 * 13376 * @hide 13377 */ 13378 public void resolvePadding() { 13379 final int resolvedLayoutDirection = getLayoutDirection(); 13380 13381 if (!isRtlCompatibilityMode()) { 13382 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13383 // If start / end padding are defined, they will be resolved (hence overriding) to 13384 // left / right or right / left depending on the resolved layout direction. 13385 // If start / end padding are not defined, use the left / right ones. 13386 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13387 Rect padding = sThreadLocal.get(); 13388 if (padding == null) { 13389 padding = new Rect(); 13390 sThreadLocal.set(padding); 13391 } 13392 mBackground.getPadding(padding); 13393 if (!mLeftPaddingDefined) { 13394 mUserPaddingLeftInitial = padding.left; 13395 } 13396 if (!mRightPaddingDefined) { 13397 mUserPaddingRightInitial = padding.right; 13398 } 13399 } 13400 switch (resolvedLayoutDirection) { 13401 case LAYOUT_DIRECTION_RTL: 13402 if (mUserPaddingStart != UNDEFINED_PADDING) { 13403 mUserPaddingRight = mUserPaddingStart; 13404 } else { 13405 mUserPaddingRight = mUserPaddingRightInitial; 13406 } 13407 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13408 mUserPaddingLeft = mUserPaddingEnd; 13409 } else { 13410 mUserPaddingLeft = mUserPaddingLeftInitial; 13411 } 13412 break; 13413 case LAYOUT_DIRECTION_LTR: 13414 default: 13415 if (mUserPaddingStart != UNDEFINED_PADDING) { 13416 mUserPaddingLeft = mUserPaddingStart; 13417 } else { 13418 mUserPaddingLeft = mUserPaddingLeftInitial; 13419 } 13420 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13421 mUserPaddingRight = mUserPaddingEnd; 13422 } else { 13423 mUserPaddingRight = mUserPaddingRightInitial; 13424 } 13425 } 13426 13427 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13428 } 13429 13430 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13431 onRtlPropertiesChanged(resolvedLayoutDirection); 13432 13433 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13434 } 13435 13436 /** 13437 * Reset the resolved layout direction. 13438 * 13439 * @hide 13440 */ 13441 public void resetResolvedPadding() { 13442 resetResolvedPaddingInternal(); 13443 } 13444 13445 /** 13446 * Used when we only want to reset *this* view's padding and not trigger overrides 13447 * in ViewGroup that reset children too. 13448 */ 13449 void resetResolvedPaddingInternal() { 13450 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13451 } 13452 13453 /** 13454 * This is called when the view is detached from a window. At this point it 13455 * no longer has a surface for drawing. 13456 * 13457 * @see #onAttachedToWindow() 13458 */ 13459 @CallSuper 13460 protected void onDetachedFromWindow() { 13461 } 13462 13463 /** 13464 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13465 * after onDetachedFromWindow(). 13466 * 13467 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13468 * The super method should be called at the end of the overridden method to ensure 13469 * subclasses are destroyed first 13470 * 13471 * @hide 13472 */ 13473 @CallSuper 13474 protected void onDetachedFromWindowInternal() { 13475 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13476 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13477 13478 removeUnsetPressCallback(); 13479 removeLongPressCallback(); 13480 removePerformClickCallback(); 13481 removeSendViewScrolledAccessibilityEventCallback(); 13482 stopNestedScroll(); 13483 13484 // Anything that started animating right before detach should already 13485 // be in its final state when re-attached. 13486 jumpDrawablesToCurrentState(); 13487 13488 destroyDrawingCache(); 13489 13490 cleanupDraw(); 13491 mCurrentAnimation = null; 13492 } 13493 13494 private void cleanupDraw() { 13495 resetDisplayList(); 13496 if (mAttachInfo != null) { 13497 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13498 } 13499 } 13500 13501 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13502 } 13503 13504 /** 13505 * @return The number of times this view has been attached to a window 13506 */ 13507 protected int getWindowAttachCount() { 13508 return mWindowAttachCount; 13509 } 13510 13511 /** 13512 * Retrieve a unique token identifying the window this view is attached to. 13513 * @return Return the window's token for use in 13514 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13515 */ 13516 public IBinder getWindowToken() { 13517 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13518 } 13519 13520 /** 13521 * Retrieve the {@link WindowId} for the window this view is 13522 * currently attached to. 13523 */ 13524 public WindowId getWindowId() { 13525 if (mAttachInfo == null) { 13526 return null; 13527 } 13528 if (mAttachInfo.mWindowId == null) { 13529 try { 13530 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13531 mAttachInfo.mWindowToken); 13532 mAttachInfo.mWindowId = new WindowId( 13533 mAttachInfo.mIWindowId); 13534 } catch (RemoteException e) { 13535 } 13536 } 13537 return mAttachInfo.mWindowId; 13538 } 13539 13540 /** 13541 * Retrieve a unique token identifying the top-level "real" window of 13542 * the window that this view is attached to. That is, this is like 13543 * {@link #getWindowToken}, except if the window this view in is a panel 13544 * window (attached to another containing window), then the token of 13545 * the containing window is returned instead. 13546 * 13547 * @return Returns the associated window token, either 13548 * {@link #getWindowToken()} or the containing window's token. 13549 */ 13550 public IBinder getApplicationWindowToken() { 13551 AttachInfo ai = mAttachInfo; 13552 if (ai != null) { 13553 IBinder appWindowToken = ai.mPanelParentWindowToken; 13554 if (appWindowToken == null) { 13555 appWindowToken = ai.mWindowToken; 13556 } 13557 return appWindowToken; 13558 } 13559 return null; 13560 } 13561 13562 /** 13563 * Gets the logical display to which the view's window has been attached. 13564 * 13565 * @return The logical display, or null if the view is not currently attached to a window. 13566 */ 13567 public Display getDisplay() { 13568 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13569 } 13570 13571 /** 13572 * Retrieve private session object this view hierarchy is using to 13573 * communicate with the window manager. 13574 * @return the session object to communicate with the window manager 13575 */ 13576 /*package*/ IWindowSession getWindowSession() { 13577 return mAttachInfo != null ? mAttachInfo.mSession : null; 13578 } 13579 13580 /** 13581 * @param info the {@link android.view.View.AttachInfo} to associated with 13582 * this view 13583 */ 13584 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13585 //System.out.println("Attached! " + this); 13586 mAttachInfo = info; 13587 if (mOverlay != null) { 13588 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13589 } 13590 mWindowAttachCount++; 13591 // We will need to evaluate the drawable state at least once. 13592 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13593 if (mFloatingTreeObserver != null) { 13594 info.mTreeObserver.merge(mFloatingTreeObserver); 13595 mFloatingTreeObserver = null; 13596 } 13597 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13598 mAttachInfo.mScrollContainers.add(this); 13599 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13600 } 13601 performCollectViewAttributes(mAttachInfo, visibility); 13602 onAttachedToWindow(); 13603 13604 ListenerInfo li = mListenerInfo; 13605 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13606 li != null ? li.mOnAttachStateChangeListeners : null; 13607 if (listeners != null && listeners.size() > 0) { 13608 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13609 // perform the dispatching. The iterator is a safe guard against listeners that 13610 // could mutate the list by calling the various add/remove methods. This prevents 13611 // the array from being modified while we iterate it. 13612 for (OnAttachStateChangeListener listener : listeners) { 13613 listener.onViewAttachedToWindow(this); 13614 } 13615 } 13616 13617 int vis = info.mWindowVisibility; 13618 if (vis != GONE) { 13619 onWindowVisibilityChanged(vis); 13620 } 13621 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13622 // If nobody has evaluated the drawable state yet, then do it now. 13623 refreshDrawableState(); 13624 } 13625 needGlobalAttributesUpdate(false); 13626 } 13627 13628 void dispatchDetachedFromWindow() { 13629 AttachInfo info = mAttachInfo; 13630 if (info != null) { 13631 int vis = info.mWindowVisibility; 13632 if (vis != GONE) { 13633 onWindowVisibilityChanged(GONE); 13634 } 13635 } 13636 13637 onDetachedFromWindow(); 13638 onDetachedFromWindowInternal(); 13639 13640 ListenerInfo li = mListenerInfo; 13641 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13642 li != null ? li.mOnAttachStateChangeListeners : null; 13643 if (listeners != null && listeners.size() > 0) { 13644 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13645 // perform the dispatching. The iterator is a safe guard against listeners that 13646 // could mutate the list by calling the various add/remove methods. This prevents 13647 // the array from being modified while we iterate it. 13648 for (OnAttachStateChangeListener listener : listeners) { 13649 listener.onViewDetachedFromWindow(this); 13650 } 13651 } 13652 13653 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13654 mAttachInfo.mScrollContainers.remove(this); 13655 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13656 } 13657 13658 mAttachInfo = null; 13659 if (mOverlay != null) { 13660 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13661 } 13662 } 13663 13664 /** 13665 * Cancel any deferred high-level input events that were previously posted to the event queue. 13666 * 13667 * <p>Many views post high-level events such as click handlers to the event queue 13668 * to run deferred in order to preserve a desired user experience - clearing visible 13669 * pressed states before executing, etc. This method will abort any events of this nature 13670 * that are currently in flight.</p> 13671 * 13672 * <p>Custom views that generate their own high-level deferred input events should override 13673 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13674 * 13675 * <p>This will also cancel pending input events for any child views.</p> 13676 * 13677 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13678 * This will not impact newer events posted after this call that may occur as a result of 13679 * lower-level input events still waiting in the queue. If you are trying to prevent 13680 * double-submitted events for the duration of some sort of asynchronous transaction 13681 * you should also take other steps to protect against unexpected double inputs e.g. calling 13682 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13683 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13684 */ 13685 public final void cancelPendingInputEvents() { 13686 dispatchCancelPendingInputEvents(); 13687 } 13688 13689 /** 13690 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13691 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13692 */ 13693 void dispatchCancelPendingInputEvents() { 13694 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13695 onCancelPendingInputEvents(); 13696 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13697 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13698 " did not call through to super.onCancelPendingInputEvents()"); 13699 } 13700 } 13701 13702 /** 13703 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13704 * a parent view. 13705 * 13706 * <p>This method is responsible for removing any pending high-level input events that were 13707 * posted to the event queue to run later. Custom view classes that post their own deferred 13708 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13709 * {@link android.os.Handler} should override this method, call 13710 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13711 * </p> 13712 */ 13713 public void onCancelPendingInputEvents() { 13714 removePerformClickCallback(); 13715 cancelLongPress(); 13716 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13717 } 13718 13719 /** 13720 * Store this view hierarchy's frozen state into the given container. 13721 * 13722 * @param container The SparseArray in which to save the view's state. 13723 * 13724 * @see #restoreHierarchyState(android.util.SparseArray) 13725 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13726 * @see #onSaveInstanceState() 13727 */ 13728 public void saveHierarchyState(SparseArray<Parcelable> container) { 13729 dispatchSaveInstanceState(container); 13730 } 13731 13732 /** 13733 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13734 * this view and its children. May be overridden to modify how freezing happens to a 13735 * view's children; for example, some views may want to not store state for their children. 13736 * 13737 * @param container The SparseArray in which to save the view's state. 13738 * 13739 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13740 * @see #saveHierarchyState(android.util.SparseArray) 13741 * @see #onSaveInstanceState() 13742 */ 13743 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13744 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13745 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13746 Parcelable state = onSaveInstanceState(); 13747 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13748 throw new IllegalStateException( 13749 "Derived class did not call super.onSaveInstanceState()"); 13750 } 13751 if (state != null) { 13752 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13753 // + ": " + state); 13754 container.put(mID, state); 13755 } 13756 } 13757 } 13758 13759 /** 13760 * Hook allowing a view to generate a representation of its internal state 13761 * that can later be used to create a new instance with that same state. 13762 * This state should only contain information that is not persistent or can 13763 * not be reconstructed later. For example, you will never store your 13764 * current position on screen because that will be computed again when a 13765 * new instance of the view is placed in its view hierarchy. 13766 * <p> 13767 * Some examples of things you may store here: the current cursor position 13768 * in a text view (but usually not the text itself since that is stored in a 13769 * content provider or other persistent storage), the currently selected 13770 * item in a list view. 13771 * 13772 * @return Returns a Parcelable object containing the view's current dynamic 13773 * state, or null if there is nothing interesting to save. The 13774 * default implementation returns null. 13775 * @see #onRestoreInstanceState(android.os.Parcelable) 13776 * @see #saveHierarchyState(android.util.SparseArray) 13777 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13778 * @see #setSaveEnabled(boolean) 13779 */ 13780 @CallSuper 13781 protected Parcelable onSaveInstanceState() { 13782 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13783 return BaseSavedState.EMPTY_STATE; 13784 } 13785 13786 /** 13787 * Restore this view hierarchy's frozen state from the given container. 13788 * 13789 * @param container The SparseArray which holds previously frozen states. 13790 * 13791 * @see #saveHierarchyState(android.util.SparseArray) 13792 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13793 * @see #onRestoreInstanceState(android.os.Parcelable) 13794 */ 13795 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13796 dispatchRestoreInstanceState(container); 13797 } 13798 13799 /** 13800 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13801 * state for this view and its children. May be overridden to modify how restoring 13802 * happens to a view's children; for example, some views may want to not store state 13803 * for their children. 13804 * 13805 * @param container The SparseArray which holds previously saved state. 13806 * 13807 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13808 * @see #restoreHierarchyState(android.util.SparseArray) 13809 * @see #onRestoreInstanceState(android.os.Parcelable) 13810 */ 13811 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13812 if (mID != NO_ID) { 13813 Parcelable state = container.get(mID); 13814 if (state != null) { 13815 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13816 // + ": " + state); 13817 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13818 onRestoreInstanceState(state); 13819 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13820 throw new IllegalStateException( 13821 "Derived class did not call super.onRestoreInstanceState()"); 13822 } 13823 } 13824 } 13825 } 13826 13827 /** 13828 * Hook allowing a view to re-apply a representation of its internal state that had previously 13829 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13830 * null state. 13831 * 13832 * @param state The frozen state that had previously been returned by 13833 * {@link #onSaveInstanceState}. 13834 * 13835 * @see #onSaveInstanceState() 13836 * @see #restoreHierarchyState(android.util.SparseArray) 13837 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13838 */ 13839 @CallSuper 13840 protected void onRestoreInstanceState(Parcelable state) { 13841 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13842 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13843 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13844 + "received " + state.getClass().toString() + " instead. This usually happens " 13845 + "when two views of different type have the same id in the same hierarchy. " 13846 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13847 + "other views do not use the same id."); 13848 } 13849 } 13850 13851 /** 13852 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13853 * 13854 * @return the drawing start time in milliseconds 13855 */ 13856 public long getDrawingTime() { 13857 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13858 } 13859 13860 /** 13861 * <p>Enables or disables the duplication of the parent's state into this view. When 13862 * duplication is enabled, this view gets its drawable state from its parent rather 13863 * than from its own internal properties.</p> 13864 * 13865 * <p>Note: in the current implementation, setting this property to true after the 13866 * view was added to a ViewGroup might have no effect at all. This property should 13867 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13868 * 13869 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13870 * property is enabled, an exception will be thrown.</p> 13871 * 13872 * <p>Note: if the child view uses and updates additional states which are unknown to the 13873 * parent, these states should not be affected by this method.</p> 13874 * 13875 * @param enabled True to enable duplication of the parent's drawable state, false 13876 * to disable it. 13877 * 13878 * @see #getDrawableState() 13879 * @see #isDuplicateParentStateEnabled() 13880 */ 13881 public void setDuplicateParentStateEnabled(boolean enabled) { 13882 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13883 } 13884 13885 /** 13886 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13887 * 13888 * @return True if this view's drawable state is duplicated from the parent, 13889 * false otherwise 13890 * 13891 * @see #getDrawableState() 13892 * @see #setDuplicateParentStateEnabled(boolean) 13893 */ 13894 public boolean isDuplicateParentStateEnabled() { 13895 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13896 } 13897 13898 /** 13899 * <p>Specifies the type of layer backing this view. The layer can be 13900 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13901 * {@link #LAYER_TYPE_HARDWARE}.</p> 13902 * 13903 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13904 * instance that controls how the layer is composed on screen. The following 13905 * properties of the paint are taken into account when composing the layer:</p> 13906 * <ul> 13907 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13908 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13909 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13910 * </ul> 13911 * 13912 * <p>If this view has an alpha value set to < 1.0 by calling 13913 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 13914 * by this view's alpha value.</p> 13915 * 13916 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13917 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13918 * for more information on when and how to use layers.</p> 13919 * 13920 * @param layerType The type of layer to use with this view, must be one of 13921 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13922 * {@link #LAYER_TYPE_HARDWARE} 13923 * @param paint The paint used to compose the layer. This argument is optional 13924 * and can be null. It is ignored when the layer type is 13925 * {@link #LAYER_TYPE_NONE} 13926 * 13927 * @see #getLayerType() 13928 * @see #LAYER_TYPE_NONE 13929 * @see #LAYER_TYPE_SOFTWARE 13930 * @see #LAYER_TYPE_HARDWARE 13931 * @see #setAlpha(float) 13932 * 13933 * @attr ref android.R.styleable#View_layerType 13934 */ 13935 public void setLayerType(int layerType, Paint paint) { 13936 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13937 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13938 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13939 } 13940 13941 boolean typeChanged = mRenderNode.setLayerType(layerType); 13942 13943 if (!typeChanged) { 13944 setLayerPaint(paint); 13945 return; 13946 } 13947 13948 // Destroy any previous software drawing cache if needed 13949 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13950 destroyDrawingCache(); 13951 } 13952 13953 mLayerType = layerType; 13954 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13955 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13956 mRenderNode.setLayerPaint(mLayerPaint); 13957 13958 // draw() behaves differently if we are on a layer, so we need to 13959 // invalidate() here 13960 invalidateParentCaches(); 13961 invalidate(true); 13962 } 13963 13964 /** 13965 * Updates the {@link Paint} object used with the current layer (used only if the current 13966 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13967 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13968 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13969 * ensure that the view gets redrawn immediately. 13970 * 13971 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13972 * instance that controls how the layer is composed on screen. The following 13973 * properties of the paint are taken into account when composing the layer:</p> 13974 * <ul> 13975 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13976 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13977 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13978 * </ul> 13979 * 13980 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13981 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 13982 * 13983 * @param paint The paint used to compose the layer. This argument is optional 13984 * and can be null. It is ignored when the layer type is 13985 * {@link #LAYER_TYPE_NONE} 13986 * 13987 * @see #setLayerType(int, android.graphics.Paint) 13988 */ 13989 public void setLayerPaint(Paint paint) { 13990 int layerType = getLayerType(); 13991 if (layerType != LAYER_TYPE_NONE) { 13992 mLayerPaint = paint == null ? new Paint() : paint; 13993 if (layerType == LAYER_TYPE_HARDWARE) { 13994 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13995 invalidateViewProperty(false, false); 13996 } 13997 } else { 13998 invalidate(); 13999 } 14000 } 14001 } 14002 14003 /** 14004 * Indicates whether this view has a static layer. A view with layer type 14005 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 14006 * dynamic. 14007 */ 14008 boolean hasStaticLayer() { 14009 return true; 14010 } 14011 14012 /** 14013 * Indicates what type of layer is currently associated with this view. By default 14014 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14015 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14016 * for more information on the different types of layers. 14017 * 14018 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14019 * {@link #LAYER_TYPE_HARDWARE} 14020 * 14021 * @see #setLayerType(int, android.graphics.Paint) 14022 * @see #buildLayer() 14023 * @see #LAYER_TYPE_NONE 14024 * @see #LAYER_TYPE_SOFTWARE 14025 * @see #LAYER_TYPE_HARDWARE 14026 */ 14027 public int getLayerType() { 14028 return mLayerType; 14029 } 14030 14031 /** 14032 * Forces this view's layer to be created and this view to be rendered 14033 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14034 * invoking this method will have no effect. 14035 * 14036 * This method can for instance be used to render a view into its layer before 14037 * starting an animation. If this view is complex, rendering into the layer 14038 * before starting the animation will avoid skipping frames. 14039 * 14040 * @throws IllegalStateException If this view is not attached to a window 14041 * 14042 * @see #setLayerType(int, android.graphics.Paint) 14043 */ 14044 public void buildLayer() { 14045 if (mLayerType == LAYER_TYPE_NONE) return; 14046 14047 final AttachInfo attachInfo = mAttachInfo; 14048 if (attachInfo == null) { 14049 throw new IllegalStateException("This view must be attached to a window first"); 14050 } 14051 14052 if (getWidth() == 0 || getHeight() == 0) { 14053 return; 14054 } 14055 14056 switch (mLayerType) { 14057 case LAYER_TYPE_HARDWARE: 14058 updateDisplayListIfDirty(); 14059 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14060 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14061 } 14062 break; 14063 case LAYER_TYPE_SOFTWARE: 14064 buildDrawingCache(true); 14065 break; 14066 } 14067 } 14068 14069 /** 14070 * If this View draws with a HardwareLayer, returns it. 14071 * Otherwise returns null 14072 * 14073 * TODO: Only TextureView uses this, can we eliminate it? 14074 */ 14075 HardwareLayer getHardwareLayer() { 14076 return null; 14077 } 14078 14079 /** 14080 * Destroys all hardware rendering resources. This method is invoked 14081 * when the system needs to reclaim resources. Upon execution of this 14082 * method, you should free any OpenGL resources created by the view. 14083 * 14084 * Note: you <strong>must</strong> call 14085 * <code>super.destroyHardwareResources()</code> when overriding 14086 * this method. 14087 * 14088 * @hide 14089 */ 14090 @CallSuper 14091 protected void destroyHardwareResources() { 14092 // Although the Layer will be destroyed by RenderNode, we want to release 14093 // the staging display list, which is also a signal to RenderNode that it's 14094 // safe to free its copy of the display list as it knows that we will 14095 // push an updated DisplayList if we try to draw again 14096 resetDisplayList(); 14097 } 14098 14099 /** 14100 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14101 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14102 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14103 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14104 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14105 * null.</p> 14106 * 14107 * <p>Enabling the drawing cache is similar to 14108 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14109 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14110 * drawing cache has no effect on rendering because the system uses a different mechanism 14111 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14112 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14113 * for information on how to enable software and hardware layers.</p> 14114 * 14115 * <p>This API can be used to manually generate 14116 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14117 * {@link #getDrawingCache()}.</p> 14118 * 14119 * @param enabled true to enable the drawing cache, false otherwise 14120 * 14121 * @see #isDrawingCacheEnabled() 14122 * @see #getDrawingCache() 14123 * @see #buildDrawingCache() 14124 * @see #setLayerType(int, android.graphics.Paint) 14125 */ 14126 public void setDrawingCacheEnabled(boolean enabled) { 14127 mCachingFailed = false; 14128 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14129 } 14130 14131 /** 14132 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14133 * 14134 * @return true if the drawing cache is enabled 14135 * 14136 * @see #setDrawingCacheEnabled(boolean) 14137 * @see #getDrawingCache() 14138 */ 14139 @ViewDebug.ExportedProperty(category = "drawing") 14140 public boolean isDrawingCacheEnabled() { 14141 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14142 } 14143 14144 /** 14145 * Debugging utility which recursively outputs the dirty state of a view and its 14146 * descendants. 14147 * 14148 * @hide 14149 */ 14150 @SuppressWarnings({"UnusedDeclaration"}) 14151 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14152 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14153 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14154 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 14155 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 14156 if (clear) { 14157 mPrivateFlags &= clearMask; 14158 } 14159 if (this instanceof ViewGroup) { 14160 ViewGroup parent = (ViewGroup) this; 14161 final int count = parent.getChildCount(); 14162 for (int i = 0; i < count; i++) { 14163 final View child = parent.getChildAt(i); 14164 child.outputDirtyFlags(indent + " ", clear, clearMask); 14165 } 14166 } 14167 } 14168 14169 /** 14170 * This method is used by ViewGroup to cause its children to restore or recreate their 14171 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 14172 * to recreate its own display list, which would happen if it went through the normal 14173 * draw/dispatchDraw mechanisms. 14174 * 14175 * @hide 14176 */ 14177 protected void dispatchGetDisplayList() {} 14178 14179 /** 14180 * A view that is not attached or hardware accelerated cannot create a display list. 14181 * This method checks these conditions and returns the appropriate result. 14182 * 14183 * @return true if view has the ability to create a display list, false otherwise. 14184 * 14185 * @hide 14186 */ 14187 public boolean canHaveDisplayList() { 14188 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 14189 } 14190 14191 private void updateDisplayListIfDirty() { 14192 final RenderNode renderNode = mRenderNode; 14193 if (!canHaveDisplayList()) { 14194 // can't populate RenderNode, don't try 14195 return; 14196 } 14197 14198 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 14199 || !renderNode.isValid() 14200 || (mRecreateDisplayList)) { 14201 // Don't need to recreate the display list, just need to tell our 14202 // children to restore/recreate theirs 14203 if (renderNode.isValid() 14204 && !mRecreateDisplayList) { 14205 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14206 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14207 dispatchGetDisplayList(); 14208 14209 return; // no work needed 14210 } 14211 14212 // If we got here, we're recreating it. Mark it as such to ensure that 14213 // we copy in child display lists into ours in drawChild() 14214 mRecreateDisplayList = true; 14215 14216 int width = mRight - mLeft; 14217 int height = mBottom - mTop; 14218 int layerType = getLayerType(); 14219 14220 final DisplayListCanvas canvas = renderNode.start(width, height); 14221 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14222 14223 try { 14224 final HardwareLayer layer = getHardwareLayer(); 14225 if (layer != null && layer.isValid()) { 14226 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14227 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14228 buildDrawingCache(true); 14229 Bitmap cache = getDrawingCache(true); 14230 if (cache != null) { 14231 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14232 } 14233 } else { 14234 computeScroll(); 14235 14236 canvas.translate(-mScrollX, -mScrollY); 14237 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14238 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14239 14240 // Fast path for layouts with no backgrounds 14241 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14242 dispatchDraw(canvas); 14243 if (mOverlay != null && !mOverlay.isEmpty()) { 14244 mOverlay.getOverlayView().draw(canvas); 14245 } 14246 } else { 14247 draw(canvas); 14248 } 14249 } 14250 } finally { 14251 renderNode.end(canvas); 14252 setDisplayListProperties(renderNode); 14253 } 14254 } else { 14255 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14256 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14257 } 14258 } 14259 14260 /** 14261 * Returns a RenderNode with View draw content recorded, which can be 14262 * used to draw this view again without executing its draw method. 14263 * 14264 * @return A RenderNode ready to replay, or null if caching is not enabled. 14265 * 14266 * @hide 14267 */ 14268 public RenderNode getDisplayList() { 14269 updateDisplayListIfDirty(); 14270 return mRenderNode; 14271 } 14272 14273 private void resetDisplayList() { 14274 if (mRenderNode.isValid()) { 14275 mRenderNode.destroyDisplayListData(); 14276 } 14277 14278 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14279 mBackgroundRenderNode.destroyDisplayListData(); 14280 } 14281 } 14282 14283 /** 14284 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14285 * 14286 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14287 * 14288 * @see #getDrawingCache(boolean) 14289 */ 14290 public Bitmap getDrawingCache() { 14291 return getDrawingCache(false); 14292 } 14293 14294 /** 14295 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14296 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14297 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14298 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14299 * request the drawing cache by calling this method and draw it on screen if the 14300 * returned bitmap is not null.</p> 14301 * 14302 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14303 * this method will create a bitmap of the same size as this view. Because this bitmap 14304 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14305 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14306 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14307 * size than the view. This implies that your application must be able to handle this 14308 * size.</p> 14309 * 14310 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14311 * the current density of the screen when the application is in compatibility 14312 * mode. 14313 * 14314 * @return A bitmap representing this view or null if cache is disabled. 14315 * 14316 * @see #setDrawingCacheEnabled(boolean) 14317 * @see #isDrawingCacheEnabled() 14318 * @see #buildDrawingCache(boolean) 14319 * @see #destroyDrawingCache() 14320 */ 14321 public Bitmap getDrawingCache(boolean autoScale) { 14322 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14323 return null; 14324 } 14325 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14326 buildDrawingCache(autoScale); 14327 } 14328 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14329 } 14330 14331 /** 14332 * <p>Frees the resources used by the drawing cache. If you call 14333 * {@link #buildDrawingCache()} manually without calling 14334 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14335 * should cleanup the cache with this method afterwards.</p> 14336 * 14337 * @see #setDrawingCacheEnabled(boolean) 14338 * @see #buildDrawingCache() 14339 * @see #getDrawingCache() 14340 */ 14341 public void destroyDrawingCache() { 14342 if (mDrawingCache != null) { 14343 mDrawingCache.recycle(); 14344 mDrawingCache = null; 14345 } 14346 if (mUnscaledDrawingCache != null) { 14347 mUnscaledDrawingCache.recycle(); 14348 mUnscaledDrawingCache = null; 14349 } 14350 } 14351 14352 /** 14353 * Setting a solid background color for the drawing cache's bitmaps will improve 14354 * performance and memory usage. Note, though that this should only be used if this 14355 * view will always be drawn on top of a solid color. 14356 * 14357 * @param color The background color to use for the drawing cache's bitmap 14358 * 14359 * @see #setDrawingCacheEnabled(boolean) 14360 * @see #buildDrawingCache() 14361 * @see #getDrawingCache() 14362 */ 14363 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 14364 if (color != mDrawingCacheBackgroundColor) { 14365 mDrawingCacheBackgroundColor = color; 14366 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14367 } 14368 } 14369 14370 /** 14371 * @see #setDrawingCacheBackgroundColor(int) 14372 * 14373 * @return The background color to used for the drawing cache's bitmap 14374 */ 14375 @ColorInt 14376 public int getDrawingCacheBackgroundColor() { 14377 return mDrawingCacheBackgroundColor; 14378 } 14379 14380 /** 14381 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14382 * 14383 * @see #buildDrawingCache(boolean) 14384 */ 14385 public void buildDrawingCache() { 14386 buildDrawingCache(false); 14387 } 14388 14389 /** 14390 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14391 * 14392 * <p>If you call {@link #buildDrawingCache()} manually without calling 14393 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14394 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14395 * 14396 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14397 * this method will create a bitmap of the same size as this view. Because this bitmap 14398 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14399 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14400 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14401 * size than the view. This implies that your application must be able to handle this 14402 * size.</p> 14403 * 14404 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14405 * you do not need the drawing cache bitmap, calling this method will increase memory 14406 * usage and cause the view to be rendered in software once, thus negatively impacting 14407 * performance.</p> 14408 * 14409 * @see #getDrawingCache() 14410 * @see #destroyDrawingCache() 14411 */ 14412 public void buildDrawingCache(boolean autoScale) { 14413 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14414 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14415 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 14416 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 14417 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 14418 } 14419 try { 14420 buildDrawingCacheImpl(autoScale); 14421 } finally { 14422 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 14423 } 14424 } 14425 } 14426 14427 /** 14428 * private, internal implementation of buildDrawingCache, used to enable tracing 14429 */ 14430 private void buildDrawingCacheImpl(boolean autoScale) { 14431 mCachingFailed = false; 14432 14433 int width = mRight - mLeft; 14434 int height = mBottom - mTop; 14435 14436 final AttachInfo attachInfo = mAttachInfo; 14437 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14438 14439 if (autoScale && scalingRequired) { 14440 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14441 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14442 } 14443 14444 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14445 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14446 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14447 14448 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14449 final long drawingCacheSize = 14450 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14451 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14452 if (width > 0 && height > 0) { 14453 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14454 + projectedBitmapSize + " bytes, only " 14455 + drawingCacheSize + " available"); 14456 } 14457 destroyDrawingCache(); 14458 mCachingFailed = true; 14459 return; 14460 } 14461 14462 boolean clear = true; 14463 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14464 14465 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14466 Bitmap.Config quality; 14467 if (!opaque) { 14468 // Never pick ARGB_4444 because it looks awful 14469 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14470 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14471 case DRAWING_CACHE_QUALITY_AUTO: 14472 case DRAWING_CACHE_QUALITY_LOW: 14473 case DRAWING_CACHE_QUALITY_HIGH: 14474 default: 14475 quality = Bitmap.Config.ARGB_8888; 14476 break; 14477 } 14478 } else { 14479 // Optimization for translucent windows 14480 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14481 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14482 } 14483 14484 // Try to cleanup memory 14485 if (bitmap != null) bitmap.recycle(); 14486 14487 try { 14488 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14489 width, height, quality); 14490 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14491 if (autoScale) { 14492 mDrawingCache = bitmap; 14493 } else { 14494 mUnscaledDrawingCache = bitmap; 14495 } 14496 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14497 } catch (OutOfMemoryError e) { 14498 // If there is not enough memory to create the bitmap cache, just 14499 // ignore the issue as bitmap caches are not required to draw the 14500 // view hierarchy 14501 if (autoScale) { 14502 mDrawingCache = null; 14503 } else { 14504 mUnscaledDrawingCache = null; 14505 } 14506 mCachingFailed = true; 14507 return; 14508 } 14509 14510 clear = drawingCacheBackgroundColor != 0; 14511 } 14512 14513 Canvas canvas; 14514 if (attachInfo != null) { 14515 canvas = attachInfo.mCanvas; 14516 if (canvas == null) { 14517 canvas = new Canvas(); 14518 } 14519 canvas.setBitmap(bitmap); 14520 // Temporarily clobber the cached Canvas in case one of our children 14521 // is also using a drawing cache. Without this, the children would 14522 // steal the canvas by attaching their own bitmap to it and bad, bad 14523 // thing would happen (invisible views, corrupted drawings, etc.) 14524 attachInfo.mCanvas = null; 14525 } else { 14526 // This case should hopefully never or seldom happen 14527 canvas = new Canvas(bitmap); 14528 } 14529 14530 if (clear) { 14531 bitmap.eraseColor(drawingCacheBackgroundColor); 14532 } 14533 14534 computeScroll(); 14535 final int restoreCount = canvas.save(); 14536 14537 if (autoScale && scalingRequired) { 14538 final float scale = attachInfo.mApplicationScale; 14539 canvas.scale(scale, scale); 14540 } 14541 14542 canvas.translate(-mScrollX, -mScrollY); 14543 14544 mPrivateFlags |= PFLAG_DRAWN; 14545 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14546 mLayerType != LAYER_TYPE_NONE) { 14547 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14548 } 14549 14550 // Fast path for layouts with no backgrounds 14551 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14552 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14553 dispatchDraw(canvas); 14554 if (mOverlay != null && !mOverlay.isEmpty()) { 14555 mOverlay.getOverlayView().draw(canvas); 14556 } 14557 } else { 14558 draw(canvas); 14559 } 14560 14561 canvas.restoreToCount(restoreCount); 14562 canvas.setBitmap(null); 14563 14564 if (attachInfo != null) { 14565 // Restore the cached Canvas for our siblings 14566 attachInfo.mCanvas = canvas; 14567 } 14568 } 14569 14570 /** 14571 * Create a snapshot of the view into a bitmap. We should probably make 14572 * some form of this public, but should think about the API. 14573 */ 14574 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14575 int width = mRight - mLeft; 14576 int height = mBottom - mTop; 14577 14578 final AttachInfo attachInfo = mAttachInfo; 14579 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14580 width = (int) ((width * scale) + 0.5f); 14581 height = (int) ((height * scale) + 0.5f); 14582 14583 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14584 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14585 if (bitmap == null) { 14586 throw new OutOfMemoryError(); 14587 } 14588 14589 Resources resources = getResources(); 14590 if (resources != null) { 14591 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14592 } 14593 14594 Canvas canvas; 14595 if (attachInfo != null) { 14596 canvas = attachInfo.mCanvas; 14597 if (canvas == null) { 14598 canvas = new Canvas(); 14599 } 14600 canvas.setBitmap(bitmap); 14601 // Temporarily clobber the cached Canvas in case one of our children 14602 // is also using a drawing cache. Without this, the children would 14603 // steal the canvas by attaching their own bitmap to it and bad, bad 14604 // things would happen (invisible views, corrupted drawings, etc.) 14605 attachInfo.mCanvas = null; 14606 } else { 14607 // This case should hopefully never or seldom happen 14608 canvas = new Canvas(bitmap); 14609 } 14610 14611 if ((backgroundColor & 0xff000000) != 0) { 14612 bitmap.eraseColor(backgroundColor); 14613 } 14614 14615 computeScroll(); 14616 final int restoreCount = canvas.save(); 14617 canvas.scale(scale, scale); 14618 canvas.translate(-mScrollX, -mScrollY); 14619 14620 // Temporarily remove the dirty mask 14621 int flags = mPrivateFlags; 14622 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14623 14624 // Fast path for layouts with no backgrounds 14625 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14626 dispatchDraw(canvas); 14627 if (mOverlay != null && !mOverlay.isEmpty()) { 14628 mOverlay.getOverlayView().draw(canvas); 14629 } 14630 } else { 14631 draw(canvas); 14632 } 14633 14634 mPrivateFlags = flags; 14635 14636 canvas.restoreToCount(restoreCount); 14637 canvas.setBitmap(null); 14638 14639 if (attachInfo != null) { 14640 // Restore the cached Canvas for our siblings 14641 attachInfo.mCanvas = canvas; 14642 } 14643 14644 return bitmap; 14645 } 14646 14647 /** 14648 * Indicates whether this View is currently in edit mode. A View is usually 14649 * in edit mode when displayed within a developer tool. For instance, if 14650 * this View is being drawn by a visual user interface builder, this method 14651 * should return true. 14652 * 14653 * Subclasses should check the return value of this method to provide 14654 * different behaviors if their normal behavior might interfere with the 14655 * host environment. For instance: the class spawns a thread in its 14656 * constructor, the drawing code relies on device-specific features, etc. 14657 * 14658 * This method is usually checked in the drawing code of custom widgets. 14659 * 14660 * @return True if this View is in edit mode, false otherwise. 14661 */ 14662 public boolean isInEditMode() { 14663 return false; 14664 } 14665 14666 /** 14667 * If the View draws content inside its padding and enables fading edges, 14668 * it needs to support padding offsets. Padding offsets are added to the 14669 * fading edges to extend the length of the fade so that it covers pixels 14670 * drawn inside the padding. 14671 * 14672 * Subclasses of this class should override this method if they need 14673 * to draw content inside the padding. 14674 * 14675 * @return True if padding offset must be applied, false otherwise. 14676 * 14677 * @see #getLeftPaddingOffset() 14678 * @see #getRightPaddingOffset() 14679 * @see #getTopPaddingOffset() 14680 * @see #getBottomPaddingOffset() 14681 * 14682 * @since CURRENT 14683 */ 14684 protected boolean isPaddingOffsetRequired() { 14685 return false; 14686 } 14687 14688 /** 14689 * Amount by which to extend the left fading region. Called only when 14690 * {@link #isPaddingOffsetRequired()} returns true. 14691 * 14692 * @return The left padding offset in pixels. 14693 * 14694 * @see #isPaddingOffsetRequired() 14695 * 14696 * @since CURRENT 14697 */ 14698 protected int getLeftPaddingOffset() { 14699 return 0; 14700 } 14701 14702 /** 14703 * Amount by which to extend the right fading region. Called only when 14704 * {@link #isPaddingOffsetRequired()} returns true. 14705 * 14706 * @return The right padding offset in pixels. 14707 * 14708 * @see #isPaddingOffsetRequired() 14709 * 14710 * @since CURRENT 14711 */ 14712 protected int getRightPaddingOffset() { 14713 return 0; 14714 } 14715 14716 /** 14717 * Amount by which to extend the top fading region. Called only when 14718 * {@link #isPaddingOffsetRequired()} returns true. 14719 * 14720 * @return The top padding offset in pixels. 14721 * 14722 * @see #isPaddingOffsetRequired() 14723 * 14724 * @since CURRENT 14725 */ 14726 protected int getTopPaddingOffset() { 14727 return 0; 14728 } 14729 14730 /** 14731 * Amount by which to extend the bottom fading region. Called only when 14732 * {@link #isPaddingOffsetRequired()} returns true. 14733 * 14734 * @return The bottom padding offset in pixels. 14735 * 14736 * @see #isPaddingOffsetRequired() 14737 * 14738 * @since CURRENT 14739 */ 14740 protected int getBottomPaddingOffset() { 14741 return 0; 14742 } 14743 14744 /** 14745 * @hide 14746 * @param offsetRequired 14747 */ 14748 protected int getFadeTop(boolean offsetRequired) { 14749 int top = mPaddingTop; 14750 if (offsetRequired) top += getTopPaddingOffset(); 14751 return top; 14752 } 14753 14754 /** 14755 * @hide 14756 * @param offsetRequired 14757 */ 14758 protected int getFadeHeight(boolean offsetRequired) { 14759 int padding = mPaddingTop; 14760 if (offsetRequired) padding += getTopPaddingOffset(); 14761 return mBottom - mTop - mPaddingBottom - padding; 14762 } 14763 14764 /** 14765 * <p>Indicates whether this view is attached to a hardware accelerated 14766 * window or not.</p> 14767 * 14768 * <p>Even if this method returns true, it does not mean that every call 14769 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14770 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14771 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14772 * window is hardware accelerated, 14773 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14774 * return false, and this method will return true.</p> 14775 * 14776 * @return True if the view is attached to a window and the window is 14777 * hardware accelerated; false in any other case. 14778 */ 14779 @ViewDebug.ExportedProperty(category = "drawing") 14780 public boolean isHardwareAccelerated() { 14781 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14782 } 14783 14784 /** 14785 * Sets a rectangular area on this view to which the view will be clipped 14786 * when it is drawn. Setting the value to null will remove the clip bounds 14787 * and the view will draw normally, using its full bounds. 14788 * 14789 * @param clipBounds The rectangular area, in the local coordinates of 14790 * this view, to which future drawing operations will be clipped. 14791 */ 14792 public void setClipBounds(Rect clipBounds) { 14793 if (clipBounds == mClipBounds 14794 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 14795 return; 14796 } 14797 if (clipBounds != null) { 14798 if (mClipBounds == null) { 14799 mClipBounds = new Rect(clipBounds); 14800 } else { 14801 mClipBounds.set(clipBounds); 14802 } 14803 } else { 14804 mClipBounds = null; 14805 } 14806 mRenderNode.setClipBounds(mClipBounds); 14807 invalidateViewProperty(false, false); 14808 } 14809 14810 /** 14811 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14812 * 14813 * @return A copy of the current clip bounds if clip bounds are set, 14814 * otherwise null. 14815 */ 14816 public Rect getClipBounds() { 14817 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14818 } 14819 14820 /** 14821 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14822 * case of an active Animation being run on the view. 14823 */ 14824 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14825 Animation a, boolean scalingRequired) { 14826 Transformation invalidationTransform; 14827 final int flags = parent.mGroupFlags; 14828 final boolean initialized = a.isInitialized(); 14829 if (!initialized) { 14830 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14831 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14832 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14833 onAnimationStart(); 14834 } 14835 14836 final Transformation t = parent.getChildTransformation(); 14837 boolean more = a.getTransformation(drawingTime, t, 1f); 14838 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14839 if (parent.mInvalidationTransformation == null) { 14840 parent.mInvalidationTransformation = new Transformation(); 14841 } 14842 invalidationTransform = parent.mInvalidationTransformation; 14843 a.getTransformation(drawingTime, invalidationTransform, 1f); 14844 } else { 14845 invalidationTransform = t; 14846 } 14847 14848 if (more) { 14849 if (!a.willChangeBounds()) { 14850 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14851 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14852 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14853 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14854 // The child need to draw an animation, potentially offscreen, so 14855 // make sure we do not cancel invalidate requests 14856 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14857 parent.invalidate(mLeft, mTop, mRight, mBottom); 14858 } 14859 } else { 14860 if (parent.mInvalidateRegion == null) { 14861 parent.mInvalidateRegion = new RectF(); 14862 } 14863 final RectF region = parent.mInvalidateRegion; 14864 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14865 invalidationTransform); 14866 14867 // The child need to draw an animation, potentially offscreen, so 14868 // make sure we do not cancel invalidate requests 14869 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14870 14871 final int left = mLeft + (int) region.left; 14872 final int top = mTop + (int) region.top; 14873 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14874 top + (int) (region.height() + .5f)); 14875 } 14876 } 14877 return more; 14878 } 14879 14880 /** 14881 * This method is called by getDisplayList() when a display list is recorded for a View. 14882 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14883 */ 14884 void setDisplayListProperties(RenderNode renderNode) { 14885 if (renderNode != null) { 14886 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14887 renderNode.setClipToBounds(mParent instanceof ViewGroup 14888 && ((ViewGroup) mParent).getClipChildren()); 14889 14890 float alpha = 1; 14891 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14892 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14893 ViewGroup parentVG = (ViewGroup) mParent; 14894 final Transformation t = parentVG.getChildTransformation(); 14895 if (parentVG.getChildStaticTransformation(this, t)) { 14896 final int transformType = t.getTransformationType(); 14897 if (transformType != Transformation.TYPE_IDENTITY) { 14898 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14899 alpha = t.getAlpha(); 14900 } 14901 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14902 renderNode.setStaticMatrix(t.getMatrix()); 14903 } 14904 } 14905 } 14906 } 14907 if (mTransformationInfo != null) { 14908 alpha *= getFinalAlpha(); 14909 if (alpha < 1) { 14910 final int multipliedAlpha = (int) (255 * alpha); 14911 if (onSetAlpha(multipliedAlpha)) { 14912 alpha = 1; 14913 } 14914 } 14915 renderNode.setAlpha(alpha); 14916 } else if (alpha < 1) { 14917 renderNode.setAlpha(alpha); 14918 } 14919 } 14920 } 14921 14922 /** 14923 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14924 * This draw() method is an implementation detail and is not intended to be overridden or 14925 * to be called from anywhere else other than ViewGroup.drawChild(). 14926 */ 14927 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14928 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14929 boolean more = false; 14930 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14931 final int flags = parent.mGroupFlags; 14932 14933 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14934 parent.getChildTransformation().clear(); 14935 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14936 } 14937 14938 Transformation transformToApply = null; 14939 boolean concatMatrix = false; 14940 14941 boolean scalingRequired = false; 14942 boolean caching; 14943 int layerType = getLayerType(); 14944 14945 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14946 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14947 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14948 caching = true; 14949 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14950 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14951 } else { 14952 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14953 } 14954 14955 final Animation a = getAnimation(); 14956 if (a != null) { 14957 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14958 concatMatrix = a.willChangeTransformationMatrix(); 14959 if (concatMatrix) { 14960 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14961 } 14962 transformToApply = parent.getChildTransformation(); 14963 } else { 14964 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14965 // No longer animating: clear out old animation matrix 14966 mRenderNode.setAnimationMatrix(null); 14967 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14968 } 14969 if (!usingRenderNodeProperties && 14970 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14971 final Transformation t = parent.getChildTransformation(); 14972 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14973 if (hasTransform) { 14974 final int transformType = t.getTransformationType(); 14975 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14976 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14977 } 14978 } 14979 } 14980 14981 concatMatrix |= !childHasIdentityMatrix; 14982 14983 // Sets the flag as early as possible to allow draw() implementations 14984 // to call invalidate() successfully when doing animations 14985 mPrivateFlags |= PFLAG_DRAWN; 14986 14987 if (!concatMatrix && 14988 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14989 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14990 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14991 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14992 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14993 return more; 14994 } 14995 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14996 14997 if (hardwareAccelerated) { 14998 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14999 // retain the flag's value temporarily in the mRecreateDisplayList flag 15000 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 15001 mPrivateFlags &= ~PFLAG_INVALIDATED; 15002 } 15003 15004 RenderNode renderNode = null; 15005 Bitmap cache = null; 15006 boolean hasDisplayList = false; 15007 if (caching) { 15008 if (!hardwareAccelerated) { 15009 if (layerType != LAYER_TYPE_NONE) { 15010 layerType = LAYER_TYPE_SOFTWARE; 15011 buildDrawingCache(true); 15012 } 15013 cache = getDrawingCache(true); 15014 } else { 15015 switch (layerType) { 15016 case LAYER_TYPE_SOFTWARE: 15017 if (usingRenderNodeProperties) { 15018 hasDisplayList = canHaveDisplayList(); 15019 } else { 15020 buildDrawingCache(true); 15021 cache = getDrawingCache(true); 15022 } 15023 break; 15024 case LAYER_TYPE_HARDWARE: 15025 if (usingRenderNodeProperties) { 15026 hasDisplayList = canHaveDisplayList(); 15027 } 15028 break; 15029 case LAYER_TYPE_NONE: 15030 // Delay getting the display list until animation-driven alpha values are 15031 // set up and possibly passed on to the view 15032 hasDisplayList = canHaveDisplayList(); 15033 break; 15034 } 15035 } 15036 } 15037 usingRenderNodeProperties &= hasDisplayList; 15038 if (usingRenderNodeProperties) { 15039 renderNode = getDisplayList(); 15040 if (!renderNode.isValid()) { 15041 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15042 // to getDisplayList(), the display list will be marked invalid and we should not 15043 // try to use it again. 15044 renderNode = null; 15045 hasDisplayList = false; 15046 usingRenderNodeProperties = false; 15047 } 15048 } 15049 15050 int sx = 0; 15051 int sy = 0; 15052 if (!hasDisplayList) { 15053 computeScroll(); 15054 sx = mScrollX; 15055 sy = mScrollY; 15056 } 15057 15058 final boolean hasNoCache = cache == null || hasDisplayList; 15059 final boolean offsetForScroll = cache == null && !hasDisplayList && 15060 layerType != LAYER_TYPE_HARDWARE; 15061 15062 int restoreTo = -1; 15063 if (!usingRenderNodeProperties || transformToApply != null) { 15064 restoreTo = canvas.save(); 15065 } 15066 if (offsetForScroll) { 15067 canvas.translate(mLeft - sx, mTop - sy); 15068 } else { 15069 if (!usingRenderNodeProperties) { 15070 canvas.translate(mLeft, mTop); 15071 } 15072 if (scalingRequired) { 15073 if (usingRenderNodeProperties) { 15074 // TODO: Might not need this if we put everything inside the DL 15075 restoreTo = canvas.save(); 15076 } 15077 // mAttachInfo cannot be null, otherwise scalingRequired == false 15078 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15079 canvas.scale(scale, scale); 15080 } 15081 } 15082 15083 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 15084 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 15085 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15086 if (transformToApply != null || !childHasIdentityMatrix) { 15087 int transX = 0; 15088 int transY = 0; 15089 15090 if (offsetForScroll) { 15091 transX = -sx; 15092 transY = -sy; 15093 } 15094 15095 if (transformToApply != null) { 15096 if (concatMatrix) { 15097 if (usingRenderNodeProperties) { 15098 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15099 } else { 15100 // Undo the scroll translation, apply the transformation matrix, 15101 // then redo the scroll translate to get the correct result. 15102 canvas.translate(-transX, -transY); 15103 canvas.concat(transformToApply.getMatrix()); 15104 canvas.translate(transX, transY); 15105 } 15106 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15107 } 15108 15109 float transformAlpha = transformToApply.getAlpha(); 15110 if (transformAlpha < 1) { 15111 alpha *= transformAlpha; 15112 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15113 } 15114 } 15115 15116 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 15117 canvas.translate(-transX, -transY); 15118 canvas.concat(getMatrix()); 15119 canvas.translate(transX, transY); 15120 } 15121 } 15122 15123 // Deal with alpha if it is or used to be <1 15124 if (alpha < 1 || 15125 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15126 if (alpha < 1) { 15127 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15128 } else { 15129 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15130 } 15131 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15132 if (hasNoCache) { 15133 final int multipliedAlpha = (int) (255 * alpha); 15134 if (!onSetAlpha(multipliedAlpha)) { 15135 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15136 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 15137 layerType != LAYER_TYPE_NONE) { 15138 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 15139 } 15140 if (usingRenderNodeProperties) { 15141 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15142 } else if (layerType == LAYER_TYPE_NONE) { 15143 final int scrollX = hasDisplayList ? 0 : sx; 15144 final int scrollY = hasDisplayList ? 0 : sy; 15145 canvas.saveLayerAlpha(scrollX, scrollY, 15146 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 15147 multipliedAlpha, layerFlags); 15148 } 15149 } else { 15150 // Alpha is handled by the child directly, clobber the layer's alpha 15151 mPrivateFlags |= PFLAG_ALPHA_SET; 15152 } 15153 } 15154 } 15155 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15156 onSetAlpha(255); 15157 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15158 } 15159 15160 if (!usingRenderNodeProperties) { 15161 // apply clips directly, since RenderNode won't do it for this draw 15162 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 15163 && cache == null) { 15164 if (offsetForScroll) { 15165 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 15166 } else { 15167 if (!scalingRequired || cache == null) { 15168 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 15169 } else { 15170 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15171 } 15172 } 15173 } 15174 15175 if (mClipBounds != null) { 15176 // clip bounds ignore scroll 15177 canvas.clipRect(mClipBounds); 15178 } 15179 } 15180 15181 15182 15183 if (!usingRenderNodeProperties && hasDisplayList) { 15184 renderNode = getDisplayList(); 15185 if (!renderNode.isValid()) { 15186 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15187 // to getDisplayList(), the display list will be marked invalid and we should not 15188 // try to use it again. 15189 renderNode = null; 15190 hasDisplayList = false; 15191 } 15192 } 15193 15194 if (hasNoCache) { 15195 boolean layerRendered = false; 15196 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 15197 final HardwareLayer layer = getHardwareLayer(); 15198 if (layer != null && layer.isValid()) { 15199 int restoreAlpha = mLayerPaint.getAlpha(); 15200 mLayerPaint.setAlpha((int) (alpha * 255)); 15201 ((DisplayListCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15202 mLayerPaint.setAlpha(restoreAlpha); 15203 layerRendered = true; 15204 } else { 15205 final int scrollX = hasDisplayList ? 0 : sx; 15206 final int scrollY = hasDisplayList ? 0 : sy; 15207 canvas.saveLayer(scrollX, scrollY, 15208 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15209 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15210 } 15211 } 15212 15213 if (!layerRendered) { 15214 if (!hasDisplayList) { 15215 // Fast path for layouts with no backgrounds 15216 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15217 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15218 dispatchDraw(canvas); 15219 } else { 15220 draw(canvas); 15221 } 15222 } else { 15223 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15224 ((DisplayListCanvas) canvas).drawRenderNode(renderNode, flags); 15225 } 15226 } 15227 } else if (cache != null) { 15228 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15229 Paint cachePaint; 15230 int restoreAlpha = 0; 15231 15232 if (layerType == LAYER_TYPE_NONE) { 15233 cachePaint = parent.mCachePaint; 15234 if (cachePaint == null) { 15235 cachePaint = new Paint(); 15236 cachePaint.setDither(false); 15237 parent.mCachePaint = cachePaint; 15238 } 15239 } else { 15240 cachePaint = mLayerPaint; 15241 restoreAlpha = mLayerPaint.getAlpha(); 15242 } 15243 cachePaint.setAlpha((int) (alpha * 255)); 15244 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15245 cachePaint.setAlpha(restoreAlpha); 15246 } 15247 15248 if (restoreTo >= 0) { 15249 canvas.restoreToCount(restoreTo); 15250 } 15251 15252 if (a != null && !more) { 15253 if (!hardwareAccelerated && !a.getFillAfter()) { 15254 onSetAlpha(255); 15255 } 15256 parent.finishAnimatingView(this, a); 15257 } 15258 15259 if (more && hardwareAccelerated) { 15260 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15261 // alpha animations should cause the child to recreate its display list 15262 invalidate(true); 15263 } 15264 } 15265 15266 mRecreateDisplayList = false; 15267 15268 return more; 15269 } 15270 15271 /** 15272 * Manually render this view (and all of its children) to the given Canvas. 15273 * The view must have already done a full layout before this function is 15274 * called. When implementing a view, implement 15275 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15276 * If you do need to override this method, call the superclass version. 15277 * 15278 * @param canvas The Canvas to which the View is rendered. 15279 */ 15280 @CallSuper 15281 public void draw(Canvas canvas) { 15282 final int privateFlags = mPrivateFlags; 15283 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15284 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15285 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15286 15287 /* 15288 * Draw traversal performs several drawing steps which must be executed 15289 * in the appropriate order: 15290 * 15291 * 1. Draw the background 15292 * 2. If necessary, save the canvas' layers to prepare for fading 15293 * 3. Draw view's content 15294 * 4. Draw children 15295 * 5. If necessary, draw the fading edges and restore layers 15296 * 6. Draw decorations (scrollbars for instance) 15297 */ 15298 15299 // Step 1, draw the background, if needed 15300 int saveCount; 15301 15302 if (!dirtyOpaque) { 15303 drawBackground(canvas); 15304 } 15305 15306 // skip step 2 & 5 if possible (common case) 15307 final int viewFlags = mViewFlags; 15308 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15309 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15310 if (!verticalEdges && !horizontalEdges) { 15311 // Step 3, draw the content 15312 if (!dirtyOpaque) onDraw(canvas); 15313 15314 // Step 4, draw the children 15315 dispatchDraw(canvas); 15316 15317 // Step 6, draw decorations (scrollbars) 15318 onDrawScrollBars(canvas); 15319 15320 if (mOverlay != null && !mOverlay.isEmpty()) { 15321 mOverlay.getOverlayView().dispatchDraw(canvas); 15322 } 15323 15324 // we're done... 15325 return; 15326 } 15327 15328 /* 15329 * Here we do the full fledged routine... 15330 * (this is an uncommon case where speed matters less, 15331 * this is why we repeat some of the tests that have been 15332 * done above) 15333 */ 15334 15335 boolean drawTop = false; 15336 boolean drawBottom = false; 15337 boolean drawLeft = false; 15338 boolean drawRight = false; 15339 15340 float topFadeStrength = 0.0f; 15341 float bottomFadeStrength = 0.0f; 15342 float leftFadeStrength = 0.0f; 15343 float rightFadeStrength = 0.0f; 15344 15345 // Step 2, save the canvas' layers 15346 int paddingLeft = mPaddingLeft; 15347 15348 final boolean offsetRequired = isPaddingOffsetRequired(); 15349 if (offsetRequired) { 15350 paddingLeft += getLeftPaddingOffset(); 15351 } 15352 15353 int left = mScrollX + paddingLeft; 15354 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15355 int top = mScrollY + getFadeTop(offsetRequired); 15356 int bottom = top + getFadeHeight(offsetRequired); 15357 15358 if (offsetRequired) { 15359 right += getRightPaddingOffset(); 15360 bottom += getBottomPaddingOffset(); 15361 } 15362 15363 final ScrollabilityCache scrollabilityCache = mScrollCache; 15364 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15365 int length = (int) fadeHeight; 15366 15367 // clip the fade length if top and bottom fades overlap 15368 // overlapping fades produce odd-looking artifacts 15369 if (verticalEdges && (top + length > bottom - length)) { 15370 length = (bottom - top) / 2; 15371 } 15372 15373 // also clip horizontal fades if necessary 15374 if (horizontalEdges && (left + length > right - length)) { 15375 length = (right - left) / 2; 15376 } 15377 15378 if (verticalEdges) { 15379 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15380 drawTop = topFadeStrength * fadeHeight > 1.0f; 15381 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15382 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15383 } 15384 15385 if (horizontalEdges) { 15386 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15387 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15388 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15389 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15390 } 15391 15392 saveCount = canvas.getSaveCount(); 15393 15394 int solidColor = getSolidColor(); 15395 if (solidColor == 0) { 15396 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15397 15398 if (drawTop) { 15399 canvas.saveLayer(left, top, right, top + length, null, flags); 15400 } 15401 15402 if (drawBottom) { 15403 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15404 } 15405 15406 if (drawLeft) { 15407 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15408 } 15409 15410 if (drawRight) { 15411 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15412 } 15413 } else { 15414 scrollabilityCache.setFadeColor(solidColor); 15415 } 15416 15417 // Step 3, draw the content 15418 if (!dirtyOpaque) onDraw(canvas); 15419 15420 // Step 4, draw the children 15421 dispatchDraw(canvas); 15422 15423 // Step 5, draw the fade effect and restore layers 15424 final Paint p = scrollabilityCache.paint; 15425 final Matrix matrix = scrollabilityCache.matrix; 15426 final Shader fade = scrollabilityCache.shader; 15427 15428 if (drawTop) { 15429 matrix.setScale(1, fadeHeight * topFadeStrength); 15430 matrix.postTranslate(left, top); 15431 fade.setLocalMatrix(matrix); 15432 p.setShader(fade); 15433 canvas.drawRect(left, top, right, top + length, p); 15434 } 15435 15436 if (drawBottom) { 15437 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15438 matrix.postRotate(180); 15439 matrix.postTranslate(left, bottom); 15440 fade.setLocalMatrix(matrix); 15441 p.setShader(fade); 15442 canvas.drawRect(left, bottom - length, right, bottom, p); 15443 } 15444 15445 if (drawLeft) { 15446 matrix.setScale(1, fadeHeight * leftFadeStrength); 15447 matrix.postRotate(-90); 15448 matrix.postTranslate(left, top); 15449 fade.setLocalMatrix(matrix); 15450 p.setShader(fade); 15451 canvas.drawRect(left, top, left + length, bottom, p); 15452 } 15453 15454 if (drawRight) { 15455 matrix.setScale(1, fadeHeight * rightFadeStrength); 15456 matrix.postRotate(90); 15457 matrix.postTranslate(right, top); 15458 fade.setLocalMatrix(matrix); 15459 p.setShader(fade); 15460 canvas.drawRect(right - length, top, right, bottom, p); 15461 } 15462 15463 canvas.restoreToCount(saveCount); 15464 15465 // Step 6, draw decorations (scrollbars) 15466 onDrawScrollBars(canvas); 15467 15468 if (mOverlay != null && !mOverlay.isEmpty()) { 15469 mOverlay.getOverlayView().dispatchDraw(canvas); 15470 } 15471 } 15472 15473 /** 15474 * Draws the background onto the specified canvas. 15475 * 15476 * @param canvas Canvas on which to draw the background 15477 */ 15478 private void drawBackground(Canvas canvas) { 15479 final Drawable background = mBackground; 15480 if (background == null) { 15481 return; 15482 } 15483 15484 if (mBackgroundSizeChanged) { 15485 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15486 mBackgroundSizeChanged = false; 15487 rebuildOutline(); 15488 } 15489 15490 // Attempt to use a display list if requested. 15491 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15492 && mAttachInfo.mHardwareRenderer != null) { 15493 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15494 15495 final RenderNode renderNode = mBackgroundRenderNode; 15496 if (renderNode != null && renderNode.isValid()) { 15497 setBackgroundRenderNodeProperties(renderNode); 15498 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 15499 return; 15500 } 15501 } 15502 15503 final int scrollX = mScrollX; 15504 final int scrollY = mScrollY; 15505 if ((scrollX | scrollY) == 0) { 15506 background.draw(canvas); 15507 } else { 15508 canvas.translate(scrollX, scrollY); 15509 background.draw(canvas); 15510 canvas.translate(-scrollX, -scrollY); 15511 } 15512 } 15513 15514 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 15515 renderNode.setTranslationX(mScrollX); 15516 renderNode.setTranslationY(mScrollY); 15517 } 15518 15519 /** 15520 * Creates a new display list or updates the existing display list for the 15521 * specified Drawable. 15522 * 15523 * @param drawable Drawable for which to create a display list 15524 * @param renderNode Existing RenderNode, or {@code null} 15525 * @return A valid display list for the specified drawable 15526 */ 15527 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15528 if (renderNode == null) { 15529 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15530 } 15531 15532 final Rect bounds = drawable.getBounds(); 15533 final int width = bounds.width(); 15534 final int height = bounds.height(); 15535 final DisplayListCanvas canvas = renderNode.start(width, height); 15536 15537 // Reverse left/top translation done by drawable canvas, which will 15538 // instead be applied by rendernode's LTRB bounds below. This way, the 15539 // drawable's bounds match with its rendernode bounds and its content 15540 // will lie within those bounds in the rendernode tree. 15541 canvas.translate(-bounds.left, -bounds.top); 15542 15543 try { 15544 drawable.draw(canvas); 15545 } finally { 15546 renderNode.end(canvas); 15547 } 15548 15549 // Set up drawable properties that are view-independent. 15550 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15551 renderNode.setProjectBackwards(drawable.isProjected()); 15552 renderNode.setProjectionReceiver(true); 15553 renderNode.setClipToBounds(false); 15554 return renderNode; 15555 } 15556 15557 /** 15558 * Returns the overlay for this view, creating it if it does not yet exist. 15559 * Adding drawables to the overlay will cause them to be displayed whenever 15560 * the view itself is redrawn. Objects in the overlay should be actively 15561 * managed: remove them when they should not be displayed anymore. The 15562 * overlay will always have the same size as its host view. 15563 * 15564 * <p>Note: Overlays do not currently work correctly with {@link 15565 * SurfaceView} or {@link TextureView}; contents in overlays for these 15566 * types of views may not display correctly.</p> 15567 * 15568 * @return The ViewOverlay object for this view. 15569 * @see ViewOverlay 15570 */ 15571 public ViewOverlay getOverlay() { 15572 if (mOverlay == null) { 15573 mOverlay = new ViewOverlay(mContext, this); 15574 } 15575 return mOverlay; 15576 } 15577 15578 /** 15579 * Override this if your view is known to always be drawn on top of a solid color background, 15580 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15581 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15582 * should be set to 0xFF. 15583 * 15584 * @see #setVerticalFadingEdgeEnabled(boolean) 15585 * @see #setHorizontalFadingEdgeEnabled(boolean) 15586 * 15587 * @return The known solid color background for this view, or 0 if the color may vary 15588 */ 15589 @ViewDebug.ExportedProperty(category = "drawing") 15590 @ColorInt 15591 public int getSolidColor() { 15592 return 0; 15593 } 15594 15595 /** 15596 * Build a human readable string representation of the specified view flags. 15597 * 15598 * @param flags the view flags to convert to a string 15599 * @return a String representing the supplied flags 15600 */ 15601 private static String printFlags(int flags) { 15602 String output = ""; 15603 int numFlags = 0; 15604 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15605 output += "TAKES_FOCUS"; 15606 numFlags++; 15607 } 15608 15609 switch (flags & VISIBILITY_MASK) { 15610 case INVISIBLE: 15611 if (numFlags > 0) { 15612 output += " "; 15613 } 15614 output += "INVISIBLE"; 15615 // USELESS HERE numFlags++; 15616 break; 15617 case GONE: 15618 if (numFlags > 0) { 15619 output += " "; 15620 } 15621 output += "GONE"; 15622 // USELESS HERE numFlags++; 15623 break; 15624 default: 15625 break; 15626 } 15627 return output; 15628 } 15629 15630 /** 15631 * Build a human readable string representation of the specified private 15632 * view flags. 15633 * 15634 * @param privateFlags the private view flags to convert to a string 15635 * @return a String representing the supplied flags 15636 */ 15637 private static String printPrivateFlags(int privateFlags) { 15638 String output = ""; 15639 int numFlags = 0; 15640 15641 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15642 output += "WANTS_FOCUS"; 15643 numFlags++; 15644 } 15645 15646 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15647 if (numFlags > 0) { 15648 output += " "; 15649 } 15650 output += "FOCUSED"; 15651 numFlags++; 15652 } 15653 15654 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15655 if (numFlags > 0) { 15656 output += " "; 15657 } 15658 output += "SELECTED"; 15659 numFlags++; 15660 } 15661 15662 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15663 if (numFlags > 0) { 15664 output += " "; 15665 } 15666 output += "IS_ROOT_NAMESPACE"; 15667 numFlags++; 15668 } 15669 15670 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15671 if (numFlags > 0) { 15672 output += " "; 15673 } 15674 output += "HAS_BOUNDS"; 15675 numFlags++; 15676 } 15677 15678 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15679 if (numFlags > 0) { 15680 output += " "; 15681 } 15682 output += "DRAWN"; 15683 // USELESS HERE numFlags++; 15684 } 15685 return output; 15686 } 15687 15688 /** 15689 * <p>Indicates whether or not this view's layout will be requested during 15690 * the next hierarchy layout pass.</p> 15691 * 15692 * @return true if the layout will be forced during next layout pass 15693 */ 15694 public boolean isLayoutRequested() { 15695 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15696 } 15697 15698 /** 15699 * Return true if o is a ViewGroup that is laying out using optical bounds. 15700 * @hide 15701 */ 15702 public static boolean isLayoutModeOptical(Object o) { 15703 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15704 } 15705 15706 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15707 Insets parentInsets = mParent instanceof View ? 15708 ((View) mParent).getOpticalInsets() : Insets.NONE; 15709 Insets childInsets = getOpticalInsets(); 15710 return setFrame( 15711 left + parentInsets.left - childInsets.left, 15712 top + parentInsets.top - childInsets.top, 15713 right + parentInsets.left + childInsets.right, 15714 bottom + parentInsets.top + childInsets.bottom); 15715 } 15716 15717 /** 15718 * Assign a size and position to a view and all of its 15719 * descendants 15720 * 15721 * <p>This is the second phase of the layout mechanism. 15722 * (The first is measuring). In this phase, each parent calls 15723 * layout on all of its children to position them. 15724 * This is typically done using the child measurements 15725 * that were stored in the measure pass().</p> 15726 * 15727 * <p>Derived classes should not override this method. 15728 * Derived classes with children should override 15729 * onLayout. In that method, they should 15730 * call layout on each of their children.</p> 15731 * 15732 * @param l Left position, relative to parent 15733 * @param t Top position, relative to parent 15734 * @param r Right position, relative to parent 15735 * @param b Bottom position, relative to parent 15736 */ 15737 @SuppressWarnings({"unchecked"}) 15738 public void layout(int l, int t, int r, int b) { 15739 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15740 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15741 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15742 } 15743 15744 int oldL = mLeft; 15745 int oldT = mTop; 15746 int oldB = mBottom; 15747 int oldR = mRight; 15748 15749 boolean changed = isLayoutModeOptical(mParent) ? 15750 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15751 15752 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15753 onLayout(changed, l, t, r, b); 15754 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15755 15756 ListenerInfo li = mListenerInfo; 15757 if (li != null && li.mOnLayoutChangeListeners != null) { 15758 ArrayList<OnLayoutChangeListener> listenersCopy = 15759 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15760 int numListeners = listenersCopy.size(); 15761 for (int i = 0; i < numListeners; ++i) { 15762 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15763 } 15764 } 15765 } 15766 15767 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15768 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15769 } 15770 15771 /** 15772 * Called from layout when this view should 15773 * assign a size and position to each of its children. 15774 * 15775 * Derived classes with children should override 15776 * this method and call layout on each of 15777 * their children. 15778 * @param changed This is a new size or position for this view 15779 * @param left Left position, relative to parent 15780 * @param top Top position, relative to parent 15781 * @param right Right position, relative to parent 15782 * @param bottom Bottom position, relative to parent 15783 */ 15784 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15785 } 15786 15787 /** 15788 * Assign a size and position to this view. 15789 * 15790 * This is called from layout. 15791 * 15792 * @param left Left position, relative to parent 15793 * @param top Top position, relative to parent 15794 * @param right Right position, relative to parent 15795 * @param bottom Bottom position, relative to parent 15796 * @return true if the new size and position are different than the 15797 * previous ones 15798 * {@hide} 15799 */ 15800 protected boolean setFrame(int left, int top, int right, int bottom) { 15801 boolean changed = false; 15802 15803 if (DBG) { 15804 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15805 + right + "," + bottom + ")"); 15806 } 15807 15808 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15809 changed = true; 15810 15811 // Remember our drawn bit 15812 int drawn = mPrivateFlags & PFLAG_DRAWN; 15813 15814 int oldWidth = mRight - mLeft; 15815 int oldHeight = mBottom - mTop; 15816 int newWidth = right - left; 15817 int newHeight = bottom - top; 15818 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15819 15820 // Invalidate our old position 15821 invalidate(sizeChanged); 15822 15823 mLeft = left; 15824 mTop = top; 15825 mRight = right; 15826 mBottom = bottom; 15827 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15828 15829 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15830 15831 15832 if (sizeChanged) { 15833 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15834 } 15835 15836 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 15837 // If we are visible, force the DRAWN bit to on so that 15838 // this invalidate will go through (at least to our parent). 15839 // This is because someone may have invalidated this view 15840 // before this call to setFrame came in, thereby clearing 15841 // the DRAWN bit. 15842 mPrivateFlags |= PFLAG_DRAWN; 15843 invalidate(sizeChanged); 15844 // parent display list may need to be recreated based on a change in the bounds 15845 // of any child 15846 invalidateParentCaches(); 15847 } 15848 15849 // Reset drawn bit to original value (invalidate turns it off) 15850 mPrivateFlags |= drawn; 15851 15852 mBackgroundSizeChanged = true; 15853 15854 notifySubtreeAccessibilityStateChangedIfNeeded(); 15855 } 15856 return changed; 15857 } 15858 15859 /** 15860 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 15861 * @hide 15862 */ 15863 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 15864 setFrame(left, top, right, bottom); 15865 } 15866 15867 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15868 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15869 if (mOverlay != null) { 15870 mOverlay.getOverlayView().setRight(newWidth); 15871 mOverlay.getOverlayView().setBottom(newHeight); 15872 } 15873 rebuildOutline(); 15874 } 15875 15876 /** 15877 * Finalize inflating a view from XML. This is called as the last phase 15878 * of inflation, after all child views have been added. 15879 * 15880 * <p>Even if the subclass overrides onFinishInflate, they should always be 15881 * sure to call the super method, so that we get called. 15882 */ 15883 @CallSuper 15884 protected void onFinishInflate() { 15885 } 15886 15887 /** 15888 * Returns the resources associated with this view. 15889 * 15890 * @return Resources object. 15891 */ 15892 public Resources getResources() { 15893 return mResources; 15894 } 15895 15896 /** 15897 * Invalidates the specified Drawable. 15898 * 15899 * @param drawable the drawable to invalidate 15900 */ 15901 @Override 15902 public void invalidateDrawable(@NonNull Drawable drawable) { 15903 if (verifyDrawable(drawable)) { 15904 final Rect dirty = drawable.getDirtyBounds(); 15905 final int scrollX = mScrollX; 15906 final int scrollY = mScrollY; 15907 15908 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15909 dirty.right + scrollX, dirty.bottom + scrollY); 15910 rebuildOutline(); 15911 } 15912 } 15913 15914 /** 15915 * Schedules an action on a drawable to occur at a specified time. 15916 * 15917 * @param who the recipient of the action 15918 * @param what the action to run on the drawable 15919 * @param when the time at which the action must occur. Uses the 15920 * {@link SystemClock#uptimeMillis} timebase. 15921 */ 15922 @Override 15923 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15924 if (verifyDrawable(who) && what != null) { 15925 final long delay = when - SystemClock.uptimeMillis(); 15926 if (mAttachInfo != null) { 15927 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15928 Choreographer.CALLBACK_ANIMATION, what, who, 15929 Choreographer.subtractFrameDelay(delay)); 15930 } else { 15931 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15932 } 15933 } 15934 } 15935 15936 /** 15937 * Cancels a scheduled action on a drawable. 15938 * 15939 * @param who the recipient of the action 15940 * @param what the action to cancel 15941 */ 15942 @Override 15943 public void unscheduleDrawable(Drawable who, Runnable what) { 15944 if (verifyDrawable(who) && what != null) { 15945 if (mAttachInfo != null) { 15946 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15947 Choreographer.CALLBACK_ANIMATION, what, who); 15948 } 15949 ViewRootImpl.getRunQueue().removeCallbacks(what); 15950 } 15951 } 15952 15953 /** 15954 * Unschedule any events associated with the given Drawable. This can be 15955 * used when selecting a new Drawable into a view, so that the previous 15956 * one is completely unscheduled. 15957 * 15958 * @param who The Drawable to unschedule. 15959 * 15960 * @see #drawableStateChanged 15961 */ 15962 public void unscheduleDrawable(Drawable who) { 15963 if (mAttachInfo != null && who != null) { 15964 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15965 Choreographer.CALLBACK_ANIMATION, null, who); 15966 } 15967 } 15968 15969 /** 15970 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15971 * that the View directionality can and will be resolved before its Drawables. 15972 * 15973 * Will call {@link View#onResolveDrawables} when resolution is done. 15974 * 15975 * @hide 15976 */ 15977 protected void resolveDrawables() { 15978 // Drawables resolution may need to happen before resolving the layout direction (which is 15979 // done only during the measure() call). 15980 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15981 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15982 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15983 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15984 // direction to be resolved as its resolved value will be the same as its raw value. 15985 if (!isLayoutDirectionResolved() && 15986 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15987 return; 15988 } 15989 15990 final int layoutDirection = isLayoutDirectionResolved() ? 15991 getLayoutDirection() : getRawLayoutDirection(); 15992 15993 if (mBackground != null) { 15994 mBackground.setLayoutDirection(layoutDirection); 15995 } 15996 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15997 onResolveDrawables(layoutDirection); 15998 } 15999 16000 boolean areDrawablesResolved() { 16001 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 16002 } 16003 16004 /** 16005 * Called when layout direction has been resolved. 16006 * 16007 * The default implementation does nothing. 16008 * 16009 * @param layoutDirection The resolved layout direction. 16010 * 16011 * @see #LAYOUT_DIRECTION_LTR 16012 * @see #LAYOUT_DIRECTION_RTL 16013 * 16014 * @hide 16015 */ 16016 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16017 } 16018 16019 /** 16020 * @hide 16021 */ 16022 protected void resetResolvedDrawables() { 16023 resetResolvedDrawablesInternal(); 16024 } 16025 16026 void resetResolvedDrawablesInternal() { 16027 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16028 } 16029 16030 /** 16031 * If your view subclass is displaying its own Drawable objects, it should 16032 * override this function and return true for any Drawable it is 16033 * displaying. This allows animations for those drawables to be 16034 * scheduled. 16035 * 16036 * <p>Be sure to call through to the super class when overriding this 16037 * function. 16038 * 16039 * @param who The Drawable to verify. Return true if it is one you are 16040 * displaying, else return the result of calling through to the 16041 * super class. 16042 * 16043 * @return boolean If true than the Drawable is being displayed in the 16044 * view; else false and it is not allowed to animate. 16045 * 16046 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16047 * @see #drawableStateChanged() 16048 */ 16049 @CallSuper 16050 protected boolean verifyDrawable(Drawable who) { 16051 return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who); 16052 } 16053 16054 /** 16055 * This function is called whenever the state of the view changes in such 16056 * a way that it impacts the state of drawables being shown. 16057 * <p> 16058 * If the View has a StateListAnimator, it will also be called to run necessary state 16059 * change animations. 16060 * <p> 16061 * Be sure to call through to the superclass when overriding this function. 16062 * 16063 * @see Drawable#setState(int[]) 16064 */ 16065 @CallSuper 16066 protected void drawableStateChanged() { 16067 final int[] state = getDrawableState(); 16068 16069 final Drawable d = mBackground; 16070 if (d != null && d.isStateful()) { 16071 d.setState(state); 16072 } 16073 16074 if (mScrollCache != null) { 16075 final Drawable scrollBar = mScrollCache.scrollBar; 16076 if (scrollBar != null && scrollBar.isStateful()) { 16077 scrollBar.setState(state); 16078 } 16079 } 16080 16081 if (mStateListAnimator != null) { 16082 mStateListAnimator.setState(state); 16083 } 16084 } 16085 16086 /** 16087 * This function is called whenever the view hotspot changes and needs to 16088 * be propagated to drawables or child views managed by the view. 16089 * <p> 16090 * Dispatching to child views is handled by 16091 * {@link #dispatchDrawableHotspotChanged(float, float)}. 16092 * <p> 16093 * Be sure to call through to the superclass when overriding this function. 16094 * 16095 * @param x hotspot x coordinate 16096 * @param y hotspot y coordinate 16097 */ 16098 @CallSuper 16099 public void drawableHotspotChanged(float x, float y) { 16100 if (mBackground != null) { 16101 mBackground.setHotspot(x, y); 16102 } 16103 16104 dispatchDrawableHotspotChanged(x, y); 16105 } 16106 16107 /** 16108 * Dispatches drawableHotspotChanged to all of this View's children. 16109 * 16110 * @param x hotspot x coordinate 16111 * @param y hotspot y coordinate 16112 * @see #drawableHotspotChanged(float, float) 16113 */ 16114 public void dispatchDrawableHotspotChanged(float x, float y) { 16115 } 16116 16117 /** 16118 * Call this to force a view to update its drawable state. This will cause 16119 * drawableStateChanged to be called on this view. Views that are interested 16120 * in the new state should call getDrawableState. 16121 * 16122 * @see #drawableStateChanged 16123 * @see #getDrawableState 16124 */ 16125 public void refreshDrawableState() { 16126 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16127 drawableStateChanged(); 16128 16129 ViewParent parent = mParent; 16130 if (parent != null) { 16131 parent.childDrawableStateChanged(this); 16132 } 16133 } 16134 16135 /** 16136 * Return an array of resource IDs of the drawable states representing the 16137 * current state of the view. 16138 * 16139 * @return The current drawable state 16140 * 16141 * @see Drawable#setState(int[]) 16142 * @see #drawableStateChanged() 16143 * @see #onCreateDrawableState(int) 16144 */ 16145 public final int[] getDrawableState() { 16146 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16147 return mDrawableState; 16148 } else { 16149 mDrawableState = onCreateDrawableState(0); 16150 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16151 return mDrawableState; 16152 } 16153 } 16154 16155 /** 16156 * Generate the new {@link android.graphics.drawable.Drawable} state for 16157 * this view. This is called by the view 16158 * system when the cached Drawable state is determined to be invalid. To 16159 * retrieve the current state, you should use {@link #getDrawableState}. 16160 * 16161 * @param extraSpace if non-zero, this is the number of extra entries you 16162 * would like in the returned array in which you can place your own 16163 * states. 16164 * 16165 * @return Returns an array holding the current {@link Drawable} state of 16166 * the view. 16167 * 16168 * @see #mergeDrawableStates(int[], int[]) 16169 */ 16170 protected int[] onCreateDrawableState(int extraSpace) { 16171 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16172 mParent instanceof View) { 16173 return ((View) mParent).onCreateDrawableState(extraSpace); 16174 } 16175 16176 int[] drawableState; 16177 16178 int privateFlags = mPrivateFlags; 16179 16180 int viewStateIndex = 0; 16181 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 16182 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 16183 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 16184 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 16185 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 16186 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 16187 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 16188 HardwareRenderer.isAvailable()) { 16189 // This is set if HW acceleration is requested, even if the current 16190 // process doesn't allow it. This is just to allow app preview 16191 // windows to better match their app. 16192 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 16193 } 16194 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 16195 16196 final int privateFlags2 = mPrivateFlags2; 16197 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 16198 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 16199 } 16200 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 16201 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 16202 } 16203 16204 drawableState = StateSet.get(viewStateIndex); 16205 16206 //noinspection ConstantIfStatement 16207 if (false) { 16208 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16209 Log.i("View", toString() 16210 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16211 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16212 + " fo=" + hasFocus() 16213 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16214 + " wf=" + hasWindowFocus() 16215 + ": " + Arrays.toString(drawableState)); 16216 } 16217 16218 if (extraSpace == 0) { 16219 return drawableState; 16220 } 16221 16222 final int[] fullState; 16223 if (drawableState != null) { 16224 fullState = new int[drawableState.length + extraSpace]; 16225 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16226 } else { 16227 fullState = new int[extraSpace]; 16228 } 16229 16230 return fullState; 16231 } 16232 16233 /** 16234 * Merge your own state values in <var>additionalState</var> into the base 16235 * state values <var>baseState</var> that were returned by 16236 * {@link #onCreateDrawableState(int)}. 16237 * 16238 * @param baseState The base state values returned by 16239 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16240 * own additional state values. 16241 * 16242 * @param additionalState The additional state values you would like 16243 * added to <var>baseState</var>; this array is not modified. 16244 * 16245 * @return As a convenience, the <var>baseState</var> array you originally 16246 * passed into the function is returned. 16247 * 16248 * @see #onCreateDrawableState(int) 16249 */ 16250 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16251 final int N = baseState.length; 16252 int i = N - 1; 16253 while (i >= 0 && baseState[i] == 0) { 16254 i--; 16255 } 16256 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16257 return baseState; 16258 } 16259 16260 /** 16261 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16262 * on all Drawable objects associated with this view. 16263 * <p> 16264 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16265 * attached to this view. 16266 */ 16267 public void jumpDrawablesToCurrentState() { 16268 if (mBackground != null) { 16269 mBackground.jumpToCurrentState(); 16270 } 16271 if (mStateListAnimator != null) { 16272 mStateListAnimator.jumpToCurrentState(); 16273 } 16274 } 16275 16276 /** 16277 * Sets the background color for this view. 16278 * @param color the color of the background 16279 */ 16280 @RemotableViewMethod 16281 public void setBackgroundColor(@ColorInt int color) { 16282 if (mBackground instanceof ColorDrawable) { 16283 ((ColorDrawable) mBackground.mutate()).setColor(color); 16284 computeOpaqueFlags(); 16285 mBackgroundResource = 0; 16286 } else { 16287 setBackground(new ColorDrawable(color)); 16288 } 16289 } 16290 16291 /** 16292 * If the view has a ColorDrawable background, returns the color of that 16293 * drawable. 16294 * 16295 * @return The color of the ColorDrawable background, if set, otherwise 0. 16296 */ 16297 @ColorInt 16298 public int getBackgroundColor() { 16299 if (mBackground instanceof ColorDrawable) { 16300 return ((ColorDrawable) mBackground).getColor(); 16301 } 16302 return 0; 16303 } 16304 16305 /** 16306 * Set the background to a given resource. The resource should refer to 16307 * a Drawable object or 0 to remove the background. 16308 * @param resid The identifier of the resource. 16309 * 16310 * @attr ref android.R.styleable#View_background 16311 */ 16312 @RemotableViewMethod 16313 public void setBackgroundResource(@DrawableRes int resid) { 16314 if (resid != 0 && resid == mBackgroundResource) { 16315 return; 16316 } 16317 16318 Drawable d = null; 16319 if (resid != 0) { 16320 d = mContext.getDrawable(resid); 16321 } 16322 setBackground(d); 16323 16324 mBackgroundResource = resid; 16325 } 16326 16327 /** 16328 * Set the background to a given Drawable, or remove the background. If the 16329 * background has padding, this View's padding is set to the background's 16330 * padding. However, when a background is removed, this View's padding isn't 16331 * touched. If setting the padding is desired, please use 16332 * {@link #setPadding(int, int, int, int)}. 16333 * 16334 * @param background The Drawable to use as the background, or null to remove the 16335 * background 16336 */ 16337 public void setBackground(Drawable background) { 16338 //noinspection deprecation 16339 setBackgroundDrawable(background); 16340 } 16341 16342 /** 16343 * @deprecated use {@link #setBackground(Drawable)} instead 16344 */ 16345 @Deprecated 16346 public void setBackgroundDrawable(Drawable background) { 16347 computeOpaqueFlags(); 16348 16349 if (background == mBackground) { 16350 return; 16351 } 16352 16353 boolean requestLayout = false; 16354 16355 mBackgroundResource = 0; 16356 16357 /* 16358 * Regardless of whether we're setting a new background or not, we want 16359 * to clear the previous drawable. 16360 */ 16361 if (mBackground != null) { 16362 mBackground.setCallback(null); 16363 unscheduleDrawable(mBackground); 16364 } 16365 16366 if (background != null) { 16367 Rect padding = sThreadLocal.get(); 16368 if (padding == null) { 16369 padding = new Rect(); 16370 sThreadLocal.set(padding); 16371 } 16372 resetResolvedDrawablesInternal(); 16373 background.setLayoutDirection(getLayoutDirection()); 16374 if (background.getPadding(padding)) { 16375 resetResolvedPaddingInternal(); 16376 switch (background.getLayoutDirection()) { 16377 case LAYOUT_DIRECTION_RTL: 16378 mUserPaddingLeftInitial = padding.right; 16379 mUserPaddingRightInitial = padding.left; 16380 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16381 break; 16382 case LAYOUT_DIRECTION_LTR: 16383 default: 16384 mUserPaddingLeftInitial = padding.left; 16385 mUserPaddingRightInitial = padding.right; 16386 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16387 } 16388 mLeftPaddingDefined = false; 16389 mRightPaddingDefined = false; 16390 } 16391 16392 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16393 // if it has a different minimum size, we should layout again 16394 if (mBackground == null 16395 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16396 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16397 requestLayout = true; 16398 } 16399 16400 background.setCallback(this); 16401 if (background.isStateful()) { 16402 background.setState(getDrawableState()); 16403 } 16404 background.setVisible(getVisibility() == VISIBLE, false); 16405 mBackground = background; 16406 16407 applyBackgroundTint(); 16408 16409 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16410 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16411 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16412 requestLayout = true; 16413 } 16414 } else { 16415 /* Remove the background */ 16416 mBackground = null; 16417 16418 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16419 /* 16420 * This view ONLY drew the background before and we're removing 16421 * the background, so now it won't draw anything 16422 * (hence we SKIP_DRAW) 16423 */ 16424 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16425 mPrivateFlags |= PFLAG_SKIP_DRAW; 16426 } 16427 16428 /* 16429 * When the background is set, we try to apply its padding to this 16430 * View. When the background is removed, we don't touch this View's 16431 * padding. This is noted in the Javadocs. Hence, we don't need to 16432 * requestLayout(), the invalidate() below is sufficient. 16433 */ 16434 16435 // The old background's minimum size could have affected this 16436 // View's layout, so let's requestLayout 16437 requestLayout = true; 16438 } 16439 16440 computeOpaqueFlags(); 16441 16442 if (requestLayout) { 16443 requestLayout(); 16444 } 16445 16446 mBackgroundSizeChanged = true; 16447 invalidate(true); 16448 } 16449 16450 /** 16451 * Gets the background drawable 16452 * 16453 * @return The drawable used as the background for this view, if any. 16454 * 16455 * @see #setBackground(Drawable) 16456 * 16457 * @attr ref android.R.styleable#View_background 16458 */ 16459 public Drawable getBackground() { 16460 return mBackground; 16461 } 16462 16463 /** 16464 * Applies a tint to the background drawable. Does not modify the current tint 16465 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16466 * <p> 16467 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16468 * mutate the drawable and apply the specified tint and tint mode using 16469 * {@link Drawable#setTintList(ColorStateList)}. 16470 * 16471 * @param tint the tint to apply, may be {@code null} to clear tint 16472 * 16473 * @attr ref android.R.styleable#View_backgroundTint 16474 * @see #getBackgroundTintList() 16475 * @see Drawable#setTintList(ColorStateList) 16476 */ 16477 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16478 if (mBackgroundTint == null) { 16479 mBackgroundTint = new TintInfo(); 16480 } 16481 mBackgroundTint.mTintList = tint; 16482 mBackgroundTint.mHasTintList = true; 16483 16484 applyBackgroundTint(); 16485 } 16486 16487 /** 16488 * Return the tint applied to the background drawable, if specified. 16489 * 16490 * @return the tint applied to the background drawable 16491 * @attr ref android.R.styleable#View_backgroundTint 16492 * @see #setBackgroundTintList(ColorStateList) 16493 */ 16494 @Nullable 16495 public ColorStateList getBackgroundTintList() { 16496 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16497 } 16498 16499 /** 16500 * Specifies the blending mode used to apply the tint specified by 16501 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16502 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16503 * 16504 * @param tintMode the blending mode used to apply the tint, may be 16505 * {@code null} to clear tint 16506 * @attr ref android.R.styleable#View_backgroundTintMode 16507 * @see #getBackgroundTintMode() 16508 * @see Drawable#setTintMode(PorterDuff.Mode) 16509 */ 16510 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16511 if (mBackgroundTint == null) { 16512 mBackgroundTint = new TintInfo(); 16513 } 16514 mBackgroundTint.mTintMode = tintMode; 16515 mBackgroundTint.mHasTintMode = true; 16516 16517 applyBackgroundTint(); 16518 } 16519 16520 /** 16521 * Return the blending mode used to apply the tint to the background 16522 * drawable, if specified. 16523 * 16524 * @return the blending mode used to apply the tint to the background 16525 * drawable 16526 * @attr ref android.R.styleable#View_backgroundTintMode 16527 * @see #setBackgroundTintMode(PorterDuff.Mode) 16528 */ 16529 @Nullable 16530 public PorterDuff.Mode getBackgroundTintMode() { 16531 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16532 } 16533 16534 private void applyBackgroundTint() { 16535 if (mBackground != null && mBackgroundTint != null) { 16536 final TintInfo tintInfo = mBackgroundTint; 16537 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16538 mBackground = mBackground.mutate(); 16539 16540 if (tintInfo.mHasTintList) { 16541 mBackground.setTintList(tintInfo.mTintList); 16542 } 16543 16544 if (tintInfo.mHasTintMode) { 16545 mBackground.setTintMode(tintInfo.mTintMode); 16546 } 16547 16548 // The drawable (or one of its children) may not have been 16549 // stateful before applying the tint, so let's try again. 16550 if (mBackground.isStateful()) { 16551 mBackground.setState(getDrawableState()); 16552 } 16553 } 16554 } 16555 } 16556 16557 /** 16558 * Sets the padding. The view may add on the space required to display 16559 * the scrollbars, depending on the style and visibility of the scrollbars. 16560 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16561 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16562 * from the values set in this call. 16563 * 16564 * @attr ref android.R.styleable#View_padding 16565 * @attr ref android.R.styleable#View_paddingBottom 16566 * @attr ref android.R.styleable#View_paddingLeft 16567 * @attr ref android.R.styleable#View_paddingRight 16568 * @attr ref android.R.styleable#View_paddingTop 16569 * @param left the left padding in pixels 16570 * @param top the top padding in pixels 16571 * @param right the right padding in pixels 16572 * @param bottom the bottom padding in pixels 16573 */ 16574 public void setPadding(int left, int top, int right, int bottom) { 16575 resetResolvedPaddingInternal(); 16576 16577 mUserPaddingStart = UNDEFINED_PADDING; 16578 mUserPaddingEnd = UNDEFINED_PADDING; 16579 16580 mUserPaddingLeftInitial = left; 16581 mUserPaddingRightInitial = right; 16582 16583 mLeftPaddingDefined = true; 16584 mRightPaddingDefined = true; 16585 16586 internalSetPadding(left, top, right, bottom); 16587 } 16588 16589 /** 16590 * @hide 16591 */ 16592 protected void internalSetPadding(int left, int top, int right, int bottom) { 16593 mUserPaddingLeft = left; 16594 mUserPaddingRight = right; 16595 mUserPaddingBottom = bottom; 16596 16597 final int viewFlags = mViewFlags; 16598 boolean changed = false; 16599 16600 // Common case is there are no scroll bars. 16601 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16602 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16603 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16604 ? 0 : getVerticalScrollbarWidth(); 16605 switch (mVerticalScrollbarPosition) { 16606 case SCROLLBAR_POSITION_DEFAULT: 16607 if (isLayoutRtl()) { 16608 left += offset; 16609 } else { 16610 right += offset; 16611 } 16612 break; 16613 case SCROLLBAR_POSITION_RIGHT: 16614 right += offset; 16615 break; 16616 case SCROLLBAR_POSITION_LEFT: 16617 left += offset; 16618 break; 16619 } 16620 } 16621 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16622 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16623 ? 0 : getHorizontalScrollbarHeight(); 16624 } 16625 } 16626 16627 if (mPaddingLeft != left) { 16628 changed = true; 16629 mPaddingLeft = left; 16630 } 16631 if (mPaddingTop != top) { 16632 changed = true; 16633 mPaddingTop = top; 16634 } 16635 if (mPaddingRight != right) { 16636 changed = true; 16637 mPaddingRight = right; 16638 } 16639 if (mPaddingBottom != bottom) { 16640 changed = true; 16641 mPaddingBottom = bottom; 16642 } 16643 16644 if (changed) { 16645 requestLayout(); 16646 invalidateOutline(); 16647 } 16648 } 16649 16650 /** 16651 * Sets the relative padding. The view may add on the space required to display 16652 * the scrollbars, depending on the style and visibility of the scrollbars. 16653 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16654 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16655 * from the values set in this call. 16656 * 16657 * @attr ref android.R.styleable#View_padding 16658 * @attr ref android.R.styleable#View_paddingBottom 16659 * @attr ref android.R.styleable#View_paddingStart 16660 * @attr ref android.R.styleable#View_paddingEnd 16661 * @attr ref android.R.styleable#View_paddingTop 16662 * @param start the start padding in pixels 16663 * @param top the top padding in pixels 16664 * @param end the end padding in pixels 16665 * @param bottom the bottom padding in pixels 16666 */ 16667 public void setPaddingRelative(int start, int top, int end, int bottom) { 16668 resetResolvedPaddingInternal(); 16669 16670 mUserPaddingStart = start; 16671 mUserPaddingEnd = end; 16672 mLeftPaddingDefined = true; 16673 mRightPaddingDefined = true; 16674 16675 switch(getLayoutDirection()) { 16676 case LAYOUT_DIRECTION_RTL: 16677 mUserPaddingLeftInitial = end; 16678 mUserPaddingRightInitial = start; 16679 internalSetPadding(end, top, start, bottom); 16680 break; 16681 case LAYOUT_DIRECTION_LTR: 16682 default: 16683 mUserPaddingLeftInitial = start; 16684 mUserPaddingRightInitial = end; 16685 internalSetPadding(start, top, end, bottom); 16686 } 16687 } 16688 16689 /** 16690 * Returns the top padding of this view. 16691 * 16692 * @return the top padding in pixels 16693 */ 16694 public int getPaddingTop() { 16695 return mPaddingTop; 16696 } 16697 16698 /** 16699 * Returns the bottom padding of this view. If there are inset and enabled 16700 * scrollbars, this value may include the space required to display the 16701 * scrollbars as well. 16702 * 16703 * @return the bottom padding in pixels 16704 */ 16705 public int getPaddingBottom() { 16706 return mPaddingBottom; 16707 } 16708 16709 /** 16710 * Returns the left padding of this view. If there are inset and enabled 16711 * scrollbars, this value may include the space required to display the 16712 * scrollbars as well. 16713 * 16714 * @return the left padding in pixels 16715 */ 16716 public int getPaddingLeft() { 16717 if (!isPaddingResolved()) { 16718 resolvePadding(); 16719 } 16720 return mPaddingLeft; 16721 } 16722 16723 /** 16724 * Returns the start padding of this view depending on its resolved layout direction. 16725 * If there are inset and enabled scrollbars, this value may include the space 16726 * required to display the scrollbars as well. 16727 * 16728 * @return the start padding in pixels 16729 */ 16730 public int getPaddingStart() { 16731 if (!isPaddingResolved()) { 16732 resolvePadding(); 16733 } 16734 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16735 mPaddingRight : mPaddingLeft; 16736 } 16737 16738 /** 16739 * Returns the right padding of this view. If there are inset and enabled 16740 * scrollbars, this value may include the space required to display the 16741 * scrollbars as well. 16742 * 16743 * @return the right padding in pixels 16744 */ 16745 public int getPaddingRight() { 16746 if (!isPaddingResolved()) { 16747 resolvePadding(); 16748 } 16749 return mPaddingRight; 16750 } 16751 16752 /** 16753 * Returns the end padding of this view depending on its resolved layout direction. 16754 * If there are inset and enabled scrollbars, this value may include the space 16755 * required to display the scrollbars as well. 16756 * 16757 * @return the end padding in pixels 16758 */ 16759 public int getPaddingEnd() { 16760 if (!isPaddingResolved()) { 16761 resolvePadding(); 16762 } 16763 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16764 mPaddingLeft : mPaddingRight; 16765 } 16766 16767 /** 16768 * Return if the padding has been set through relative values 16769 * {@link #setPaddingRelative(int, int, int, int)} or through 16770 * @attr ref android.R.styleable#View_paddingStart or 16771 * @attr ref android.R.styleable#View_paddingEnd 16772 * 16773 * @return true if the padding is relative or false if it is not. 16774 */ 16775 public boolean isPaddingRelative() { 16776 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16777 } 16778 16779 Insets computeOpticalInsets() { 16780 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16781 } 16782 16783 /** 16784 * @hide 16785 */ 16786 public void resetPaddingToInitialValues() { 16787 if (isRtlCompatibilityMode()) { 16788 mPaddingLeft = mUserPaddingLeftInitial; 16789 mPaddingRight = mUserPaddingRightInitial; 16790 return; 16791 } 16792 if (isLayoutRtl()) { 16793 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16794 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16795 } else { 16796 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16797 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16798 } 16799 } 16800 16801 /** 16802 * @hide 16803 */ 16804 public Insets getOpticalInsets() { 16805 if (mLayoutInsets == null) { 16806 mLayoutInsets = computeOpticalInsets(); 16807 } 16808 return mLayoutInsets; 16809 } 16810 16811 /** 16812 * Set this view's optical insets. 16813 * 16814 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16815 * property. Views that compute their own optical insets should call it as part of measurement. 16816 * This method does not request layout. If you are setting optical insets outside of 16817 * measure/layout itself you will want to call requestLayout() yourself. 16818 * </p> 16819 * @hide 16820 */ 16821 public void setOpticalInsets(Insets insets) { 16822 mLayoutInsets = insets; 16823 } 16824 16825 /** 16826 * Changes the selection state of this view. A view can be selected or not. 16827 * Note that selection is not the same as focus. Views are typically 16828 * selected in the context of an AdapterView like ListView or GridView; 16829 * the selected view is the view that is highlighted. 16830 * 16831 * @param selected true if the view must be selected, false otherwise 16832 */ 16833 public void setSelected(boolean selected) { 16834 //noinspection DoubleNegation 16835 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16836 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16837 if (!selected) resetPressedState(); 16838 invalidate(true); 16839 refreshDrawableState(); 16840 dispatchSetSelected(selected); 16841 if (selected) { 16842 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 16843 } else { 16844 notifyViewAccessibilityStateChangedIfNeeded( 16845 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16846 } 16847 } 16848 } 16849 16850 /** 16851 * Dispatch setSelected to all of this View's children. 16852 * 16853 * @see #setSelected(boolean) 16854 * 16855 * @param selected The new selected state 16856 */ 16857 protected void dispatchSetSelected(boolean selected) { 16858 } 16859 16860 /** 16861 * Indicates the selection state of this view. 16862 * 16863 * @return true if the view is selected, false otherwise 16864 */ 16865 @ViewDebug.ExportedProperty 16866 public boolean isSelected() { 16867 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16868 } 16869 16870 /** 16871 * Changes the activated state of this view. A view can be activated or not. 16872 * Note that activation is not the same as selection. Selection is 16873 * a transient property, representing the view (hierarchy) the user is 16874 * currently interacting with. Activation is a longer-term state that the 16875 * user can move views in and out of. For example, in a list view with 16876 * single or multiple selection enabled, the views in the current selection 16877 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16878 * here.) The activated state is propagated down to children of the view it 16879 * is set on. 16880 * 16881 * @param activated true if the view must be activated, false otherwise 16882 */ 16883 public void setActivated(boolean activated) { 16884 //noinspection DoubleNegation 16885 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16886 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16887 invalidate(true); 16888 refreshDrawableState(); 16889 dispatchSetActivated(activated); 16890 } 16891 } 16892 16893 /** 16894 * Dispatch setActivated to all of this View's children. 16895 * 16896 * @see #setActivated(boolean) 16897 * 16898 * @param activated The new activated state 16899 */ 16900 protected void dispatchSetActivated(boolean activated) { 16901 } 16902 16903 /** 16904 * Indicates the activation state of this view. 16905 * 16906 * @return true if the view is activated, false otherwise 16907 */ 16908 @ViewDebug.ExportedProperty 16909 public boolean isActivated() { 16910 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16911 } 16912 16913 /** 16914 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16915 * observer can be used to get notifications when global events, like 16916 * layout, happen. 16917 * 16918 * The returned ViewTreeObserver observer is not guaranteed to remain 16919 * valid for the lifetime of this View. If the caller of this method keeps 16920 * a long-lived reference to ViewTreeObserver, it should always check for 16921 * the return value of {@link ViewTreeObserver#isAlive()}. 16922 * 16923 * @return The ViewTreeObserver for this view's hierarchy. 16924 */ 16925 public ViewTreeObserver getViewTreeObserver() { 16926 if (mAttachInfo != null) { 16927 return mAttachInfo.mTreeObserver; 16928 } 16929 if (mFloatingTreeObserver == null) { 16930 mFloatingTreeObserver = new ViewTreeObserver(); 16931 } 16932 return mFloatingTreeObserver; 16933 } 16934 16935 /** 16936 * <p>Finds the topmost view in the current view hierarchy.</p> 16937 * 16938 * @return the topmost view containing this view 16939 */ 16940 public View getRootView() { 16941 if (mAttachInfo != null) { 16942 final View v = mAttachInfo.mRootView; 16943 if (v != null) { 16944 return v; 16945 } 16946 } 16947 16948 View parent = this; 16949 16950 while (parent.mParent != null && parent.mParent instanceof View) { 16951 parent = (View) parent.mParent; 16952 } 16953 16954 return parent; 16955 } 16956 16957 /** 16958 * Transforms a motion event from view-local coordinates to on-screen 16959 * coordinates. 16960 * 16961 * @param ev the view-local motion event 16962 * @return false if the transformation could not be applied 16963 * @hide 16964 */ 16965 public boolean toGlobalMotionEvent(MotionEvent ev) { 16966 final AttachInfo info = mAttachInfo; 16967 if (info == null) { 16968 return false; 16969 } 16970 16971 final Matrix m = info.mTmpMatrix; 16972 m.set(Matrix.IDENTITY_MATRIX); 16973 transformMatrixToGlobal(m); 16974 ev.transform(m); 16975 return true; 16976 } 16977 16978 /** 16979 * Transforms a motion event from on-screen coordinates to view-local 16980 * coordinates. 16981 * 16982 * @param ev the on-screen motion event 16983 * @return false if the transformation could not be applied 16984 * @hide 16985 */ 16986 public boolean toLocalMotionEvent(MotionEvent ev) { 16987 final AttachInfo info = mAttachInfo; 16988 if (info == null) { 16989 return false; 16990 } 16991 16992 final Matrix m = info.mTmpMatrix; 16993 m.set(Matrix.IDENTITY_MATRIX); 16994 transformMatrixToLocal(m); 16995 ev.transform(m); 16996 return true; 16997 } 16998 16999 /** 17000 * Modifies the input matrix such that it maps view-local coordinates to 17001 * on-screen coordinates. 17002 * 17003 * @param m input matrix to modify 17004 * @hide 17005 */ 17006 public void transformMatrixToGlobal(Matrix m) { 17007 final ViewParent parent = mParent; 17008 if (parent instanceof View) { 17009 final View vp = (View) parent; 17010 vp.transformMatrixToGlobal(m); 17011 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 17012 } else if (parent instanceof ViewRootImpl) { 17013 final ViewRootImpl vr = (ViewRootImpl) parent; 17014 vr.transformMatrixToGlobal(m); 17015 m.preTranslate(0, -vr.mCurScrollY); 17016 } 17017 17018 m.preTranslate(mLeft, mTop); 17019 17020 if (!hasIdentityMatrix()) { 17021 m.preConcat(getMatrix()); 17022 } 17023 } 17024 17025 /** 17026 * Modifies the input matrix such that it maps on-screen coordinates to 17027 * view-local coordinates. 17028 * 17029 * @param m input matrix to modify 17030 * @hide 17031 */ 17032 public void transformMatrixToLocal(Matrix m) { 17033 final ViewParent parent = mParent; 17034 if (parent instanceof View) { 17035 final View vp = (View) parent; 17036 vp.transformMatrixToLocal(m); 17037 m.postTranslate(vp.mScrollX, vp.mScrollY); 17038 } else if (parent instanceof ViewRootImpl) { 17039 final ViewRootImpl vr = (ViewRootImpl) parent; 17040 vr.transformMatrixToLocal(m); 17041 m.postTranslate(0, vr.mCurScrollY); 17042 } 17043 17044 m.postTranslate(-mLeft, -mTop); 17045 17046 if (!hasIdentityMatrix()) { 17047 m.postConcat(getInverseMatrix()); 17048 } 17049 } 17050 17051 /** 17052 * @hide 17053 */ 17054 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 17055 @ViewDebug.IntToString(from = 0, to = "x"), 17056 @ViewDebug.IntToString(from = 1, to = "y") 17057 }) 17058 public int[] getLocationOnScreen() { 17059 int[] location = new int[2]; 17060 getLocationOnScreen(location); 17061 return location; 17062 } 17063 17064 /** 17065 * <p>Computes the coordinates of this view on the screen. The argument 17066 * must be an array of two integers. After the method returns, the array 17067 * contains the x and y location in that order.</p> 17068 * 17069 * @param location an array of two integers in which to hold the coordinates 17070 */ 17071 public void getLocationOnScreen(@Size(2) int[] location) { 17072 getLocationInWindow(location); 17073 17074 final AttachInfo info = mAttachInfo; 17075 if (info != null) { 17076 location[0] += info.mWindowLeft; 17077 location[1] += info.mWindowTop; 17078 } 17079 } 17080 17081 /** 17082 * <p>Computes the coordinates of this view in its window. The argument 17083 * must be an array of two integers. After the method returns, the array 17084 * contains the x and y location in that order.</p> 17085 * 17086 * @param location an array of two integers in which to hold the coordinates 17087 */ 17088 public void getLocationInWindow(@Size(2) int[] location) { 17089 if (location == null || location.length < 2) { 17090 throw new IllegalArgumentException("location must be an array of two integers"); 17091 } 17092 17093 if (mAttachInfo == null) { 17094 // When the view is not attached to a window, this method does not make sense 17095 location[0] = location[1] = 0; 17096 return; 17097 } 17098 17099 float[] position = mAttachInfo.mTmpTransformLocation; 17100 position[0] = position[1] = 0.0f; 17101 17102 if (!hasIdentityMatrix()) { 17103 getMatrix().mapPoints(position); 17104 } 17105 17106 position[0] += mLeft; 17107 position[1] += mTop; 17108 17109 ViewParent viewParent = mParent; 17110 while (viewParent instanceof View) { 17111 final View view = (View) viewParent; 17112 17113 position[0] -= view.mScrollX; 17114 position[1] -= view.mScrollY; 17115 17116 if (!view.hasIdentityMatrix()) { 17117 view.getMatrix().mapPoints(position); 17118 } 17119 17120 position[0] += view.mLeft; 17121 position[1] += view.mTop; 17122 17123 viewParent = view.mParent; 17124 } 17125 17126 if (viewParent instanceof ViewRootImpl) { 17127 // *cough* 17128 final ViewRootImpl vr = (ViewRootImpl) viewParent; 17129 position[1] -= vr.mCurScrollY; 17130 } 17131 17132 location[0] = (int) (position[0] + 0.5f); 17133 location[1] = (int) (position[1] + 0.5f); 17134 } 17135 17136 /** 17137 * {@hide} 17138 * @param id the id of the view to be found 17139 * @return the view of the specified id, null if cannot be found 17140 */ 17141 protected View findViewTraversal(@IdRes int id) { 17142 if (id == mID) { 17143 return this; 17144 } 17145 return null; 17146 } 17147 17148 /** 17149 * {@hide} 17150 * @param tag the tag of the view to be found 17151 * @return the view of specified tag, null if cannot be found 17152 */ 17153 protected View findViewWithTagTraversal(Object tag) { 17154 if (tag != null && tag.equals(mTag)) { 17155 return this; 17156 } 17157 return null; 17158 } 17159 17160 /** 17161 * {@hide} 17162 * @param predicate The predicate to evaluate. 17163 * @param childToSkip If not null, ignores this child during the recursive traversal. 17164 * @return The first view that matches the predicate or null. 17165 */ 17166 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 17167 if (predicate.apply(this)) { 17168 return this; 17169 } 17170 return null; 17171 } 17172 17173 /** 17174 * Look for a child view with the given id. If this view has the given 17175 * id, return this view. 17176 * 17177 * @param id The id to search for. 17178 * @return The view that has the given id in the hierarchy or null 17179 */ 17180 @Nullable 17181 public final View findViewById(@IdRes int id) { 17182 if (id < 0) { 17183 return null; 17184 } 17185 return findViewTraversal(id); 17186 } 17187 17188 /** 17189 * Finds a view by its unuque and stable accessibility id. 17190 * 17191 * @param accessibilityId The searched accessibility id. 17192 * @return The found view. 17193 */ 17194 final View findViewByAccessibilityId(int accessibilityId) { 17195 if (accessibilityId < 0) { 17196 return null; 17197 } 17198 return findViewByAccessibilityIdTraversal(accessibilityId); 17199 } 17200 17201 /** 17202 * Performs the traversal to find a view by its unuque and stable accessibility id. 17203 * 17204 * <strong>Note:</strong>This method does not stop at the root namespace 17205 * boundary since the user can touch the screen at an arbitrary location 17206 * potentially crossing the root namespace bounday which will send an 17207 * accessibility event to accessibility services and they should be able 17208 * to obtain the event source. Also accessibility ids are guaranteed to be 17209 * unique in the window. 17210 * 17211 * @param accessibilityId The accessibility id. 17212 * @return The found view. 17213 * 17214 * @hide 17215 */ 17216 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 17217 if (getAccessibilityViewId() == accessibilityId) { 17218 return this; 17219 } 17220 return null; 17221 } 17222 17223 /** 17224 * Look for a child view with the given tag. If this view has the given 17225 * tag, return this view. 17226 * 17227 * @param tag The tag to search for, using "tag.equals(getTag())". 17228 * @return The View that has the given tag in the hierarchy or null 17229 */ 17230 public final View findViewWithTag(Object tag) { 17231 if (tag == null) { 17232 return null; 17233 } 17234 return findViewWithTagTraversal(tag); 17235 } 17236 17237 /** 17238 * {@hide} 17239 * Look for a child view that matches the specified predicate. 17240 * If this view matches the predicate, return this view. 17241 * 17242 * @param predicate The predicate to evaluate. 17243 * @return The first view that matches the predicate or null. 17244 */ 17245 public final View findViewByPredicate(Predicate<View> predicate) { 17246 return findViewByPredicateTraversal(predicate, null); 17247 } 17248 17249 /** 17250 * {@hide} 17251 * Look for a child view that matches the specified predicate, 17252 * starting with the specified view and its descendents and then 17253 * recusively searching the ancestors and siblings of that view 17254 * until this view is reached. 17255 * 17256 * This method is useful in cases where the predicate does not match 17257 * a single unique view (perhaps multiple views use the same id) 17258 * and we are trying to find the view that is "closest" in scope to the 17259 * starting view. 17260 * 17261 * @param start The view to start from. 17262 * @param predicate The predicate to evaluate. 17263 * @return The first view that matches the predicate or null. 17264 */ 17265 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17266 View childToSkip = null; 17267 for (;;) { 17268 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17269 if (view != null || start == this) { 17270 return view; 17271 } 17272 17273 ViewParent parent = start.getParent(); 17274 if (parent == null || !(parent instanceof View)) { 17275 return null; 17276 } 17277 17278 childToSkip = start; 17279 start = (View) parent; 17280 } 17281 } 17282 17283 /** 17284 * Sets the identifier for this view. The identifier does not have to be 17285 * unique in this view's hierarchy. The identifier should be a positive 17286 * number. 17287 * 17288 * @see #NO_ID 17289 * @see #getId() 17290 * @see #findViewById(int) 17291 * 17292 * @param id a number used to identify the view 17293 * 17294 * @attr ref android.R.styleable#View_id 17295 */ 17296 public void setId(@IdRes int id) { 17297 mID = id; 17298 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17299 mID = generateViewId(); 17300 } 17301 } 17302 17303 /** 17304 * {@hide} 17305 * 17306 * @param isRoot true if the view belongs to the root namespace, false 17307 * otherwise 17308 */ 17309 public void setIsRootNamespace(boolean isRoot) { 17310 if (isRoot) { 17311 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17312 } else { 17313 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17314 } 17315 } 17316 17317 /** 17318 * {@hide} 17319 * 17320 * @return true if the view belongs to the root namespace, false otherwise 17321 */ 17322 public boolean isRootNamespace() { 17323 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17324 } 17325 17326 /** 17327 * Returns this view's identifier. 17328 * 17329 * @return a positive integer used to identify the view or {@link #NO_ID} 17330 * if the view has no ID 17331 * 17332 * @see #setId(int) 17333 * @see #findViewById(int) 17334 * @attr ref android.R.styleable#View_id 17335 */ 17336 @IdRes 17337 @ViewDebug.CapturedViewProperty 17338 public int getId() { 17339 return mID; 17340 } 17341 17342 /** 17343 * Returns this view's tag. 17344 * 17345 * @return the Object stored in this view as a tag, or {@code null} if not 17346 * set 17347 * 17348 * @see #setTag(Object) 17349 * @see #getTag(int) 17350 */ 17351 @ViewDebug.ExportedProperty 17352 public Object getTag() { 17353 return mTag; 17354 } 17355 17356 /** 17357 * Sets the tag associated with this view. A tag can be used to mark 17358 * a view in its hierarchy and does not have to be unique within the 17359 * hierarchy. Tags can also be used to store data within a view without 17360 * resorting to another data structure. 17361 * 17362 * @param tag an Object to tag the view with 17363 * 17364 * @see #getTag() 17365 * @see #setTag(int, Object) 17366 */ 17367 public void setTag(final Object tag) { 17368 mTag = tag; 17369 } 17370 17371 /** 17372 * Returns the tag associated with this view and the specified key. 17373 * 17374 * @param key The key identifying the tag 17375 * 17376 * @return the Object stored in this view as a tag, or {@code null} if not 17377 * set 17378 * 17379 * @see #setTag(int, Object) 17380 * @see #getTag() 17381 */ 17382 public Object getTag(int key) { 17383 if (mKeyedTags != null) return mKeyedTags.get(key); 17384 return null; 17385 } 17386 17387 /** 17388 * Sets a tag associated with this view and a key. A tag can be used 17389 * to mark a view in its hierarchy and does not have to be unique within 17390 * the hierarchy. Tags can also be used to store data within a view 17391 * without resorting to another data structure. 17392 * 17393 * The specified key should be an id declared in the resources of the 17394 * application to ensure it is unique (see the <a 17395 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17396 * Keys identified as belonging to 17397 * the Android framework or not associated with any package will cause 17398 * an {@link IllegalArgumentException} to be thrown. 17399 * 17400 * @param key The key identifying the tag 17401 * @param tag An Object to tag the view with 17402 * 17403 * @throws IllegalArgumentException If they specified key is not valid 17404 * 17405 * @see #setTag(Object) 17406 * @see #getTag(int) 17407 */ 17408 public void setTag(int key, final Object tag) { 17409 // If the package id is 0x00 or 0x01, it's either an undefined package 17410 // or a framework id 17411 if ((key >>> 24) < 2) { 17412 throw new IllegalArgumentException("The key must be an application-specific " 17413 + "resource id."); 17414 } 17415 17416 setKeyedTag(key, tag); 17417 } 17418 17419 /** 17420 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17421 * framework id. 17422 * 17423 * @hide 17424 */ 17425 public void setTagInternal(int key, Object tag) { 17426 if ((key >>> 24) != 0x1) { 17427 throw new IllegalArgumentException("The key must be a framework-specific " 17428 + "resource id."); 17429 } 17430 17431 setKeyedTag(key, tag); 17432 } 17433 17434 private void setKeyedTag(int key, Object tag) { 17435 if (mKeyedTags == null) { 17436 mKeyedTags = new SparseArray<Object>(2); 17437 } 17438 17439 mKeyedTags.put(key, tag); 17440 } 17441 17442 /** 17443 * Prints information about this view in the log output, with the tag 17444 * {@link #VIEW_LOG_TAG}. 17445 * 17446 * @hide 17447 */ 17448 public void debug() { 17449 debug(0); 17450 } 17451 17452 /** 17453 * Prints information about this view in the log output, with the tag 17454 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17455 * indentation defined by the <code>depth</code>. 17456 * 17457 * @param depth the indentation level 17458 * 17459 * @hide 17460 */ 17461 protected void debug(int depth) { 17462 String output = debugIndent(depth - 1); 17463 17464 output += "+ " + this; 17465 int id = getId(); 17466 if (id != -1) { 17467 output += " (id=" + id + ")"; 17468 } 17469 Object tag = getTag(); 17470 if (tag != null) { 17471 output += " (tag=" + tag + ")"; 17472 } 17473 Log.d(VIEW_LOG_TAG, output); 17474 17475 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17476 output = debugIndent(depth) + " FOCUSED"; 17477 Log.d(VIEW_LOG_TAG, output); 17478 } 17479 17480 output = debugIndent(depth); 17481 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17482 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17483 + "} "; 17484 Log.d(VIEW_LOG_TAG, output); 17485 17486 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17487 || mPaddingBottom != 0) { 17488 output = debugIndent(depth); 17489 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17490 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17491 Log.d(VIEW_LOG_TAG, output); 17492 } 17493 17494 output = debugIndent(depth); 17495 output += "mMeasureWidth=" + mMeasuredWidth + 17496 " mMeasureHeight=" + mMeasuredHeight; 17497 Log.d(VIEW_LOG_TAG, output); 17498 17499 output = debugIndent(depth); 17500 if (mLayoutParams == null) { 17501 output += "BAD! no layout params"; 17502 } else { 17503 output = mLayoutParams.debug(output); 17504 } 17505 Log.d(VIEW_LOG_TAG, output); 17506 17507 output = debugIndent(depth); 17508 output += "flags={"; 17509 output += View.printFlags(mViewFlags); 17510 output += "}"; 17511 Log.d(VIEW_LOG_TAG, output); 17512 17513 output = debugIndent(depth); 17514 output += "privateFlags={"; 17515 output += View.printPrivateFlags(mPrivateFlags); 17516 output += "}"; 17517 Log.d(VIEW_LOG_TAG, output); 17518 } 17519 17520 /** 17521 * Creates a string of whitespaces used for indentation. 17522 * 17523 * @param depth the indentation level 17524 * @return a String containing (depth * 2 + 3) * 2 white spaces 17525 * 17526 * @hide 17527 */ 17528 protected static String debugIndent(int depth) { 17529 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17530 for (int i = 0; i < (depth * 2) + 3; i++) { 17531 spaces.append(' ').append(' '); 17532 } 17533 return spaces.toString(); 17534 } 17535 17536 /** 17537 * <p>Return the offset of the widget's text baseline from the widget's top 17538 * boundary. If this widget does not support baseline alignment, this 17539 * method returns -1. </p> 17540 * 17541 * @return the offset of the baseline within the widget's bounds or -1 17542 * if baseline alignment is not supported 17543 */ 17544 @ViewDebug.ExportedProperty(category = "layout") 17545 public int getBaseline() { 17546 return -1; 17547 } 17548 17549 /** 17550 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17551 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17552 * a layout pass. 17553 * 17554 * @return whether the view hierarchy is currently undergoing a layout pass 17555 */ 17556 public boolean isInLayout() { 17557 ViewRootImpl viewRoot = getViewRootImpl(); 17558 return (viewRoot != null && viewRoot.isInLayout()); 17559 } 17560 17561 /** 17562 * Call this when something has changed which has invalidated the 17563 * layout of this view. This will schedule a layout pass of the view 17564 * tree. This should not be called while the view hierarchy is currently in a layout 17565 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17566 * end of the current layout pass (and then layout will run again) or after the current 17567 * frame is drawn and the next layout occurs. 17568 * 17569 * <p>Subclasses which override this method should call the superclass method to 17570 * handle possible request-during-layout errors correctly.</p> 17571 */ 17572 @CallSuper 17573 public void requestLayout() { 17574 if (mMeasureCache != null) mMeasureCache.clear(); 17575 17576 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17577 // Only trigger request-during-layout logic if this is the view requesting it, 17578 // not the views in its parent hierarchy 17579 ViewRootImpl viewRoot = getViewRootImpl(); 17580 if (viewRoot != null && viewRoot.isInLayout()) { 17581 if (!viewRoot.requestLayoutDuringLayout(this)) { 17582 return; 17583 } 17584 } 17585 mAttachInfo.mViewRequestingLayout = this; 17586 } 17587 17588 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17589 mPrivateFlags |= PFLAG_INVALIDATED; 17590 17591 if (mParent != null && !mParent.isLayoutRequested()) { 17592 mParent.requestLayout(); 17593 } 17594 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17595 mAttachInfo.mViewRequestingLayout = null; 17596 } 17597 } 17598 17599 /** 17600 * Forces this view to be laid out during the next layout pass. 17601 * This method does not call requestLayout() or forceLayout() 17602 * on the parent. 17603 */ 17604 public void forceLayout() { 17605 if (mMeasureCache != null) mMeasureCache.clear(); 17606 17607 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17608 mPrivateFlags |= PFLAG_INVALIDATED; 17609 } 17610 17611 /** 17612 * <p> 17613 * This is called to find out how big a view should be. The parent 17614 * supplies constraint information in the width and height parameters. 17615 * </p> 17616 * 17617 * <p> 17618 * The actual measurement work of a view is performed in 17619 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17620 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17621 * </p> 17622 * 17623 * 17624 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17625 * parent 17626 * @param heightMeasureSpec Vertical space requirements as imposed by the 17627 * parent 17628 * 17629 * @see #onMeasure(int, int) 17630 */ 17631 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17632 boolean optical = isLayoutModeOptical(this); 17633 if (optical != isLayoutModeOptical(mParent)) { 17634 Insets insets = getOpticalInsets(); 17635 int oWidth = insets.left + insets.right; 17636 int oHeight = insets.top + insets.bottom; 17637 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17638 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17639 } 17640 17641 // Suppress sign extension for the low bytes 17642 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17643 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17644 17645 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17646 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 17647 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 17648 final boolean matchingSize = isExactly && 17649 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 17650 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 17651 if (forceLayout || !matchingSize && 17652 (widthMeasureSpec != mOldWidthMeasureSpec || 17653 heightMeasureSpec != mOldHeightMeasureSpec)) { 17654 17655 // first clears the measured dimension flag 17656 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17657 17658 resolveRtlPropertiesIfNeeded(); 17659 17660 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 17661 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17662 // measure ourselves, this should set the measured dimension flag back 17663 onMeasure(widthMeasureSpec, heightMeasureSpec); 17664 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17665 } else { 17666 long value = mMeasureCache.valueAt(cacheIndex); 17667 // Casting a long to int drops the high 32 bits, no mask needed 17668 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17669 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17670 } 17671 17672 // flag not set, setMeasuredDimension() was not invoked, we raise 17673 // an exception to warn the developer 17674 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17675 throw new IllegalStateException("onMeasure() did not set the" 17676 + " measured dimension by calling" 17677 + " setMeasuredDimension()"); 17678 } 17679 17680 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17681 } 17682 17683 mOldWidthMeasureSpec = widthMeasureSpec; 17684 mOldHeightMeasureSpec = heightMeasureSpec; 17685 17686 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17687 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17688 } 17689 17690 /** 17691 * <p> 17692 * Measure the view and its content to determine the measured width and the 17693 * measured height. This method is invoked by {@link #measure(int, int)} and 17694 * should be overridden by subclasses to provide accurate and efficient 17695 * measurement of their contents. 17696 * </p> 17697 * 17698 * <p> 17699 * <strong>CONTRACT:</strong> When overriding this method, you 17700 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17701 * measured width and height of this view. Failure to do so will trigger an 17702 * <code>IllegalStateException</code>, thrown by 17703 * {@link #measure(int, int)}. Calling the superclass' 17704 * {@link #onMeasure(int, int)} is a valid use. 17705 * </p> 17706 * 17707 * <p> 17708 * The base class implementation of measure defaults to the background size, 17709 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17710 * override {@link #onMeasure(int, int)} to provide better measurements of 17711 * their content. 17712 * </p> 17713 * 17714 * <p> 17715 * If this method is overridden, it is the subclass's responsibility to make 17716 * sure the measured height and width are at least the view's minimum height 17717 * and width ({@link #getSuggestedMinimumHeight()} and 17718 * {@link #getSuggestedMinimumWidth()}). 17719 * </p> 17720 * 17721 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17722 * The requirements are encoded with 17723 * {@link android.view.View.MeasureSpec}. 17724 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17725 * The requirements are encoded with 17726 * {@link android.view.View.MeasureSpec}. 17727 * 17728 * @see #getMeasuredWidth() 17729 * @see #getMeasuredHeight() 17730 * @see #setMeasuredDimension(int, int) 17731 * @see #getSuggestedMinimumHeight() 17732 * @see #getSuggestedMinimumWidth() 17733 * @see android.view.View.MeasureSpec#getMode(int) 17734 * @see android.view.View.MeasureSpec#getSize(int) 17735 */ 17736 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17737 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17738 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17739 } 17740 17741 /** 17742 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17743 * measured width and measured height. Failing to do so will trigger an 17744 * exception at measurement time.</p> 17745 * 17746 * @param measuredWidth The measured width of this view. May be a complex 17747 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17748 * {@link #MEASURED_STATE_TOO_SMALL}. 17749 * @param measuredHeight The measured height of this view. May be a complex 17750 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17751 * {@link #MEASURED_STATE_TOO_SMALL}. 17752 */ 17753 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17754 boolean optical = isLayoutModeOptical(this); 17755 if (optical != isLayoutModeOptical(mParent)) { 17756 Insets insets = getOpticalInsets(); 17757 int opticalWidth = insets.left + insets.right; 17758 int opticalHeight = insets.top + insets.bottom; 17759 17760 measuredWidth += optical ? opticalWidth : -opticalWidth; 17761 measuredHeight += optical ? opticalHeight : -opticalHeight; 17762 } 17763 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17764 } 17765 17766 /** 17767 * Sets the measured dimension without extra processing for things like optical bounds. 17768 * Useful for reapplying consistent values that have already been cooked with adjustments 17769 * for optical bounds, etc. such as those from the measurement cache. 17770 * 17771 * @param measuredWidth The measured width of this view. May be a complex 17772 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17773 * {@link #MEASURED_STATE_TOO_SMALL}. 17774 * @param measuredHeight The measured height of this view. May be a complex 17775 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17776 * {@link #MEASURED_STATE_TOO_SMALL}. 17777 */ 17778 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17779 mMeasuredWidth = measuredWidth; 17780 mMeasuredHeight = measuredHeight; 17781 17782 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17783 } 17784 17785 /** 17786 * Merge two states as returned by {@link #getMeasuredState()}. 17787 * @param curState The current state as returned from a view or the result 17788 * of combining multiple views. 17789 * @param newState The new view state to combine. 17790 * @return Returns a new integer reflecting the combination of the two 17791 * states. 17792 */ 17793 public static int combineMeasuredStates(int curState, int newState) { 17794 return curState | newState; 17795 } 17796 17797 /** 17798 * Version of {@link #resolveSizeAndState(int, int, int)} 17799 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17800 */ 17801 public static int resolveSize(int size, int measureSpec) { 17802 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17803 } 17804 17805 /** 17806 * Utility to reconcile a desired size and state, with constraints imposed 17807 * by a MeasureSpec. Will take the desired size, unless a different size 17808 * is imposed by the constraints. The returned value is a compound integer, 17809 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17810 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 17811 * resulting size is smaller than the size the view wants to be. 17812 * 17813 * @param size How big the view wants to be. 17814 * @param measureSpec Constraints imposed by the parent. 17815 * @param childMeasuredState Size information bit mask for the view's 17816 * children. 17817 * @return Size information bit mask as defined by 17818 * {@link #MEASURED_SIZE_MASK} and 17819 * {@link #MEASURED_STATE_TOO_SMALL}. 17820 */ 17821 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17822 final int specMode = MeasureSpec.getMode(measureSpec); 17823 final int specSize = MeasureSpec.getSize(measureSpec); 17824 final int result; 17825 switch (specMode) { 17826 case MeasureSpec.AT_MOST: 17827 if (specSize < size) { 17828 result = specSize | MEASURED_STATE_TOO_SMALL; 17829 } else { 17830 result = size; 17831 } 17832 break; 17833 case MeasureSpec.EXACTLY: 17834 result = specSize; 17835 break; 17836 case MeasureSpec.UNSPECIFIED: 17837 default: 17838 result = size; 17839 } 17840 return result | (childMeasuredState & MEASURED_STATE_MASK); 17841 } 17842 17843 /** 17844 * Utility to return a default size. Uses the supplied size if the 17845 * MeasureSpec imposed no constraints. Will get larger if allowed 17846 * by the MeasureSpec. 17847 * 17848 * @param size Default size for this view 17849 * @param measureSpec Constraints imposed by the parent 17850 * @return The size this view should be. 17851 */ 17852 public static int getDefaultSize(int size, int measureSpec) { 17853 int result = size; 17854 int specMode = MeasureSpec.getMode(measureSpec); 17855 int specSize = MeasureSpec.getSize(measureSpec); 17856 17857 switch (specMode) { 17858 case MeasureSpec.UNSPECIFIED: 17859 result = size; 17860 break; 17861 case MeasureSpec.AT_MOST: 17862 case MeasureSpec.EXACTLY: 17863 result = specSize; 17864 break; 17865 } 17866 return result; 17867 } 17868 17869 /** 17870 * Returns the suggested minimum height that the view should use. This 17871 * returns the maximum of the view's minimum height 17872 * and the background's minimum height 17873 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17874 * <p> 17875 * When being used in {@link #onMeasure(int, int)}, the caller should still 17876 * ensure the returned height is within the requirements of the parent. 17877 * 17878 * @return The suggested minimum height of the view. 17879 */ 17880 protected int getSuggestedMinimumHeight() { 17881 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17882 17883 } 17884 17885 /** 17886 * Returns the suggested minimum width that the view should use. This 17887 * returns the maximum of the view's minimum width) 17888 * and the background's minimum width 17889 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17890 * <p> 17891 * When being used in {@link #onMeasure(int, int)}, the caller should still 17892 * ensure the returned width is within the requirements of the parent. 17893 * 17894 * @return The suggested minimum width of the view. 17895 */ 17896 protected int getSuggestedMinimumWidth() { 17897 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17898 } 17899 17900 /** 17901 * Returns the minimum height of the view. 17902 * 17903 * @return the minimum height the view will try to be. 17904 * 17905 * @see #setMinimumHeight(int) 17906 * 17907 * @attr ref android.R.styleable#View_minHeight 17908 */ 17909 public int getMinimumHeight() { 17910 return mMinHeight; 17911 } 17912 17913 /** 17914 * Sets the minimum height of the view. It is not guaranteed the view will 17915 * be able to achieve this minimum height (for example, if its parent layout 17916 * constrains it with less available height). 17917 * 17918 * @param minHeight The minimum height the view will try to be. 17919 * 17920 * @see #getMinimumHeight() 17921 * 17922 * @attr ref android.R.styleable#View_minHeight 17923 */ 17924 public void setMinimumHeight(int minHeight) { 17925 mMinHeight = minHeight; 17926 requestLayout(); 17927 } 17928 17929 /** 17930 * Returns the minimum width of the view. 17931 * 17932 * @return the minimum width the view will try to be. 17933 * 17934 * @see #setMinimumWidth(int) 17935 * 17936 * @attr ref android.R.styleable#View_minWidth 17937 */ 17938 public int getMinimumWidth() { 17939 return mMinWidth; 17940 } 17941 17942 /** 17943 * Sets the minimum width of the view. It is not guaranteed the view will 17944 * be able to achieve this minimum width (for example, if its parent layout 17945 * constrains it with less available width). 17946 * 17947 * @param minWidth The minimum width the view will try to be. 17948 * 17949 * @see #getMinimumWidth() 17950 * 17951 * @attr ref android.R.styleable#View_minWidth 17952 */ 17953 public void setMinimumWidth(int minWidth) { 17954 mMinWidth = minWidth; 17955 requestLayout(); 17956 17957 } 17958 17959 /** 17960 * Get the animation currently associated with this view. 17961 * 17962 * @return The animation that is currently playing or 17963 * scheduled to play for this view. 17964 */ 17965 public Animation getAnimation() { 17966 return mCurrentAnimation; 17967 } 17968 17969 /** 17970 * Start the specified animation now. 17971 * 17972 * @param animation the animation to start now 17973 */ 17974 public void startAnimation(Animation animation) { 17975 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17976 setAnimation(animation); 17977 invalidateParentCaches(); 17978 invalidate(true); 17979 } 17980 17981 /** 17982 * Cancels any animations for this view. 17983 */ 17984 public void clearAnimation() { 17985 if (mCurrentAnimation != null) { 17986 mCurrentAnimation.detach(); 17987 } 17988 mCurrentAnimation = null; 17989 invalidateParentIfNeeded(); 17990 } 17991 17992 /** 17993 * Sets the next animation to play for this view. 17994 * If you want the animation to play immediately, use 17995 * {@link #startAnimation(android.view.animation.Animation)} instead. 17996 * This method provides allows fine-grained 17997 * control over the start time and invalidation, but you 17998 * must make sure that 1) the animation has a start time set, and 17999 * 2) the view's parent (which controls animations on its children) 18000 * will be invalidated when the animation is supposed to 18001 * start. 18002 * 18003 * @param animation The next animation, or null. 18004 */ 18005 public void setAnimation(Animation animation) { 18006 mCurrentAnimation = animation; 18007 18008 if (animation != null) { 18009 // If the screen is off assume the animation start time is now instead of 18010 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 18011 // would cause the animation to start when the screen turns back on 18012 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 18013 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 18014 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 18015 } 18016 animation.reset(); 18017 } 18018 } 18019 18020 /** 18021 * Invoked by a parent ViewGroup to notify the start of the animation 18022 * currently associated with this view. If you override this method, 18023 * always call super.onAnimationStart(); 18024 * 18025 * @see #setAnimation(android.view.animation.Animation) 18026 * @see #getAnimation() 18027 */ 18028 @CallSuper 18029 protected void onAnimationStart() { 18030 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 18031 } 18032 18033 /** 18034 * Invoked by a parent ViewGroup to notify the end of the animation 18035 * currently associated with this view. If you override this method, 18036 * always call super.onAnimationEnd(); 18037 * 18038 * @see #setAnimation(android.view.animation.Animation) 18039 * @see #getAnimation() 18040 */ 18041 @CallSuper 18042 protected void onAnimationEnd() { 18043 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 18044 } 18045 18046 /** 18047 * Invoked if there is a Transform that involves alpha. Subclass that can 18048 * draw themselves with the specified alpha should return true, and then 18049 * respect that alpha when their onDraw() is called. If this returns false 18050 * then the view may be redirected to draw into an offscreen buffer to 18051 * fulfill the request, which will look fine, but may be slower than if the 18052 * subclass handles it internally. The default implementation returns false. 18053 * 18054 * @param alpha The alpha (0..255) to apply to the view's drawing 18055 * @return true if the view can draw with the specified alpha. 18056 */ 18057 protected boolean onSetAlpha(int alpha) { 18058 return false; 18059 } 18060 18061 /** 18062 * This is used by the RootView to perform an optimization when 18063 * the view hierarchy contains one or several SurfaceView. 18064 * SurfaceView is always considered transparent, but its children are not, 18065 * therefore all View objects remove themselves from the global transparent 18066 * region (passed as a parameter to this function). 18067 * 18068 * @param region The transparent region for this ViewAncestor (window). 18069 * 18070 * @return Returns true if the effective visibility of the view at this 18071 * point is opaque, regardless of the transparent region; returns false 18072 * if it is possible for underlying windows to be seen behind the view. 18073 * 18074 * {@hide} 18075 */ 18076 public boolean gatherTransparentRegion(Region region) { 18077 final AttachInfo attachInfo = mAttachInfo; 18078 if (region != null && attachInfo != null) { 18079 final int pflags = mPrivateFlags; 18080 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 18081 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 18082 // remove it from the transparent region. 18083 final int[] location = attachInfo.mTransparentLocation; 18084 getLocationInWindow(location); 18085 region.op(location[0], location[1], location[0] + mRight - mLeft, 18086 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 18087 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 18088 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 18089 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 18090 // exists, so we remove the background drawable's non-transparent 18091 // parts from this transparent region. 18092 applyDrawableToTransparentRegion(mBackground, region); 18093 } 18094 } 18095 return true; 18096 } 18097 18098 /** 18099 * Play a sound effect for this view. 18100 * 18101 * <p>The framework will play sound effects for some built in actions, such as 18102 * clicking, but you may wish to play these effects in your widget, 18103 * for instance, for internal navigation. 18104 * 18105 * <p>The sound effect will only be played if sound effects are enabled by the user, and 18106 * {@link #isSoundEffectsEnabled()} is true. 18107 * 18108 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 18109 */ 18110 public void playSoundEffect(int soundConstant) { 18111 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 18112 return; 18113 } 18114 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 18115 } 18116 18117 /** 18118 * BZZZTT!!1! 18119 * 18120 * <p>Provide haptic feedback to the user for this view. 18121 * 18122 * <p>The framework will provide haptic feedback for some built in actions, 18123 * such as long presses, but you may wish to provide feedback for your 18124 * own widget. 18125 * 18126 * <p>The feedback will only be performed if 18127 * {@link #isHapticFeedbackEnabled()} is true. 18128 * 18129 * @param feedbackConstant One of the constants defined in 18130 * {@link HapticFeedbackConstants} 18131 */ 18132 public boolean performHapticFeedback(int feedbackConstant) { 18133 return performHapticFeedback(feedbackConstant, 0); 18134 } 18135 18136 /** 18137 * BZZZTT!!1! 18138 * 18139 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 18140 * 18141 * @param feedbackConstant One of the constants defined in 18142 * {@link HapticFeedbackConstants} 18143 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 18144 */ 18145 public boolean performHapticFeedback(int feedbackConstant, int flags) { 18146 if (mAttachInfo == null) { 18147 return false; 18148 } 18149 //noinspection SimplifiableIfStatement 18150 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 18151 && !isHapticFeedbackEnabled()) { 18152 return false; 18153 } 18154 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 18155 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 18156 } 18157 18158 /** 18159 * Request that the visibility of the status bar or other screen/window 18160 * decorations be changed. 18161 * 18162 * <p>This method is used to put the over device UI into temporary modes 18163 * where the user's attention is focused more on the application content, 18164 * by dimming or hiding surrounding system affordances. This is typically 18165 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 18166 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 18167 * to be placed behind the action bar (and with these flags other system 18168 * affordances) so that smooth transitions between hiding and showing them 18169 * can be done. 18170 * 18171 * <p>Two representative examples of the use of system UI visibility is 18172 * implementing a content browsing application (like a magazine reader) 18173 * and a video playing application. 18174 * 18175 * <p>The first code shows a typical implementation of a View in a content 18176 * browsing application. In this implementation, the application goes 18177 * into a content-oriented mode by hiding the status bar and action bar, 18178 * and putting the navigation elements into lights out mode. The user can 18179 * then interact with content while in this mode. Such an application should 18180 * provide an easy way for the user to toggle out of the mode (such as to 18181 * check information in the status bar or access notifications). In the 18182 * implementation here, this is done simply by tapping on the content. 18183 * 18184 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 18185 * content} 18186 * 18187 * <p>This second code sample shows a typical implementation of a View 18188 * in a video playing application. In this situation, while the video is 18189 * playing the application would like to go into a complete full-screen mode, 18190 * to use as much of the display as possible for the video. When in this state 18191 * the user can not interact with the application; the system intercepts 18192 * touching on the screen to pop the UI out of full screen mode. See 18193 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 18194 * 18195 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 18196 * content} 18197 * 18198 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18199 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18200 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18201 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18202 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18203 */ 18204 public void setSystemUiVisibility(int visibility) { 18205 if (visibility != mSystemUiVisibility) { 18206 mSystemUiVisibility = visibility; 18207 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18208 mParent.recomputeViewAttributes(this); 18209 } 18210 } 18211 } 18212 18213 /** 18214 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 18215 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18216 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18217 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18218 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18219 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18220 */ 18221 public int getSystemUiVisibility() { 18222 return mSystemUiVisibility; 18223 } 18224 18225 /** 18226 * Returns the current system UI visibility that is currently set for 18227 * the entire window. This is the combination of the 18228 * {@link #setSystemUiVisibility(int)} values supplied by all of the 18229 * views in the window. 18230 */ 18231 public int getWindowSystemUiVisibility() { 18232 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 18233 } 18234 18235 /** 18236 * Override to find out when the window's requested system UI visibility 18237 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 18238 * This is different from the callbacks received through 18239 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18240 * in that this is only telling you about the local request of the window, 18241 * not the actual values applied by the system. 18242 */ 18243 public void onWindowSystemUiVisibilityChanged(int visible) { 18244 } 18245 18246 /** 18247 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18248 * the view hierarchy. 18249 */ 18250 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18251 onWindowSystemUiVisibilityChanged(visible); 18252 } 18253 18254 /** 18255 * Set a listener to receive callbacks when the visibility of the system bar changes. 18256 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18257 */ 18258 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18259 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18260 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18261 mParent.recomputeViewAttributes(this); 18262 } 18263 } 18264 18265 /** 18266 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18267 * the view hierarchy. 18268 */ 18269 public void dispatchSystemUiVisibilityChanged(int visibility) { 18270 ListenerInfo li = mListenerInfo; 18271 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18272 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18273 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18274 } 18275 } 18276 18277 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18278 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18279 if (val != mSystemUiVisibility) { 18280 setSystemUiVisibility(val); 18281 return true; 18282 } 18283 return false; 18284 } 18285 18286 /** @hide */ 18287 public void setDisabledSystemUiVisibility(int flags) { 18288 if (mAttachInfo != null) { 18289 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18290 mAttachInfo.mDisabledSystemUiVisibility = flags; 18291 if (mParent != null) { 18292 mParent.recomputeViewAttributes(this); 18293 } 18294 } 18295 } 18296 } 18297 18298 /** 18299 * Creates an image that the system displays during the drag and drop 18300 * operation. This is called a "drag shadow". The default implementation 18301 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18302 * appearance as the given View. The default also positions the center of the drag shadow 18303 * directly under the touch point. If no View is provided (the constructor with no parameters 18304 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18305 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 18306 * default is an invisible drag shadow. 18307 * <p> 18308 * You are not required to use the View you provide to the constructor as the basis of the 18309 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18310 * anything you want as the drag shadow. 18311 * </p> 18312 * <p> 18313 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18314 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18315 * size and position of the drag shadow. It uses this data to construct a 18316 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18317 * so that your application can draw the shadow image in the Canvas. 18318 * </p> 18319 * 18320 * <div class="special reference"> 18321 * <h3>Developer Guides</h3> 18322 * <p>For a guide to implementing drag and drop features, read the 18323 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18324 * </div> 18325 */ 18326 public static class DragShadowBuilder { 18327 private final WeakReference<View> mView; 18328 18329 /** 18330 * Constructs a shadow image builder based on a View. By default, the resulting drag 18331 * shadow will have the same appearance and dimensions as the View, with the touch point 18332 * over the center of the View. 18333 * @param view A View. Any View in scope can be used. 18334 */ 18335 public DragShadowBuilder(View view) { 18336 mView = new WeakReference<View>(view); 18337 } 18338 18339 /** 18340 * Construct a shadow builder object with no associated View. This 18341 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18342 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18343 * to supply the drag shadow's dimensions and appearance without 18344 * reference to any View object. If they are not overridden, then the result is an 18345 * invisible drag shadow. 18346 */ 18347 public DragShadowBuilder() { 18348 mView = new WeakReference<View>(null); 18349 } 18350 18351 /** 18352 * Returns the View object that had been passed to the 18353 * {@link #View.DragShadowBuilder(View)} 18354 * constructor. If that View parameter was {@code null} or if the 18355 * {@link #View.DragShadowBuilder()} 18356 * constructor was used to instantiate the builder object, this method will return 18357 * null. 18358 * 18359 * @return The View object associate with this builder object. 18360 */ 18361 @SuppressWarnings({"JavadocReference"}) 18362 final public View getView() { 18363 return mView.get(); 18364 } 18365 18366 /** 18367 * Provides the metrics for the shadow image. These include the dimensions of 18368 * the shadow image, and the point within that shadow that should 18369 * be centered under the touch location while dragging. 18370 * <p> 18371 * The default implementation sets the dimensions of the shadow to be the 18372 * same as the dimensions of the View itself and centers the shadow under 18373 * the touch point. 18374 * </p> 18375 * 18376 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18377 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18378 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18379 * image. 18380 * 18381 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18382 * shadow image that should be underneath the touch point during the drag and drop 18383 * operation. Your application must set {@link android.graphics.Point#x} to the 18384 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18385 */ 18386 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18387 final View view = mView.get(); 18388 if (view != null) { 18389 shadowSize.set(view.getWidth(), view.getHeight()); 18390 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18391 } else { 18392 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18393 } 18394 } 18395 18396 /** 18397 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18398 * based on the dimensions it received from the 18399 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18400 * 18401 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18402 */ 18403 public void onDrawShadow(Canvas canvas) { 18404 final View view = mView.get(); 18405 if (view != null) { 18406 view.draw(canvas); 18407 } else { 18408 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18409 } 18410 } 18411 } 18412 18413 /** 18414 * Starts a drag and drop operation. When your application calls this method, it passes a 18415 * {@link android.view.View.DragShadowBuilder} object to the system. The 18416 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18417 * to get metrics for the drag shadow, and then calls the object's 18418 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18419 * <p> 18420 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18421 * drag events to all the View objects in your application that are currently visible. It does 18422 * this either by calling the View object's drag listener (an implementation of 18423 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18424 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18425 * Both are passed a {@link android.view.DragEvent} object that has a 18426 * {@link android.view.DragEvent#getAction()} value of 18427 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18428 * </p> 18429 * <p> 18430 * Your application can invoke startDrag() on any attached View object. The View object does not 18431 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18432 * be related to the View the user selected for dragging. 18433 * </p> 18434 * @param data A {@link android.content.ClipData} object pointing to the data to be 18435 * transferred by the drag and drop operation. 18436 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18437 * drag shadow. 18438 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18439 * drop operation. This Object is put into every DragEvent object sent by the system during the 18440 * current drag. 18441 * <p> 18442 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18443 * to the target Views. For example, it can contain flags that differentiate between a 18444 * a copy operation and a move operation. 18445 * </p> 18446 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18447 * so the parameter should be set to 0. 18448 * @return {@code true} if the method completes successfully, or 18449 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18450 * do a drag, and so no drag operation is in progress. 18451 */ 18452 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18453 Object myLocalState, int flags) { 18454 if (ViewDebug.DEBUG_DRAG) { 18455 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18456 } 18457 boolean okay = false; 18458 18459 Point shadowSize = new Point(); 18460 Point shadowTouchPoint = new Point(); 18461 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18462 18463 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18464 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18465 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18466 } 18467 18468 if (ViewDebug.DEBUG_DRAG) { 18469 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18470 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18471 } 18472 Surface surface = new Surface(); 18473 try { 18474 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18475 flags, shadowSize.x, shadowSize.y, surface); 18476 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18477 + " surface=" + surface); 18478 if (token != null) { 18479 Canvas canvas = surface.lockCanvas(null); 18480 try { 18481 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18482 shadowBuilder.onDrawShadow(canvas); 18483 } finally { 18484 surface.unlockCanvasAndPost(canvas); 18485 } 18486 18487 final ViewRootImpl root = getViewRootImpl(); 18488 18489 // Cache the local state object for delivery with DragEvents 18490 root.setLocalDragState(myLocalState); 18491 18492 // repurpose 'shadowSize' for the last touch point 18493 root.getLastTouchPoint(shadowSize); 18494 18495 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18496 shadowSize.x, shadowSize.y, 18497 shadowTouchPoint.x, shadowTouchPoint.y, data); 18498 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18499 18500 // Off and running! Release our local surface instance; the drag 18501 // shadow surface is now managed by the system process. 18502 surface.release(); 18503 } 18504 } catch (Exception e) { 18505 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18506 surface.destroy(); 18507 } 18508 18509 return okay; 18510 } 18511 18512 /** 18513 * Handles drag events sent by the system following a call to 18514 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18515 *<p> 18516 * When the system calls this method, it passes a 18517 * {@link android.view.DragEvent} object. A call to 18518 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18519 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18520 * operation. 18521 * @param event The {@link android.view.DragEvent} sent by the system. 18522 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18523 * in DragEvent, indicating the type of drag event represented by this object. 18524 * @return {@code true} if the method was successful, otherwise {@code false}. 18525 * <p> 18526 * The method should return {@code true} in response to an action type of 18527 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18528 * operation. 18529 * </p> 18530 * <p> 18531 * The method should also return {@code true} in response to an action type of 18532 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18533 * {@code false} if it didn't. 18534 * </p> 18535 */ 18536 public boolean onDragEvent(DragEvent event) { 18537 return false; 18538 } 18539 18540 /** 18541 * Detects if this View is enabled and has a drag event listener. 18542 * If both are true, then it calls the drag event listener with the 18543 * {@link android.view.DragEvent} it received. If the drag event listener returns 18544 * {@code true}, then dispatchDragEvent() returns {@code true}. 18545 * <p> 18546 * For all other cases, the method calls the 18547 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18548 * method and returns its result. 18549 * </p> 18550 * <p> 18551 * This ensures that a drag event is always consumed, even if the View does not have a drag 18552 * event listener. However, if the View has a listener and the listener returns true, then 18553 * onDragEvent() is not called. 18554 * </p> 18555 */ 18556 public boolean dispatchDragEvent(DragEvent event) { 18557 ListenerInfo li = mListenerInfo; 18558 //noinspection SimplifiableIfStatement 18559 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18560 && li.mOnDragListener.onDrag(this, event)) { 18561 return true; 18562 } 18563 return onDragEvent(event); 18564 } 18565 18566 boolean canAcceptDrag() { 18567 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18568 } 18569 18570 /** 18571 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18572 * it is ever exposed at all. 18573 * @hide 18574 */ 18575 public void onCloseSystemDialogs(String reason) { 18576 } 18577 18578 /** 18579 * Given a Drawable whose bounds have been set to draw into this view, 18580 * update a Region being computed for 18581 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18582 * that any non-transparent parts of the Drawable are removed from the 18583 * given transparent region. 18584 * 18585 * @param dr The Drawable whose transparency is to be applied to the region. 18586 * @param region A Region holding the current transparency information, 18587 * where any parts of the region that are set are considered to be 18588 * transparent. On return, this region will be modified to have the 18589 * transparency information reduced by the corresponding parts of the 18590 * Drawable that are not transparent. 18591 * {@hide} 18592 */ 18593 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18594 if (DBG) { 18595 Log.i("View", "Getting transparent region for: " + this); 18596 } 18597 final Region r = dr.getTransparentRegion(); 18598 final Rect db = dr.getBounds(); 18599 final AttachInfo attachInfo = mAttachInfo; 18600 if (r != null && attachInfo != null) { 18601 final int w = getRight()-getLeft(); 18602 final int h = getBottom()-getTop(); 18603 if (db.left > 0) { 18604 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18605 r.op(0, 0, db.left, h, Region.Op.UNION); 18606 } 18607 if (db.right < w) { 18608 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18609 r.op(db.right, 0, w, h, Region.Op.UNION); 18610 } 18611 if (db.top > 0) { 18612 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18613 r.op(0, 0, w, db.top, Region.Op.UNION); 18614 } 18615 if (db.bottom < h) { 18616 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18617 r.op(0, db.bottom, w, h, Region.Op.UNION); 18618 } 18619 final int[] location = attachInfo.mTransparentLocation; 18620 getLocationInWindow(location); 18621 r.translate(location[0], location[1]); 18622 region.op(r, Region.Op.INTERSECT); 18623 } else { 18624 region.op(db, Region.Op.DIFFERENCE); 18625 } 18626 } 18627 18628 private void checkForLongClick(int delayOffset) { 18629 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18630 mHasPerformedLongPress = false; 18631 18632 if (mPendingCheckForLongPress == null) { 18633 mPendingCheckForLongPress = new CheckForLongPress(); 18634 } 18635 mPendingCheckForLongPress.rememberWindowAttachCount(); 18636 postDelayed(mPendingCheckForLongPress, 18637 ViewConfiguration.getLongPressTimeout() - delayOffset); 18638 } 18639 } 18640 18641 /** 18642 * Inflate a view from an XML resource. This convenience method wraps the {@link 18643 * LayoutInflater} class, which provides a full range of options for view inflation. 18644 * 18645 * @param context The Context object for your activity or application. 18646 * @param resource The resource ID to inflate 18647 * @param root A view group that will be the parent. Used to properly inflate the 18648 * layout_* parameters. 18649 * @see LayoutInflater 18650 */ 18651 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 18652 LayoutInflater factory = LayoutInflater.from(context); 18653 return factory.inflate(resource, root); 18654 } 18655 18656 /** 18657 * Scroll the view with standard behavior for scrolling beyond the normal 18658 * content boundaries. Views that call this method should override 18659 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18660 * results of an over-scroll operation. 18661 * 18662 * Views can use this method to handle any touch or fling-based scrolling. 18663 * 18664 * @param deltaX Change in X in pixels 18665 * @param deltaY Change in Y in pixels 18666 * @param scrollX Current X scroll value in pixels before applying deltaX 18667 * @param scrollY Current Y scroll value in pixels before applying deltaY 18668 * @param scrollRangeX Maximum content scroll range along the X axis 18669 * @param scrollRangeY Maximum content scroll range along the Y axis 18670 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18671 * along the X axis. 18672 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18673 * along the Y axis. 18674 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18675 * @return true if scrolling was clamped to an over-scroll boundary along either 18676 * axis, false otherwise. 18677 */ 18678 @SuppressWarnings({"UnusedParameters"}) 18679 protected boolean overScrollBy(int deltaX, int deltaY, 18680 int scrollX, int scrollY, 18681 int scrollRangeX, int scrollRangeY, 18682 int maxOverScrollX, int maxOverScrollY, 18683 boolean isTouchEvent) { 18684 final int overScrollMode = mOverScrollMode; 18685 final boolean canScrollHorizontal = 18686 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18687 final boolean canScrollVertical = 18688 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18689 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18690 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18691 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18692 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18693 18694 int newScrollX = scrollX + deltaX; 18695 if (!overScrollHorizontal) { 18696 maxOverScrollX = 0; 18697 } 18698 18699 int newScrollY = scrollY + deltaY; 18700 if (!overScrollVertical) { 18701 maxOverScrollY = 0; 18702 } 18703 18704 // Clamp values if at the limits and record 18705 final int left = -maxOverScrollX; 18706 final int right = maxOverScrollX + scrollRangeX; 18707 final int top = -maxOverScrollY; 18708 final int bottom = maxOverScrollY + scrollRangeY; 18709 18710 boolean clampedX = false; 18711 if (newScrollX > right) { 18712 newScrollX = right; 18713 clampedX = true; 18714 } else if (newScrollX < left) { 18715 newScrollX = left; 18716 clampedX = true; 18717 } 18718 18719 boolean clampedY = false; 18720 if (newScrollY > bottom) { 18721 newScrollY = bottom; 18722 clampedY = true; 18723 } else if (newScrollY < top) { 18724 newScrollY = top; 18725 clampedY = true; 18726 } 18727 18728 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18729 18730 return clampedX || clampedY; 18731 } 18732 18733 /** 18734 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18735 * respond to the results of an over-scroll operation. 18736 * 18737 * @param scrollX New X scroll value in pixels 18738 * @param scrollY New Y scroll value in pixels 18739 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18740 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18741 */ 18742 protected void onOverScrolled(int scrollX, int scrollY, 18743 boolean clampedX, boolean clampedY) { 18744 // Intentionally empty. 18745 } 18746 18747 /** 18748 * Returns the over-scroll mode for this view. The result will be 18749 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18750 * (allow over-scrolling only if the view content is larger than the container), 18751 * or {@link #OVER_SCROLL_NEVER}. 18752 * 18753 * @return This view's over-scroll mode. 18754 */ 18755 public int getOverScrollMode() { 18756 return mOverScrollMode; 18757 } 18758 18759 /** 18760 * Set the over-scroll mode for this view. Valid over-scroll modes are 18761 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18762 * (allow over-scrolling only if the view content is larger than the container), 18763 * or {@link #OVER_SCROLL_NEVER}. 18764 * 18765 * Setting the over-scroll mode of a view will have an effect only if the 18766 * view is capable of scrolling. 18767 * 18768 * @param overScrollMode The new over-scroll mode for this view. 18769 */ 18770 public void setOverScrollMode(int overScrollMode) { 18771 if (overScrollMode != OVER_SCROLL_ALWAYS && 18772 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18773 overScrollMode != OVER_SCROLL_NEVER) { 18774 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18775 } 18776 mOverScrollMode = overScrollMode; 18777 } 18778 18779 /** 18780 * Enable or disable nested scrolling for this view. 18781 * 18782 * <p>If this property is set to true the view will be permitted to initiate nested 18783 * scrolling operations with a compatible parent view in the current hierarchy. If this 18784 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18785 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18786 * the nested scroll.</p> 18787 * 18788 * @param enabled true to enable nested scrolling, false to disable 18789 * 18790 * @see #isNestedScrollingEnabled() 18791 */ 18792 public void setNestedScrollingEnabled(boolean enabled) { 18793 if (enabled) { 18794 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18795 } else { 18796 stopNestedScroll(); 18797 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18798 } 18799 } 18800 18801 /** 18802 * Returns true if nested scrolling is enabled for this view. 18803 * 18804 * <p>If nested scrolling is enabled and this View class implementation supports it, 18805 * this view will act as a nested scrolling child view when applicable, forwarding data 18806 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18807 * parent.</p> 18808 * 18809 * @return true if nested scrolling is enabled 18810 * 18811 * @see #setNestedScrollingEnabled(boolean) 18812 */ 18813 public boolean isNestedScrollingEnabled() { 18814 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18815 PFLAG3_NESTED_SCROLLING_ENABLED; 18816 } 18817 18818 /** 18819 * Begin a nestable scroll operation along the given axes. 18820 * 18821 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18822 * 18823 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18824 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18825 * In the case of touch scrolling the nested scroll will be terminated automatically in 18826 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18827 * In the event of programmatic scrolling the caller must explicitly call 18828 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18829 * 18830 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18831 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18832 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18833 * 18834 * <p>At each incremental step of the scroll the caller should invoke 18835 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18836 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18837 * parent at least partially consumed the scroll and the caller should adjust the amount it 18838 * scrolls by.</p> 18839 * 18840 * <p>After applying the remainder of the scroll delta the caller should invoke 18841 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18842 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18843 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18844 * </p> 18845 * 18846 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18847 * {@link #SCROLL_AXIS_VERTICAL}. 18848 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18849 * the current gesture. 18850 * 18851 * @see #stopNestedScroll() 18852 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18853 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18854 */ 18855 public boolean startNestedScroll(int axes) { 18856 if (hasNestedScrollingParent()) { 18857 // Already in progress 18858 return true; 18859 } 18860 if (isNestedScrollingEnabled()) { 18861 ViewParent p = getParent(); 18862 View child = this; 18863 while (p != null) { 18864 try { 18865 if (p.onStartNestedScroll(child, this, axes)) { 18866 mNestedScrollingParent = p; 18867 p.onNestedScrollAccepted(child, this, axes); 18868 return true; 18869 } 18870 } catch (AbstractMethodError e) { 18871 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18872 "method onStartNestedScroll", e); 18873 // Allow the search upward to continue 18874 } 18875 if (p instanceof View) { 18876 child = (View) p; 18877 } 18878 p = p.getParent(); 18879 } 18880 } 18881 return false; 18882 } 18883 18884 /** 18885 * Stop a nested scroll in progress. 18886 * 18887 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18888 * 18889 * @see #startNestedScroll(int) 18890 */ 18891 public void stopNestedScroll() { 18892 if (mNestedScrollingParent != null) { 18893 mNestedScrollingParent.onStopNestedScroll(this); 18894 mNestedScrollingParent = null; 18895 } 18896 } 18897 18898 /** 18899 * Returns true if this view has a nested scrolling parent. 18900 * 18901 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18902 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18903 * 18904 * @return whether this view has a nested scrolling parent 18905 */ 18906 public boolean hasNestedScrollingParent() { 18907 return mNestedScrollingParent != null; 18908 } 18909 18910 /** 18911 * Dispatch one step of a nested scroll in progress. 18912 * 18913 * <p>Implementations of views that support nested scrolling should call this to report 18914 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18915 * is not currently in progress or nested scrolling is not 18916 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18917 * 18918 * <p>Compatible View implementations should also call 18919 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18920 * consuming a component of the scroll event themselves.</p> 18921 * 18922 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18923 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18924 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18925 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18926 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18927 * in local view coordinates of this view from before this operation 18928 * to after it completes. View implementations may use this to adjust 18929 * expected input coordinate tracking. 18930 * @return true if the event was dispatched, false if it could not be dispatched. 18931 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18932 */ 18933 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18934 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 18935 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18936 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18937 int startX = 0; 18938 int startY = 0; 18939 if (offsetInWindow != null) { 18940 getLocationInWindow(offsetInWindow); 18941 startX = offsetInWindow[0]; 18942 startY = offsetInWindow[1]; 18943 } 18944 18945 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18946 dxUnconsumed, dyUnconsumed); 18947 18948 if (offsetInWindow != null) { 18949 getLocationInWindow(offsetInWindow); 18950 offsetInWindow[0] -= startX; 18951 offsetInWindow[1] -= startY; 18952 } 18953 return true; 18954 } else if (offsetInWindow != null) { 18955 // No motion, no dispatch. Keep offsetInWindow up to date. 18956 offsetInWindow[0] = 0; 18957 offsetInWindow[1] = 0; 18958 } 18959 } 18960 return false; 18961 } 18962 18963 /** 18964 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18965 * 18966 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18967 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18968 * scrolling operation to consume some or all of the scroll operation before the child view 18969 * consumes it.</p> 18970 * 18971 * @param dx Horizontal scroll distance in pixels 18972 * @param dy Vertical scroll distance in pixels 18973 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18974 * and consumed[1] the consumed dy. 18975 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18976 * in local view coordinates of this view from before this operation 18977 * to after it completes. View implementations may use this to adjust 18978 * expected input coordinate tracking. 18979 * @return true if the parent consumed some or all of the scroll delta 18980 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18981 */ 18982 public boolean dispatchNestedPreScroll(int dx, int dy, 18983 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 18984 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18985 if (dx != 0 || dy != 0) { 18986 int startX = 0; 18987 int startY = 0; 18988 if (offsetInWindow != null) { 18989 getLocationInWindow(offsetInWindow); 18990 startX = offsetInWindow[0]; 18991 startY = offsetInWindow[1]; 18992 } 18993 18994 if (consumed == null) { 18995 if (mTempNestedScrollConsumed == null) { 18996 mTempNestedScrollConsumed = new int[2]; 18997 } 18998 consumed = mTempNestedScrollConsumed; 18999 } 19000 consumed[0] = 0; 19001 consumed[1] = 0; 19002 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 19003 19004 if (offsetInWindow != null) { 19005 getLocationInWindow(offsetInWindow); 19006 offsetInWindow[0] -= startX; 19007 offsetInWindow[1] -= startY; 19008 } 19009 return consumed[0] != 0 || consumed[1] != 0; 19010 } else if (offsetInWindow != null) { 19011 offsetInWindow[0] = 0; 19012 offsetInWindow[1] = 0; 19013 } 19014 } 19015 return false; 19016 } 19017 19018 /** 19019 * Dispatch a fling to a nested scrolling parent. 19020 * 19021 * <p>This method should be used to indicate that a nested scrolling child has detected 19022 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 19023 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 19024 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 19025 * along a scrollable axis.</p> 19026 * 19027 * <p>If a nested scrolling child view would normally fling but it is at the edge of 19028 * its own content, it can use this method to delegate the fling to its nested scrolling 19029 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 19030 * 19031 * @param velocityX Horizontal fling velocity in pixels per second 19032 * @param velocityY Vertical fling velocity in pixels per second 19033 * @param consumed true if the child consumed the fling, false otherwise 19034 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 19035 */ 19036 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 19037 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19038 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 19039 } 19040 return false; 19041 } 19042 19043 /** 19044 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 19045 * 19046 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 19047 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 19048 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 19049 * before the child view consumes it. If this method returns <code>true</code>, a nested 19050 * parent view consumed the fling and this view should not scroll as a result.</p> 19051 * 19052 * <p>For a better user experience, only one view in a nested scrolling chain should consume 19053 * the fling at a time. If a parent view consumed the fling this method will return false. 19054 * Custom view implementations should account for this in two ways:</p> 19055 * 19056 * <ul> 19057 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 19058 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 19059 * position regardless.</li> 19060 * <li>If a nested parent does consume the fling, this view should not scroll at all, 19061 * even to settle back to a valid idle position.</li> 19062 * </ul> 19063 * 19064 * <p>Views should also not offer fling velocities to nested parent views along an axis 19065 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 19066 * should not offer a horizontal fling velocity to its parents since scrolling along that 19067 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 19068 * 19069 * @param velocityX Horizontal fling velocity in pixels per second 19070 * @param velocityY Vertical fling velocity in pixels per second 19071 * @return true if a nested scrolling parent consumed the fling 19072 */ 19073 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 19074 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 19075 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 19076 } 19077 return false; 19078 } 19079 19080 /** 19081 * Gets a scale factor that determines the distance the view should scroll 19082 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 19083 * @return The vertical scroll scale factor. 19084 * @hide 19085 */ 19086 protected float getVerticalScrollFactor() { 19087 if (mVerticalScrollFactor == 0) { 19088 TypedValue outValue = new TypedValue(); 19089 if (!mContext.getTheme().resolveAttribute( 19090 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 19091 throw new IllegalStateException( 19092 "Expected theme to define listPreferredItemHeight."); 19093 } 19094 mVerticalScrollFactor = outValue.getDimension( 19095 mContext.getResources().getDisplayMetrics()); 19096 } 19097 return mVerticalScrollFactor; 19098 } 19099 19100 /** 19101 * Gets a scale factor that determines the distance the view should scroll 19102 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 19103 * @return The horizontal scroll scale factor. 19104 * @hide 19105 */ 19106 protected float getHorizontalScrollFactor() { 19107 // TODO: Should use something else. 19108 return getVerticalScrollFactor(); 19109 } 19110 19111 /** 19112 * Return the value specifying the text direction or policy that was set with 19113 * {@link #setTextDirection(int)}. 19114 * 19115 * @return the defined text direction. It can be one of: 19116 * 19117 * {@link #TEXT_DIRECTION_INHERIT}, 19118 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19119 * {@link #TEXT_DIRECTION_ANY_RTL}, 19120 * {@link #TEXT_DIRECTION_LTR}, 19121 * {@link #TEXT_DIRECTION_RTL}, 19122 * {@link #TEXT_DIRECTION_LOCALE} 19123 * 19124 * @attr ref android.R.styleable#View_textDirection 19125 * 19126 * @hide 19127 */ 19128 @ViewDebug.ExportedProperty(category = "text", mapping = { 19129 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19130 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19131 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19132 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19133 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19134 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19135 }) 19136 public int getRawTextDirection() { 19137 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 19138 } 19139 19140 /** 19141 * Set the text direction. 19142 * 19143 * @param textDirection the direction to set. Should be one of: 19144 * 19145 * {@link #TEXT_DIRECTION_INHERIT}, 19146 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19147 * {@link #TEXT_DIRECTION_ANY_RTL}, 19148 * {@link #TEXT_DIRECTION_LTR}, 19149 * {@link #TEXT_DIRECTION_RTL}, 19150 * {@link #TEXT_DIRECTION_LOCALE} 19151 * 19152 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 19153 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 19154 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 19155 * 19156 * @attr ref android.R.styleable#View_textDirection 19157 */ 19158 public void setTextDirection(int textDirection) { 19159 if (getRawTextDirection() != textDirection) { 19160 // Reset the current text direction and the resolved one 19161 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 19162 resetResolvedTextDirection(); 19163 // Set the new text direction 19164 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 19165 // Do resolution 19166 resolveTextDirection(); 19167 // Notify change 19168 onRtlPropertiesChanged(getLayoutDirection()); 19169 // Refresh 19170 requestLayout(); 19171 invalidate(true); 19172 } 19173 } 19174 19175 /** 19176 * Return the resolved text direction. 19177 * 19178 * @return the resolved text direction. Returns one of: 19179 * 19180 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19181 * {@link #TEXT_DIRECTION_ANY_RTL}, 19182 * {@link #TEXT_DIRECTION_LTR}, 19183 * {@link #TEXT_DIRECTION_RTL}, 19184 * {@link #TEXT_DIRECTION_LOCALE} 19185 * 19186 * @attr ref android.R.styleable#View_textDirection 19187 */ 19188 @ViewDebug.ExportedProperty(category = "text", mapping = { 19189 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19190 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19191 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19192 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19193 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19194 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19195 }) 19196 public int getTextDirection() { 19197 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 19198 } 19199 19200 /** 19201 * Resolve the text direction. 19202 * 19203 * @return true if resolution has been done, false otherwise. 19204 * 19205 * @hide 19206 */ 19207 public boolean resolveTextDirection() { 19208 // Reset any previous text direction resolution 19209 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19210 19211 if (hasRtlSupport()) { 19212 // Set resolved text direction flag depending on text direction flag 19213 final int textDirection = getRawTextDirection(); 19214 switch(textDirection) { 19215 case TEXT_DIRECTION_INHERIT: 19216 if (!canResolveTextDirection()) { 19217 // We cannot do the resolution if there is no parent, so use the default one 19218 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19219 // Resolution will need to happen again later 19220 return false; 19221 } 19222 19223 // Parent has not yet resolved, so we still return the default 19224 try { 19225 if (!mParent.isTextDirectionResolved()) { 19226 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19227 // Resolution will need to happen again later 19228 return false; 19229 } 19230 } catch (AbstractMethodError e) { 19231 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19232 " does not fully implement ViewParent", e); 19233 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 19234 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19235 return true; 19236 } 19237 19238 // Set current resolved direction to the same value as the parent's one 19239 int parentResolvedDirection; 19240 try { 19241 parentResolvedDirection = mParent.getTextDirection(); 19242 } catch (AbstractMethodError e) { 19243 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19244 " does not fully implement ViewParent", e); 19245 parentResolvedDirection = TEXT_DIRECTION_LTR; 19246 } 19247 switch (parentResolvedDirection) { 19248 case TEXT_DIRECTION_FIRST_STRONG: 19249 case TEXT_DIRECTION_ANY_RTL: 19250 case TEXT_DIRECTION_LTR: 19251 case TEXT_DIRECTION_RTL: 19252 case TEXT_DIRECTION_LOCALE: 19253 mPrivateFlags2 |= 19254 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19255 break; 19256 default: 19257 // Default resolved direction is "first strong" heuristic 19258 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19259 } 19260 break; 19261 case TEXT_DIRECTION_FIRST_STRONG: 19262 case TEXT_DIRECTION_ANY_RTL: 19263 case TEXT_DIRECTION_LTR: 19264 case TEXT_DIRECTION_RTL: 19265 case TEXT_DIRECTION_LOCALE: 19266 // Resolved direction is the same as text direction 19267 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19268 break; 19269 default: 19270 // Default resolved direction is "first strong" heuristic 19271 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19272 } 19273 } else { 19274 // Default resolved direction is "first strong" heuristic 19275 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19276 } 19277 19278 // Set to resolved 19279 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19280 return true; 19281 } 19282 19283 /** 19284 * Check if text direction resolution can be done. 19285 * 19286 * @return true if text direction resolution can be done otherwise return false. 19287 */ 19288 public boolean canResolveTextDirection() { 19289 switch (getRawTextDirection()) { 19290 case TEXT_DIRECTION_INHERIT: 19291 if (mParent != null) { 19292 try { 19293 return mParent.canResolveTextDirection(); 19294 } catch (AbstractMethodError e) { 19295 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19296 " does not fully implement ViewParent", e); 19297 } 19298 } 19299 return false; 19300 19301 default: 19302 return true; 19303 } 19304 } 19305 19306 /** 19307 * Reset resolved text direction. Text direction will be resolved during a call to 19308 * {@link #onMeasure(int, int)}. 19309 * 19310 * @hide 19311 */ 19312 public void resetResolvedTextDirection() { 19313 // Reset any previous text direction resolution 19314 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19315 // Set to default value 19316 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19317 } 19318 19319 /** 19320 * @return true if text direction is inherited. 19321 * 19322 * @hide 19323 */ 19324 public boolean isTextDirectionInherited() { 19325 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19326 } 19327 19328 /** 19329 * @return true if text direction is resolved. 19330 */ 19331 public boolean isTextDirectionResolved() { 19332 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19333 } 19334 19335 /** 19336 * Return the value specifying the text alignment or policy that was set with 19337 * {@link #setTextAlignment(int)}. 19338 * 19339 * @return the defined text alignment. It can be one of: 19340 * 19341 * {@link #TEXT_ALIGNMENT_INHERIT}, 19342 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19343 * {@link #TEXT_ALIGNMENT_CENTER}, 19344 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19345 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19346 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19347 * {@link #TEXT_ALIGNMENT_VIEW_END} 19348 * 19349 * @attr ref android.R.styleable#View_textAlignment 19350 * 19351 * @hide 19352 */ 19353 @ViewDebug.ExportedProperty(category = "text", mapping = { 19354 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19355 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19356 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19357 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19358 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19359 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19360 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19361 }) 19362 @TextAlignment 19363 public int getRawTextAlignment() { 19364 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19365 } 19366 19367 /** 19368 * Set the text alignment. 19369 * 19370 * @param textAlignment The text alignment to set. Should be one of 19371 * 19372 * {@link #TEXT_ALIGNMENT_INHERIT}, 19373 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19374 * {@link #TEXT_ALIGNMENT_CENTER}, 19375 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19376 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19377 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19378 * {@link #TEXT_ALIGNMENT_VIEW_END} 19379 * 19380 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19381 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19382 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19383 * 19384 * @attr ref android.R.styleable#View_textAlignment 19385 */ 19386 public void setTextAlignment(@TextAlignment int textAlignment) { 19387 if (textAlignment != getRawTextAlignment()) { 19388 // Reset the current and resolved text alignment 19389 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19390 resetResolvedTextAlignment(); 19391 // Set the new text alignment 19392 mPrivateFlags2 |= 19393 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19394 // Do resolution 19395 resolveTextAlignment(); 19396 // Notify change 19397 onRtlPropertiesChanged(getLayoutDirection()); 19398 // Refresh 19399 requestLayout(); 19400 invalidate(true); 19401 } 19402 } 19403 19404 /** 19405 * Return the resolved text alignment. 19406 * 19407 * @return the resolved text alignment. Returns one of: 19408 * 19409 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19410 * {@link #TEXT_ALIGNMENT_CENTER}, 19411 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19412 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19413 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19414 * {@link #TEXT_ALIGNMENT_VIEW_END} 19415 * 19416 * @attr ref android.R.styleable#View_textAlignment 19417 */ 19418 @ViewDebug.ExportedProperty(category = "text", mapping = { 19419 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19420 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19421 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19422 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19423 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19424 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19425 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19426 }) 19427 @TextAlignment 19428 public int getTextAlignment() { 19429 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19430 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19431 } 19432 19433 /** 19434 * Resolve the text alignment. 19435 * 19436 * @return true if resolution has been done, false otherwise. 19437 * 19438 * @hide 19439 */ 19440 public boolean resolveTextAlignment() { 19441 // Reset any previous text alignment resolution 19442 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19443 19444 if (hasRtlSupport()) { 19445 // Set resolved text alignment flag depending on text alignment flag 19446 final int textAlignment = getRawTextAlignment(); 19447 switch (textAlignment) { 19448 case TEXT_ALIGNMENT_INHERIT: 19449 // Check if we can resolve the text alignment 19450 if (!canResolveTextAlignment()) { 19451 // We cannot do the resolution if there is no parent so use the default 19452 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19453 // Resolution will need to happen again later 19454 return false; 19455 } 19456 19457 // Parent has not yet resolved, so we still return the default 19458 try { 19459 if (!mParent.isTextAlignmentResolved()) { 19460 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19461 // Resolution will need to happen again later 19462 return false; 19463 } 19464 } catch (AbstractMethodError e) { 19465 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19466 " does not fully implement ViewParent", e); 19467 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19468 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19469 return true; 19470 } 19471 19472 int parentResolvedTextAlignment; 19473 try { 19474 parentResolvedTextAlignment = mParent.getTextAlignment(); 19475 } catch (AbstractMethodError e) { 19476 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19477 " does not fully implement ViewParent", e); 19478 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19479 } 19480 switch (parentResolvedTextAlignment) { 19481 case TEXT_ALIGNMENT_GRAVITY: 19482 case TEXT_ALIGNMENT_TEXT_START: 19483 case TEXT_ALIGNMENT_TEXT_END: 19484 case TEXT_ALIGNMENT_CENTER: 19485 case TEXT_ALIGNMENT_VIEW_START: 19486 case TEXT_ALIGNMENT_VIEW_END: 19487 // Resolved text alignment is the same as the parent resolved 19488 // text alignment 19489 mPrivateFlags2 |= 19490 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19491 break; 19492 default: 19493 // Use default resolved text alignment 19494 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19495 } 19496 break; 19497 case TEXT_ALIGNMENT_GRAVITY: 19498 case TEXT_ALIGNMENT_TEXT_START: 19499 case TEXT_ALIGNMENT_TEXT_END: 19500 case TEXT_ALIGNMENT_CENTER: 19501 case TEXT_ALIGNMENT_VIEW_START: 19502 case TEXT_ALIGNMENT_VIEW_END: 19503 // Resolved text alignment is the same as text alignment 19504 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19505 break; 19506 default: 19507 // Use default resolved text alignment 19508 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19509 } 19510 } else { 19511 // Use default resolved text alignment 19512 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19513 } 19514 19515 // Set the resolved 19516 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19517 return true; 19518 } 19519 19520 /** 19521 * Check if text alignment resolution can be done. 19522 * 19523 * @return true if text alignment resolution can be done otherwise return false. 19524 */ 19525 public boolean canResolveTextAlignment() { 19526 switch (getRawTextAlignment()) { 19527 case TEXT_DIRECTION_INHERIT: 19528 if (mParent != null) { 19529 try { 19530 return mParent.canResolveTextAlignment(); 19531 } catch (AbstractMethodError e) { 19532 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19533 " does not fully implement ViewParent", e); 19534 } 19535 } 19536 return false; 19537 19538 default: 19539 return true; 19540 } 19541 } 19542 19543 /** 19544 * Reset resolved text alignment. Text alignment will be resolved during a call to 19545 * {@link #onMeasure(int, int)}. 19546 * 19547 * @hide 19548 */ 19549 public void resetResolvedTextAlignment() { 19550 // Reset any previous text alignment resolution 19551 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19552 // Set to default 19553 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19554 } 19555 19556 /** 19557 * @return true if text alignment is inherited. 19558 * 19559 * @hide 19560 */ 19561 public boolean isTextAlignmentInherited() { 19562 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19563 } 19564 19565 /** 19566 * @return true if text alignment is resolved. 19567 */ 19568 public boolean isTextAlignmentResolved() { 19569 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19570 } 19571 19572 /** 19573 * Generate a value suitable for use in {@link #setId(int)}. 19574 * This value will not collide with ID values generated at build time by aapt for R.id. 19575 * 19576 * @return a generated ID value 19577 */ 19578 public static int generateViewId() { 19579 for (;;) { 19580 final int result = sNextGeneratedId.get(); 19581 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19582 int newValue = result + 1; 19583 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19584 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19585 return result; 19586 } 19587 } 19588 } 19589 19590 /** 19591 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19592 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19593 * a normal View or a ViewGroup with 19594 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19595 * @hide 19596 */ 19597 public void captureTransitioningViews(List<View> transitioningViews) { 19598 if (getVisibility() == View.VISIBLE) { 19599 transitioningViews.add(this); 19600 } 19601 } 19602 19603 /** 19604 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19605 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19606 * @hide 19607 */ 19608 public void findNamedViews(Map<String, View> namedElements) { 19609 if (getVisibility() == VISIBLE || mGhostView != null) { 19610 String transitionName = getTransitionName(); 19611 if (transitionName != null) { 19612 namedElements.put(transitionName, this); 19613 } 19614 } 19615 } 19616 19617 // 19618 // Properties 19619 // 19620 /** 19621 * A Property wrapper around the <code>alpha</code> functionality handled by the 19622 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19623 */ 19624 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19625 @Override 19626 public void setValue(View object, float value) { 19627 object.setAlpha(value); 19628 } 19629 19630 @Override 19631 public Float get(View object) { 19632 return object.getAlpha(); 19633 } 19634 }; 19635 19636 /** 19637 * A Property wrapper around the <code>translationX</code> functionality handled by the 19638 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19639 */ 19640 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19641 @Override 19642 public void setValue(View object, float value) { 19643 object.setTranslationX(value); 19644 } 19645 19646 @Override 19647 public Float get(View object) { 19648 return object.getTranslationX(); 19649 } 19650 }; 19651 19652 /** 19653 * A Property wrapper around the <code>translationY</code> functionality handled by the 19654 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19655 */ 19656 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19657 @Override 19658 public void setValue(View object, float value) { 19659 object.setTranslationY(value); 19660 } 19661 19662 @Override 19663 public Float get(View object) { 19664 return object.getTranslationY(); 19665 } 19666 }; 19667 19668 /** 19669 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19670 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19671 */ 19672 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19673 @Override 19674 public void setValue(View object, float value) { 19675 object.setTranslationZ(value); 19676 } 19677 19678 @Override 19679 public Float get(View object) { 19680 return object.getTranslationZ(); 19681 } 19682 }; 19683 19684 /** 19685 * A Property wrapper around the <code>x</code> functionality handled by the 19686 * {@link View#setX(float)} and {@link View#getX()} methods. 19687 */ 19688 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19689 @Override 19690 public void setValue(View object, float value) { 19691 object.setX(value); 19692 } 19693 19694 @Override 19695 public Float get(View object) { 19696 return object.getX(); 19697 } 19698 }; 19699 19700 /** 19701 * A Property wrapper around the <code>y</code> functionality handled by the 19702 * {@link View#setY(float)} and {@link View#getY()} methods. 19703 */ 19704 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19705 @Override 19706 public void setValue(View object, float value) { 19707 object.setY(value); 19708 } 19709 19710 @Override 19711 public Float get(View object) { 19712 return object.getY(); 19713 } 19714 }; 19715 19716 /** 19717 * A Property wrapper around the <code>z</code> functionality handled by the 19718 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19719 */ 19720 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19721 @Override 19722 public void setValue(View object, float value) { 19723 object.setZ(value); 19724 } 19725 19726 @Override 19727 public Float get(View object) { 19728 return object.getZ(); 19729 } 19730 }; 19731 19732 /** 19733 * A Property wrapper around the <code>rotation</code> functionality handled by the 19734 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19735 */ 19736 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19737 @Override 19738 public void setValue(View object, float value) { 19739 object.setRotation(value); 19740 } 19741 19742 @Override 19743 public Float get(View object) { 19744 return object.getRotation(); 19745 } 19746 }; 19747 19748 /** 19749 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19750 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19751 */ 19752 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19753 @Override 19754 public void setValue(View object, float value) { 19755 object.setRotationX(value); 19756 } 19757 19758 @Override 19759 public Float get(View object) { 19760 return object.getRotationX(); 19761 } 19762 }; 19763 19764 /** 19765 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19766 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19767 */ 19768 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19769 @Override 19770 public void setValue(View object, float value) { 19771 object.setRotationY(value); 19772 } 19773 19774 @Override 19775 public Float get(View object) { 19776 return object.getRotationY(); 19777 } 19778 }; 19779 19780 /** 19781 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19782 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19783 */ 19784 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19785 @Override 19786 public void setValue(View object, float value) { 19787 object.setScaleX(value); 19788 } 19789 19790 @Override 19791 public Float get(View object) { 19792 return object.getScaleX(); 19793 } 19794 }; 19795 19796 /** 19797 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19798 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19799 */ 19800 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19801 @Override 19802 public void setValue(View object, float value) { 19803 object.setScaleY(value); 19804 } 19805 19806 @Override 19807 public Float get(View object) { 19808 return object.getScaleY(); 19809 } 19810 }; 19811 19812 /** 19813 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19814 * Each MeasureSpec represents a requirement for either the width or the height. 19815 * A MeasureSpec is comprised of a size and a mode. There are three possible 19816 * modes: 19817 * <dl> 19818 * <dt>UNSPECIFIED</dt> 19819 * <dd> 19820 * The parent has not imposed any constraint on the child. It can be whatever size 19821 * it wants. 19822 * </dd> 19823 * 19824 * <dt>EXACTLY</dt> 19825 * <dd> 19826 * The parent has determined an exact size for the child. The child is going to be 19827 * given those bounds regardless of how big it wants to be. 19828 * </dd> 19829 * 19830 * <dt>AT_MOST</dt> 19831 * <dd> 19832 * The child can be as large as it wants up to the specified size. 19833 * </dd> 19834 * </dl> 19835 * 19836 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19837 * is provided to pack and unpack the <size, mode> tuple into the int. 19838 */ 19839 public static class MeasureSpec { 19840 private static final int MODE_SHIFT = 30; 19841 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19842 19843 /** 19844 * Measure specification mode: The parent has not imposed any constraint 19845 * on the child. It can be whatever size it wants. 19846 */ 19847 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19848 19849 /** 19850 * Measure specification mode: The parent has determined an exact size 19851 * for the child. The child is going to be given those bounds regardless 19852 * of how big it wants to be. 19853 */ 19854 public static final int EXACTLY = 1 << MODE_SHIFT; 19855 19856 /** 19857 * Measure specification mode: The child can be as large as it wants up 19858 * to the specified size. 19859 */ 19860 public static final int AT_MOST = 2 << MODE_SHIFT; 19861 19862 /** 19863 * Creates a measure specification based on the supplied size and mode. 19864 * 19865 * The mode must always be one of the following: 19866 * <ul> 19867 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19868 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19869 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19870 * </ul> 19871 * 19872 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19873 * implementation was such that the order of arguments did not matter 19874 * and overflow in either value could impact the resulting MeasureSpec. 19875 * {@link android.widget.RelativeLayout} was affected by this bug. 19876 * Apps targeting API levels greater than 17 will get the fixed, more strict 19877 * behavior.</p> 19878 * 19879 * @param size the size of the measure specification 19880 * @param mode the mode of the measure specification 19881 * @return the measure specification based on size and mode 19882 */ 19883 public static int makeMeasureSpec(int size, int mode) { 19884 if (sUseBrokenMakeMeasureSpec) { 19885 return size + mode; 19886 } else { 19887 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19888 } 19889 } 19890 19891 /** 19892 * Extracts the mode from the supplied measure specification. 19893 * 19894 * @param measureSpec the measure specification to extract the mode from 19895 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19896 * {@link android.view.View.MeasureSpec#AT_MOST} or 19897 * {@link android.view.View.MeasureSpec#EXACTLY} 19898 */ 19899 public static int getMode(int measureSpec) { 19900 return (measureSpec & MODE_MASK); 19901 } 19902 19903 /** 19904 * Extracts the size from the supplied measure specification. 19905 * 19906 * @param measureSpec the measure specification to extract the size from 19907 * @return the size in pixels defined in the supplied measure specification 19908 */ 19909 public static int getSize(int measureSpec) { 19910 return (measureSpec & ~MODE_MASK); 19911 } 19912 19913 static int adjust(int measureSpec, int delta) { 19914 final int mode = getMode(measureSpec); 19915 if (mode == UNSPECIFIED) { 19916 // No need to adjust size for UNSPECIFIED mode. 19917 return makeMeasureSpec(0, UNSPECIFIED); 19918 } 19919 int size = getSize(measureSpec) + delta; 19920 if (size < 0) { 19921 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19922 ") spec: " + toString(measureSpec) + " delta: " + delta); 19923 size = 0; 19924 } 19925 return makeMeasureSpec(size, mode); 19926 } 19927 19928 /** 19929 * Returns a String representation of the specified measure 19930 * specification. 19931 * 19932 * @param measureSpec the measure specification to convert to a String 19933 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19934 */ 19935 public static String toString(int measureSpec) { 19936 int mode = getMode(measureSpec); 19937 int size = getSize(measureSpec); 19938 19939 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19940 19941 if (mode == UNSPECIFIED) 19942 sb.append("UNSPECIFIED "); 19943 else if (mode == EXACTLY) 19944 sb.append("EXACTLY "); 19945 else if (mode == AT_MOST) 19946 sb.append("AT_MOST "); 19947 else 19948 sb.append(mode).append(" "); 19949 19950 sb.append(size); 19951 return sb.toString(); 19952 } 19953 } 19954 19955 private final class CheckForLongPress implements Runnable { 19956 private int mOriginalWindowAttachCount; 19957 19958 @Override 19959 public void run() { 19960 if (isPressed() && (mParent != null) 19961 && mOriginalWindowAttachCount == mWindowAttachCount) { 19962 if (performLongClick()) { 19963 mHasPerformedLongPress = true; 19964 } 19965 } 19966 } 19967 19968 public void rememberWindowAttachCount() { 19969 mOriginalWindowAttachCount = mWindowAttachCount; 19970 } 19971 } 19972 19973 private final class CheckForTap implements Runnable { 19974 public float x; 19975 public float y; 19976 19977 @Override 19978 public void run() { 19979 mPrivateFlags &= ~PFLAG_PREPRESSED; 19980 setPressed(true, x, y); 19981 checkForLongClick(ViewConfiguration.getTapTimeout()); 19982 } 19983 } 19984 19985 private final class PerformClick implements Runnable { 19986 @Override 19987 public void run() { 19988 performClick(); 19989 } 19990 } 19991 19992 /** @hide */ 19993 public void hackTurnOffWindowResizeAnim(boolean off) { 19994 mAttachInfo.mTurnOffWindowResizeAnim = off; 19995 } 19996 19997 /** 19998 * This method returns a ViewPropertyAnimator object, which can be used to animate 19999 * specific properties on this View. 20000 * 20001 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 20002 */ 20003 public ViewPropertyAnimator animate() { 20004 if (mAnimator == null) { 20005 mAnimator = new ViewPropertyAnimator(this); 20006 } 20007 return mAnimator; 20008 } 20009 20010 /** 20011 * Sets the name of the View to be used to identify Views in Transitions. 20012 * Names should be unique in the View hierarchy. 20013 * 20014 * @param transitionName The name of the View to uniquely identify it for Transitions. 20015 */ 20016 public final void setTransitionName(String transitionName) { 20017 mTransitionName = transitionName; 20018 } 20019 20020 /** 20021 * Returns the name of the View to be used to identify Views in Transitions. 20022 * Names should be unique in the View hierarchy. 20023 * 20024 * <p>This returns null if the View has not been given a name.</p> 20025 * 20026 * @return The name used of the View to be used to identify Views in Transitions or null 20027 * if no name has been given. 20028 */ 20029 @ViewDebug.ExportedProperty 20030 public String getTransitionName() { 20031 return mTransitionName; 20032 } 20033 20034 /** 20035 * Interface definition for a callback to be invoked when a hardware key event is 20036 * dispatched to this view. The callback will be invoked before the key event is 20037 * given to the view. This is only useful for hardware keyboards; a software input 20038 * method has no obligation to trigger this listener. 20039 */ 20040 public interface OnKeyListener { 20041 /** 20042 * Called when a hardware key is dispatched to a view. This allows listeners to 20043 * get a chance to respond before the target view. 20044 * <p>Key presses in software keyboards will generally NOT trigger this method, 20045 * although some may elect to do so in some situations. Do not assume a 20046 * software input method has to be key-based; even if it is, it may use key presses 20047 * in a different way than you expect, so there is no way to reliably catch soft 20048 * input key presses. 20049 * 20050 * @param v The view the key has been dispatched to. 20051 * @param keyCode The code for the physical key that was pressed 20052 * @param event The KeyEvent object containing full information about 20053 * the event. 20054 * @return True if the listener has consumed the event, false otherwise. 20055 */ 20056 boolean onKey(View v, int keyCode, KeyEvent event); 20057 } 20058 20059 /** 20060 * Interface definition for a callback to be invoked when a touch event is 20061 * dispatched to this view. The callback will be invoked before the touch 20062 * event is given to the view. 20063 */ 20064 public interface OnTouchListener { 20065 /** 20066 * Called when a touch event is dispatched to a view. This allows listeners to 20067 * get a chance to respond before the target view. 20068 * 20069 * @param v The view the touch event has been dispatched to. 20070 * @param event The MotionEvent object containing full information about 20071 * the event. 20072 * @return True if the listener has consumed the event, false otherwise. 20073 */ 20074 boolean onTouch(View v, MotionEvent event); 20075 } 20076 20077 /** 20078 * Interface definition for a callback to be invoked when a hover event is 20079 * dispatched to this view. The callback will be invoked before the hover 20080 * event is given to the view. 20081 */ 20082 public interface OnHoverListener { 20083 /** 20084 * Called when a hover event is dispatched to a view. This allows listeners to 20085 * get a chance to respond before the target view. 20086 * 20087 * @param v The view the hover event has been dispatched to. 20088 * @param event The MotionEvent object containing full information about 20089 * the event. 20090 * @return True if the listener has consumed the event, false otherwise. 20091 */ 20092 boolean onHover(View v, MotionEvent event); 20093 } 20094 20095 /** 20096 * Interface definition for a callback to be invoked when a generic motion event is 20097 * dispatched to this view. The callback will be invoked before the generic motion 20098 * event is given to the view. 20099 */ 20100 public interface OnGenericMotionListener { 20101 /** 20102 * Called when a generic motion event is dispatched to a view. This allows listeners to 20103 * get a chance to respond before the target view. 20104 * 20105 * @param v The view the generic motion event has been dispatched to. 20106 * @param event The MotionEvent object containing full information about 20107 * the event. 20108 * @return True if the listener has consumed the event, false otherwise. 20109 */ 20110 boolean onGenericMotion(View v, MotionEvent event); 20111 } 20112 20113 /** 20114 * Interface definition for a callback to be invoked when a view has been clicked and held. 20115 */ 20116 public interface OnLongClickListener { 20117 /** 20118 * Called when a view has been clicked and held. 20119 * 20120 * @param v The view that was clicked and held. 20121 * 20122 * @return true if the callback consumed the long click, false otherwise. 20123 */ 20124 boolean onLongClick(View v); 20125 } 20126 20127 /** 20128 * Interface definition for a callback to be invoked when a drag is being dispatched 20129 * to this view. The callback will be invoked before the hosting view's own 20130 * onDrag(event) method. If the listener wants to fall back to the hosting view's 20131 * onDrag(event) behavior, it should return 'false' from this callback. 20132 * 20133 * <div class="special reference"> 20134 * <h3>Developer Guides</h3> 20135 * <p>For a guide to implementing drag and drop features, read the 20136 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20137 * </div> 20138 */ 20139 public interface OnDragListener { 20140 /** 20141 * Called when a drag event is dispatched to a view. This allows listeners 20142 * to get a chance to override base View behavior. 20143 * 20144 * @param v The View that received the drag event. 20145 * @param event The {@link android.view.DragEvent} object for the drag event. 20146 * @return {@code true} if the drag event was handled successfully, or {@code false} 20147 * if the drag event was not handled. Note that {@code false} will trigger the View 20148 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 20149 */ 20150 boolean onDrag(View v, DragEvent event); 20151 } 20152 20153 /** 20154 * Interface definition for a callback to be invoked when the focus state of 20155 * a view changed. 20156 */ 20157 public interface OnFocusChangeListener { 20158 /** 20159 * Called when the focus state of a view has changed. 20160 * 20161 * @param v The view whose state has changed. 20162 * @param hasFocus The new focus state of v. 20163 */ 20164 void onFocusChange(View v, boolean hasFocus); 20165 } 20166 20167 /** 20168 * Interface definition for a callback to be invoked when a view is clicked. 20169 */ 20170 public interface OnClickListener { 20171 /** 20172 * Called when a view has been clicked. 20173 * 20174 * @param v The view that was clicked. 20175 */ 20176 void onClick(View v); 20177 } 20178 20179 /** 20180 * Interface definition for a callback to be invoked when the context menu 20181 * for this view is being built. 20182 */ 20183 public interface OnCreateContextMenuListener { 20184 /** 20185 * Called when the context menu for this view is being built. It is not 20186 * safe to hold onto the menu after this method returns. 20187 * 20188 * @param menu The context menu that is being built 20189 * @param v The view for which the context menu is being built 20190 * @param menuInfo Extra information about the item for which the 20191 * context menu should be shown. This information will vary 20192 * depending on the class of v. 20193 */ 20194 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 20195 } 20196 20197 /** 20198 * Interface definition for a callback to be invoked when the status bar changes 20199 * visibility. This reports <strong>global</strong> changes to the system UI 20200 * state, not what the application is requesting. 20201 * 20202 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 20203 */ 20204 public interface OnSystemUiVisibilityChangeListener { 20205 /** 20206 * Called when the status bar changes visibility because of a call to 20207 * {@link View#setSystemUiVisibility(int)}. 20208 * 20209 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20210 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 20211 * This tells you the <strong>global</strong> state of these UI visibility 20212 * flags, not what your app is currently applying. 20213 */ 20214 public void onSystemUiVisibilityChange(int visibility); 20215 } 20216 20217 /** 20218 * Interface definition for a callback to be invoked when this view is attached 20219 * or detached from its window. 20220 */ 20221 public interface OnAttachStateChangeListener { 20222 /** 20223 * Called when the view is attached to a window. 20224 * @param v The view that was attached 20225 */ 20226 public void onViewAttachedToWindow(View v); 20227 /** 20228 * Called when the view is detached from a window. 20229 * @param v The view that was detached 20230 */ 20231 public void onViewDetachedFromWindow(View v); 20232 } 20233 20234 /** 20235 * Listener for applying window insets on a view in a custom way. 20236 * 20237 * <p>Apps may choose to implement this interface if they want to apply custom policy 20238 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 20239 * is set, its 20240 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20241 * method will be called instead of the View's own 20242 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20243 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20244 * the View's normal behavior as part of its own.</p> 20245 */ 20246 public interface OnApplyWindowInsetsListener { 20247 /** 20248 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20249 * on a View, this listener method will be called instead of the view's own 20250 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20251 * 20252 * @param v The view applying window insets 20253 * @param insets The insets to apply 20254 * @return The insets supplied, minus any insets that were consumed 20255 */ 20256 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20257 } 20258 20259 private final class UnsetPressedState implements Runnable { 20260 @Override 20261 public void run() { 20262 setPressed(false); 20263 } 20264 } 20265 20266 /** 20267 * Base class for derived classes that want to save and restore their own 20268 * state in {@link android.view.View#onSaveInstanceState()}. 20269 */ 20270 public static class BaseSavedState extends AbsSavedState { 20271 /** 20272 * Constructor used when reading from a parcel. Reads the state of the superclass. 20273 * 20274 * @param source 20275 */ 20276 public BaseSavedState(Parcel source) { 20277 super(source); 20278 } 20279 20280 /** 20281 * Constructor called by derived classes when creating their SavedState objects 20282 * 20283 * @param superState The state of the superclass of this view 20284 */ 20285 public BaseSavedState(Parcelable superState) { 20286 super(superState); 20287 } 20288 20289 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20290 new Parcelable.Creator<BaseSavedState>() { 20291 public BaseSavedState createFromParcel(Parcel in) { 20292 return new BaseSavedState(in); 20293 } 20294 20295 public BaseSavedState[] newArray(int size) { 20296 return new BaseSavedState[size]; 20297 } 20298 }; 20299 } 20300 20301 /** 20302 * A set of information given to a view when it is attached to its parent 20303 * window. 20304 */ 20305 final static class AttachInfo { 20306 interface Callbacks { 20307 void playSoundEffect(int effectId); 20308 boolean performHapticFeedback(int effectId, boolean always); 20309 } 20310 20311 /** 20312 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20313 * to a Handler. This class contains the target (View) to invalidate and 20314 * the coordinates of the dirty rectangle. 20315 * 20316 * For performance purposes, this class also implements a pool of up to 20317 * POOL_LIMIT objects that get reused. This reduces memory allocations 20318 * whenever possible. 20319 */ 20320 static class InvalidateInfo { 20321 private static final int POOL_LIMIT = 10; 20322 20323 private static final SynchronizedPool<InvalidateInfo> sPool = 20324 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20325 20326 View target; 20327 20328 int left; 20329 int top; 20330 int right; 20331 int bottom; 20332 20333 public static InvalidateInfo obtain() { 20334 InvalidateInfo instance = sPool.acquire(); 20335 return (instance != null) ? instance : new InvalidateInfo(); 20336 } 20337 20338 public void recycle() { 20339 target = null; 20340 sPool.release(this); 20341 } 20342 } 20343 20344 final IWindowSession mSession; 20345 20346 final IWindow mWindow; 20347 20348 final IBinder mWindowToken; 20349 20350 final Display mDisplay; 20351 20352 final Callbacks mRootCallbacks; 20353 20354 IWindowId mIWindowId; 20355 WindowId mWindowId; 20356 20357 /** 20358 * The top view of the hierarchy. 20359 */ 20360 View mRootView; 20361 20362 IBinder mPanelParentWindowToken; 20363 20364 boolean mHardwareAccelerated; 20365 boolean mHardwareAccelerationRequested; 20366 HardwareRenderer mHardwareRenderer; 20367 List<RenderNode> mPendingAnimatingRenderNodes; 20368 20369 /** 20370 * The state of the display to which the window is attached, as reported 20371 * by {@link Display#getState()}. Note that the display state constants 20372 * declared by {@link Display} do not exactly line up with the screen state 20373 * constants declared by {@link View} (there are more display states than 20374 * screen states). 20375 */ 20376 int mDisplayState = Display.STATE_UNKNOWN; 20377 20378 /** 20379 * Scale factor used by the compatibility mode 20380 */ 20381 float mApplicationScale; 20382 20383 /** 20384 * Indicates whether the application is in compatibility mode 20385 */ 20386 boolean mScalingRequired; 20387 20388 /** 20389 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20390 */ 20391 boolean mTurnOffWindowResizeAnim; 20392 20393 /** 20394 * Left position of this view's window 20395 */ 20396 int mWindowLeft; 20397 20398 /** 20399 * Top position of this view's window 20400 */ 20401 int mWindowTop; 20402 20403 /** 20404 * Indicates whether views need to use 32-bit drawing caches 20405 */ 20406 boolean mUse32BitDrawingCache; 20407 20408 /** 20409 * For windows that are full-screen but using insets to layout inside 20410 * of the screen areas, these are the current insets to appear inside 20411 * the overscan area of the display. 20412 */ 20413 final Rect mOverscanInsets = new Rect(); 20414 20415 /** 20416 * For windows that are full-screen but using insets to layout inside 20417 * of the screen decorations, these are the current insets for the 20418 * content of the window. 20419 */ 20420 final Rect mContentInsets = new Rect(); 20421 20422 /** 20423 * For windows that are full-screen but using insets to layout inside 20424 * of the screen decorations, these are the current insets for the 20425 * actual visible parts of the window. 20426 */ 20427 final Rect mVisibleInsets = new Rect(); 20428 20429 /** 20430 * For windows that are full-screen but using insets to layout inside 20431 * of the screen decorations, these are the current insets for the 20432 * stable system windows. 20433 */ 20434 final Rect mStableInsets = new Rect(); 20435 20436 /** 20437 * The internal insets given by this window. This value is 20438 * supplied by the client (through 20439 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20440 * be given to the window manager when changed to be used in laying 20441 * out windows behind it. 20442 */ 20443 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20444 = new ViewTreeObserver.InternalInsetsInfo(); 20445 20446 /** 20447 * Set to true when mGivenInternalInsets is non-empty. 20448 */ 20449 boolean mHasNonEmptyGivenInternalInsets; 20450 20451 /** 20452 * All views in the window's hierarchy that serve as scroll containers, 20453 * used to determine if the window can be resized or must be panned 20454 * to adjust for a soft input area. 20455 */ 20456 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20457 20458 final KeyEvent.DispatcherState mKeyDispatchState 20459 = new KeyEvent.DispatcherState(); 20460 20461 /** 20462 * Indicates whether the view's window currently has the focus. 20463 */ 20464 boolean mHasWindowFocus; 20465 20466 /** 20467 * The current visibility of the window. 20468 */ 20469 int mWindowVisibility; 20470 20471 /** 20472 * Indicates the time at which drawing started to occur. 20473 */ 20474 long mDrawingTime; 20475 20476 /** 20477 * Indicates whether or not ignoring the DIRTY_MASK flags. 20478 */ 20479 boolean mIgnoreDirtyState; 20480 20481 /** 20482 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20483 * to avoid clearing that flag prematurely. 20484 */ 20485 boolean mSetIgnoreDirtyState = false; 20486 20487 /** 20488 * Indicates whether the view's window is currently in touch mode. 20489 */ 20490 boolean mInTouchMode; 20491 20492 /** 20493 * Indicates whether the view has requested unbuffered input dispatching for the current 20494 * event stream. 20495 */ 20496 boolean mUnbufferedDispatchRequested; 20497 20498 /** 20499 * Indicates that ViewAncestor should trigger a global layout change 20500 * the next time it performs a traversal 20501 */ 20502 boolean mRecomputeGlobalAttributes; 20503 20504 /** 20505 * Always report new attributes at next traversal. 20506 */ 20507 boolean mForceReportNewAttributes; 20508 20509 /** 20510 * Set during a traveral if any views want to keep the screen on. 20511 */ 20512 boolean mKeepScreenOn; 20513 20514 /** 20515 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20516 */ 20517 int mSystemUiVisibility; 20518 20519 /** 20520 * Hack to force certain system UI visibility flags to be cleared. 20521 */ 20522 int mDisabledSystemUiVisibility; 20523 20524 /** 20525 * Last global system UI visibility reported by the window manager. 20526 */ 20527 int mGlobalSystemUiVisibility; 20528 20529 /** 20530 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20531 * attached. 20532 */ 20533 boolean mHasSystemUiListeners; 20534 20535 /** 20536 * Set if the window has requested to extend into the overscan region 20537 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20538 */ 20539 boolean mOverscanRequested; 20540 20541 /** 20542 * Set if the visibility of any views has changed. 20543 */ 20544 boolean mViewVisibilityChanged; 20545 20546 /** 20547 * Set to true if a view has been scrolled. 20548 */ 20549 boolean mViewScrollChanged; 20550 20551 /** 20552 * Set to true if high contrast mode enabled 20553 */ 20554 boolean mHighContrastText; 20555 20556 /** 20557 * Global to the view hierarchy used as a temporary for dealing with 20558 * x/y points in the transparent region computations. 20559 */ 20560 final int[] mTransparentLocation = new int[2]; 20561 20562 /** 20563 * Global to the view hierarchy used as a temporary for dealing with 20564 * x/y points in the ViewGroup.invalidateChild implementation. 20565 */ 20566 final int[] mInvalidateChildLocation = new int[2]; 20567 20568 /** 20569 * Global to the view hierarchy used as a temporary for dealng with 20570 * computing absolute on-screen location. 20571 */ 20572 final int[] mTmpLocation = new int[2]; 20573 20574 /** 20575 * Global to the view hierarchy used as a temporary for dealing with 20576 * x/y location when view is transformed. 20577 */ 20578 final float[] mTmpTransformLocation = new float[2]; 20579 20580 /** 20581 * The view tree observer used to dispatch global events like 20582 * layout, pre-draw, touch mode change, etc. 20583 */ 20584 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20585 20586 /** 20587 * A Canvas used by the view hierarchy to perform bitmap caching. 20588 */ 20589 Canvas mCanvas; 20590 20591 /** 20592 * The view root impl. 20593 */ 20594 final ViewRootImpl mViewRootImpl; 20595 20596 /** 20597 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20598 * handler can be used to pump events in the UI events queue. 20599 */ 20600 final Handler mHandler; 20601 20602 /** 20603 * Temporary for use in computing invalidate rectangles while 20604 * calling up the hierarchy. 20605 */ 20606 final Rect mTmpInvalRect = new Rect(); 20607 20608 /** 20609 * Temporary for use in computing hit areas with transformed views 20610 */ 20611 final RectF mTmpTransformRect = new RectF(); 20612 20613 /** 20614 * Temporary for use in computing hit areas with transformed views 20615 */ 20616 final RectF mTmpTransformRect1 = new RectF(); 20617 20618 /** 20619 * Temporary list of rectanges. 20620 */ 20621 final List<RectF> mTmpRectList = new ArrayList<>(); 20622 20623 /** 20624 * Temporary for use in transforming invalidation rect 20625 */ 20626 final Matrix mTmpMatrix = new Matrix(); 20627 20628 /** 20629 * Temporary for use in transforming invalidation rect 20630 */ 20631 final Transformation mTmpTransformation = new Transformation(); 20632 20633 /** 20634 * Temporary for use in querying outlines from OutlineProviders 20635 */ 20636 final Outline mTmpOutline = new Outline(); 20637 20638 /** 20639 * Temporary list for use in collecting focusable descendents of a view. 20640 */ 20641 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20642 20643 /** 20644 * The id of the window for accessibility purposes. 20645 */ 20646 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20647 20648 /** 20649 * Flags related to accessibility processing. 20650 * 20651 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20652 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20653 */ 20654 int mAccessibilityFetchFlags; 20655 20656 /** 20657 * The drawable for highlighting accessibility focus. 20658 */ 20659 Drawable mAccessibilityFocusDrawable; 20660 20661 /** 20662 * Show where the margins, bounds and layout bounds are for each view. 20663 */ 20664 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20665 20666 /** 20667 * Point used to compute visible regions. 20668 */ 20669 final Point mPoint = new Point(); 20670 20671 /** 20672 * Used to track which View originated a requestLayout() call, used when 20673 * requestLayout() is called during layout. 20674 */ 20675 View mViewRequestingLayout; 20676 20677 /** 20678 * Creates a new set of attachment information with the specified 20679 * events handler and thread. 20680 * 20681 * @param handler the events handler the view must use 20682 */ 20683 AttachInfo(IWindowSession session, IWindow window, Display display, 20684 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20685 mSession = session; 20686 mWindow = window; 20687 mWindowToken = window.asBinder(); 20688 mDisplay = display; 20689 mViewRootImpl = viewRootImpl; 20690 mHandler = handler; 20691 mRootCallbacks = effectPlayer; 20692 } 20693 } 20694 20695 /** 20696 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20697 * is supported. This avoids keeping too many unused fields in most 20698 * instances of View.</p> 20699 */ 20700 private static class ScrollabilityCache implements Runnable { 20701 20702 /** 20703 * Scrollbars are not visible 20704 */ 20705 public static final int OFF = 0; 20706 20707 /** 20708 * Scrollbars are visible 20709 */ 20710 public static final int ON = 1; 20711 20712 /** 20713 * Scrollbars are fading away 20714 */ 20715 public static final int FADING = 2; 20716 20717 public boolean fadeScrollBars; 20718 20719 public int fadingEdgeLength; 20720 public int scrollBarDefaultDelayBeforeFade; 20721 public int scrollBarFadeDuration; 20722 20723 public int scrollBarSize; 20724 public ScrollBarDrawable scrollBar; 20725 public float[] interpolatorValues; 20726 public View host; 20727 20728 public final Paint paint; 20729 public final Matrix matrix; 20730 public Shader shader; 20731 20732 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20733 20734 private static final float[] OPAQUE = { 255 }; 20735 private static final float[] TRANSPARENT = { 0.0f }; 20736 20737 /** 20738 * When fading should start. This time moves into the future every time 20739 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20740 */ 20741 public long fadeStartTime; 20742 20743 20744 /** 20745 * The current state of the scrollbars: ON, OFF, or FADING 20746 */ 20747 public int state = OFF; 20748 20749 private int mLastColor; 20750 20751 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20752 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20753 scrollBarSize = configuration.getScaledScrollBarSize(); 20754 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20755 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20756 20757 paint = new Paint(); 20758 matrix = new Matrix(); 20759 // use use a height of 1, and then wack the matrix each time we 20760 // actually use it. 20761 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20762 paint.setShader(shader); 20763 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20764 20765 this.host = host; 20766 } 20767 20768 public void setFadeColor(int color) { 20769 if (color != mLastColor) { 20770 mLastColor = color; 20771 20772 if (color != 0) { 20773 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20774 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20775 paint.setShader(shader); 20776 // Restore the default transfer mode (src_over) 20777 paint.setXfermode(null); 20778 } else { 20779 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20780 paint.setShader(shader); 20781 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20782 } 20783 } 20784 } 20785 20786 public void run() { 20787 long now = AnimationUtils.currentAnimationTimeMillis(); 20788 if (now >= fadeStartTime) { 20789 20790 // the animation fades the scrollbars out by changing 20791 // the opacity (alpha) from fully opaque to fully 20792 // transparent 20793 int nextFrame = (int) now; 20794 int framesCount = 0; 20795 20796 Interpolator interpolator = scrollBarInterpolator; 20797 20798 // Start opaque 20799 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20800 20801 // End transparent 20802 nextFrame += scrollBarFadeDuration; 20803 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20804 20805 state = FADING; 20806 20807 // Kick off the fade animation 20808 host.invalidate(true); 20809 } 20810 } 20811 } 20812 20813 /** 20814 * Resuable callback for sending 20815 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20816 */ 20817 private class SendViewScrolledAccessibilityEvent implements Runnable { 20818 public volatile boolean mIsPending; 20819 20820 public void run() { 20821 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20822 mIsPending = false; 20823 } 20824 } 20825 20826 /** 20827 * <p> 20828 * This class represents a delegate that can be registered in a {@link View} 20829 * to enhance accessibility support via composition rather via inheritance. 20830 * It is specifically targeted to widget developers that extend basic View 20831 * classes i.e. classes in package android.view, that would like their 20832 * applications to be backwards compatible. 20833 * </p> 20834 * <div class="special reference"> 20835 * <h3>Developer Guides</h3> 20836 * <p>For more information about making applications accessible, read the 20837 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20838 * developer guide.</p> 20839 * </div> 20840 * <p> 20841 * A scenario in which a developer would like to use an accessibility delegate 20842 * is overriding a method introduced in a later API version then the minimal API 20843 * version supported by the application. For example, the method 20844 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20845 * in API version 4 when the accessibility APIs were first introduced. If a 20846 * developer would like his application to run on API version 4 devices (assuming 20847 * all other APIs used by the application are version 4 or lower) and take advantage 20848 * of this method, instead of overriding the method which would break the application's 20849 * backwards compatibility, he can override the corresponding method in this 20850 * delegate and register the delegate in the target View if the API version of 20851 * the system is high enough i.e. the API version is same or higher to the API 20852 * version that introduced 20853 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20854 * </p> 20855 * <p> 20856 * Here is an example implementation: 20857 * </p> 20858 * <code><pre><p> 20859 * if (Build.VERSION.SDK_INT >= 14) { 20860 * // If the API version is equal of higher than the version in 20861 * // which onInitializeAccessibilityNodeInfo was introduced we 20862 * // register a delegate with a customized implementation. 20863 * View view = findViewById(R.id.view_id); 20864 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20865 * public void onInitializeAccessibilityNodeInfo(View host, 20866 * AccessibilityNodeInfo info) { 20867 * // Let the default implementation populate the info. 20868 * super.onInitializeAccessibilityNodeInfo(host, info); 20869 * // Set some other information. 20870 * info.setEnabled(host.isEnabled()); 20871 * } 20872 * }); 20873 * } 20874 * </code></pre></p> 20875 * <p> 20876 * This delegate contains methods that correspond to the accessibility methods 20877 * in View. If a delegate has been specified the implementation in View hands 20878 * off handling to the corresponding method in this delegate. The default 20879 * implementation the delegate methods behaves exactly as the corresponding 20880 * method in View for the case of no accessibility delegate been set. Hence, 20881 * to customize the behavior of a View method, clients can override only the 20882 * corresponding delegate method without altering the behavior of the rest 20883 * accessibility related methods of the host view. 20884 * </p> 20885 */ 20886 public static class AccessibilityDelegate { 20887 20888 /** 20889 * Sends an accessibility event of the given type. If accessibility is not 20890 * enabled this method has no effect. 20891 * <p> 20892 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20893 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20894 * been set. 20895 * </p> 20896 * 20897 * @param host The View hosting the delegate. 20898 * @param eventType The type of the event to send. 20899 * 20900 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20901 */ 20902 public void sendAccessibilityEvent(View host, int eventType) { 20903 host.sendAccessibilityEventInternal(eventType); 20904 } 20905 20906 /** 20907 * Performs the specified accessibility action on the view. For 20908 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20909 * <p> 20910 * The default implementation behaves as 20911 * {@link View#performAccessibilityAction(int, Bundle) 20912 * View#performAccessibilityAction(int, Bundle)} for the case of 20913 * no accessibility delegate been set. 20914 * </p> 20915 * 20916 * @param action The action to perform. 20917 * @return Whether the action was performed. 20918 * 20919 * @see View#performAccessibilityAction(int, Bundle) 20920 * View#performAccessibilityAction(int, Bundle) 20921 */ 20922 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20923 return host.performAccessibilityActionInternal(action, args); 20924 } 20925 20926 /** 20927 * Sends an accessibility event. This method behaves exactly as 20928 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20929 * empty {@link AccessibilityEvent} and does not perform a check whether 20930 * accessibility is enabled. 20931 * <p> 20932 * The default implementation behaves as 20933 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20934 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20935 * the case of no accessibility delegate been set. 20936 * </p> 20937 * 20938 * @param host The View hosting the delegate. 20939 * @param event The event to send. 20940 * 20941 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20942 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20943 */ 20944 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20945 host.sendAccessibilityEventUncheckedInternal(event); 20946 } 20947 20948 /** 20949 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20950 * to its children for adding their text content to the event. 20951 * <p> 20952 * The default implementation behaves as 20953 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20954 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20955 * the case of no accessibility delegate been set. 20956 * </p> 20957 * 20958 * @param host The View hosting the delegate. 20959 * @param event The event. 20960 * @return True if the event population was completed. 20961 * 20962 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20963 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20964 */ 20965 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20966 return host.dispatchPopulateAccessibilityEventInternal(event); 20967 } 20968 20969 /** 20970 * Gives a chance to the host View to populate the accessibility event with its 20971 * text content. 20972 * <p> 20973 * The default implementation behaves as 20974 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20975 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20976 * the case of no accessibility delegate been set. 20977 * </p> 20978 * 20979 * @param host The View hosting the delegate. 20980 * @param event The accessibility event which to populate. 20981 * 20982 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20983 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20984 */ 20985 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20986 host.onPopulateAccessibilityEventInternal(event); 20987 } 20988 20989 /** 20990 * Initializes an {@link AccessibilityEvent} with information about the 20991 * the host View which is the event source. 20992 * <p> 20993 * The default implementation behaves as 20994 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20995 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20996 * the case of no accessibility delegate been set. 20997 * </p> 20998 * 20999 * @param host The View hosting the delegate. 21000 * @param event The event to initialize. 21001 * 21002 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 21003 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 21004 */ 21005 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 21006 host.onInitializeAccessibilityEventInternal(event); 21007 } 21008 21009 /** 21010 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 21011 * <p> 21012 * The default implementation behaves as 21013 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21014 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 21015 * the case of no accessibility delegate been set. 21016 * </p> 21017 * 21018 * @param host The View hosting the delegate. 21019 * @param info The instance to initialize. 21020 * 21021 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21022 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 21023 */ 21024 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 21025 host.onInitializeAccessibilityNodeInfoInternal(info); 21026 } 21027 21028 /** 21029 * Called when a child of the host View has requested sending an 21030 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 21031 * to augment the event. 21032 * <p> 21033 * The default implementation behaves as 21034 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21035 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 21036 * the case of no accessibility delegate been set. 21037 * </p> 21038 * 21039 * @param host The View hosting the delegate. 21040 * @param child The child which requests sending the event. 21041 * @param event The event to be sent. 21042 * @return True if the event should be sent 21043 * 21044 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21045 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 21046 */ 21047 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 21048 AccessibilityEvent event) { 21049 return host.onRequestSendAccessibilityEventInternal(child, event); 21050 } 21051 21052 /** 21053 * Gets the provider for managing a virtual view hierarchy rooted at this View 21054 * and reported to {@link android.accessibilityservice.AccessibilityService}s 21055 * that explore the window content. 21056 * <p> 21057 * The default implementation behaves as 21058 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 21059 * the case of no accessibility delegate been set. 21060 * </p> 21061 * 21062 * @return The provider. 21063 * 21064 * @see AccessibilityNodeProvider 21065 */ 21066 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 21067 return null; 21068 } 21069 21070 /** 21071 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 21072 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 21073 * This method is responsible for obtaining an accessibility node info from a 21074 * pool of reusable instances and calling 21075 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 21076 * view to initialize the former. 21077 * <p> 21078 * <strong>Note:</strong> The client is responsible for recycling the obtained 21079 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 21080 * creation. 21081 * </p> 21082 * <p> 21083 * The default implementation behaves as 21084 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 21085 * the case of no accessibility delegate been set. 21086 * </p> 21087 * @return A populated {@link AccessibilityNodeInfo}. 21088 * 21089 * @see AccessibilityNodeInfo 21090 * 21091 * @hide 21092 */ 21093 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 21094 return host.createAccessibilityNodeInfoInternal(); 21095 } 21096 } 21097 21098 private class MatchIdPredicate implements Predicate<View> { 21099 public int mId; 21100 21101 @Override 21102 public boolean apply(View view) { 21103 return (view.mID == mId); 21104 } 21105 } 21106 21107 private class MatchLabelForPredicate implements Predicate<View> { 21108 private int mLabeledId; 21109 21110 @Override 21111 public boolean apply(View view) { 21112 return (view.mLabelForId == mLabeledId); 21113 } 21114 } 21115 21116 private class SendViewStateChangedAccessibilityEvent implements Runnable { 21117 private int mChangeTypes = 0; 21118 private boolean mPosted; 21119 private boolean mPostedWithDelay; 21120 private long mLastEventTimeMillis; 21121 21122 @Override 21123 public void run() { 21124 mPosted = false; 21125 mPostedWithDelay = false; 21126 mLastEventTimeMillis = SystemClock.uptimeMillis(); 21127 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 21128 final AccessibilityEvent event = AccessibilityEvent.obtain(); 21129 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 21130 event.setContentChangeTypes(mChangeTypes); 21131 sendAccessibilityEventUnchecked(event); 21132 } 21133 mChangeTypes = 0; 21134 } 21135 21136 public void runOrPost(int changeType) { 21137 mChangeTypes |= changeType; 21138 21139 // If this is a live region or the child of a live region, collect 21140 // all events from this frame and send them on the next frame. 21141 if (inLiveRegion()) { 21142 // If we're already posted with a delay, remove that. 21143 if (mPostedWithDelay) { 21144 removeCallbacks(this); 21145 mPostedWithDelay = false; 21146 } 21147 // Only post if we're not already posted. 21148 if (!mPosted) { 21149 post(this); 21150 mPosted = true; 21151 } 21152 return; 21153 } 21154 21155 if (mPosted) { 21156 return; 21157 } 21158 21159 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 21160 final long minEventIntevalMillis = 21161 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 21162 if (timeSinceLastMillis >= minEventIntevalMillis) { 21163 removeCallbacks(this); 21164 run(); 21165 } else { 21166 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 21167 mPostedWithDelay = true; 21168 } 21169 } 21170 } 21171 21172 private boolean inLiveRegion() { 21173 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21174 return true; 21175 } 21176 21177 ViewParent parent = getParent(); 21178 while (parent instanceof View) { 21179 if (((View) parent).getAccessibilityLiveRegion() 21180 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21181 return true; 21182 } 21183 parent = parent.getParent(); 21184 } 21185 21186 return false; 21187 } 21188 21189 /** 21190 * Dump all private flags in readable format, useful for documentation and 21191 * sanity checking. 21192 */ 21193 private static void dumpFlags() { 21194 final HashMap<String, String> found = Maps.newHashMap(); 21195 try { 21196 for (Field field : View.class.getDeclaredFields()) { 21197 final int modifiers = field.getModifiers(); 21198 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 21199 if (field.getType().equals(int.class)) { 21200 final int value = field.getInt(null); 21201 dumpFlag(found, field.getName(), value); 21202 } else if (field.getType().equals(int[].class)) { 21203 final int[] values = (int[]) field.get(null); 21204 for (int i = 0; i < values.length; i++) { 21205 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 21206 } 21207 } 21208 } 21209 } 21210 } catch (IllegalAccessException e) { 21211 throw new RuntimeException(e); 21212 } 21213 21214 final ArrayList<String> keys = Lists.newArrayList(); 21215 keys.addAll(found.keySet()); 21216 Collections.sort(keys); 21217 for (String key : keys) { 21218 Log.d(VIEW_LOG_TAG, found.get(key)); 21219 } 21220 } 21221 21222 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 21223 // Sort flags by prefix, then by bits, always keeping unique keys 21224 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 21225 final int prefix = name.indexOf('_'); 21226 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 21227 final String output = bits + " " + name; 21228 found.put(key, output); 21229 } 21230} 21231